repo_name
stringclasses
6 values
pr_number
int64
512
78.9k
pr_title
stringlengths
3
144
pr_description
stringlengths
0
30.3k
author
stringlengths
2
21
date_created
unknown
date_merged
unknown
previous_commit
stringlengths
40
40
pr_commit
stringlengths
40
40
query
stringlengths
17
30.4k
filepath
stringlengths
9
210
before_content
stringlengths
0
112M
after_content
stringlengths
0
112M
label
int64
-1
1
dotnet/roslyn
56,015
Remove obsolete APIs
Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
tmat
"2021-08-30T20:53:26Z"
"2021-09-02T16:56:01Z"
bdf1025480ad91f8db054959553257746f58f527
e782ce78f087060a3bc51737d3f07a6d102fb7b1
Remove obsolete APIs. Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
./src/Workspaces/Core/Portable/Remote/RemoteServiceName.cs
// 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. using System; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Remote { /// <summary> /// Abstract the name of a remote service. /// </summary> /// <remarks> /// Allows partner teams to specify bitness-specific service name, while we can use bitness agnostic id for well-known services. /// TODO: Update LUT and SBD to use well-known ids and remove this abstraction (https://github.com/dotnet/roslyn/issues/44327). /// </remarks> internal readonly struct RemoteServiceName : IEquatable<RemoteServiceName> { internal const string Prefix = "roslyn"; internal const string Suffix64 = "64"; internal const string SuffixServerGC = "S"; internal const string SuffixCoreClr = "Core"; internal const string IntelliCodeServiceName = "pythia"; internal const string RazorServiceName = "razorLanguageService"; internal const string UnitTestingAnalysisServiceName = "UnitTestingAnalysis"; internal const string LiveUnitTestingBuildServiceName = "LiveUnitTestingBuild"; internal const string UnitTestingSourceLookupServiceName = "UnitTestingSourceLookup"; public readonly WellKnownServiceHubService WellKnownService; public readonly string? CustomServiceName; public RemoteServiceName(WellKnownServiceHubService wellKnownService) { WellKnownService = wellKnownService; CustomServiceName = null; } /// <summary> /// Exact service name - must be reflect the bitness of the ServiceHub process. /// </summary> public RemoteServiceName(string customServiceName) { WellKnownService = WellKnownServiceHubService.None; CustomServiceName = customServiceName; } public string ToString(bool isRemoteHostServerGC, bool isRemoteHostCoreClr) { if (CustomServiceName is not null) { return CustomServiceName; } var suffix = (isRemoteHostServerGC, isRemoteHostCoreClr) switch { (false, false) => Suffix64, (true, false) => Suffix64 + SuffixServerGC, (false, true) => SuffixCoreClr + Suffix64, (true, true) => SuffixCoreClr + Suffix64 + SuffixServerGC, }; return WellKnownService switch { WellKnownServiceHubService.RemoteHost => Prefix + nameof(WellKnownServiceHubService.RemoteHost) + suffix, WellKnownServiceHubService.IntelliCode => IntelliCodeServiceName + suffix, _ => throw ExceptionUtilities.UnexpectedValue(WellKnownService), }; } public override bool Equals(object? obj) => obj is RemoteServiceName name && Equals(name); public override int GetHashCode() => Hash.Combine(CustomServiceName, (int)WellKnownService); public bool Equals(RemoteServiceName other) => CustomServiceName == other.CustomServiceName && WellKnownService == other.WellKnownService; public static bool operator ==(RemoteServiceName left, RemoteServiceName right) => left.Equals(right); public static bool operator !=(RemoteServiceName left, RemoteServiceName right) => !(left == right); public static implicit operator RemoteServiceName(WellKnownServiceHubService wellKnownService) => new(wellKnownService); } }
// 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. using System; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Remote { /// <summary> /// Abstract the name of a remote service. /// </summary> /// <remarks> /// Allows partner teams to specify bitness-specific service name, while we can use bitness agnostic id for well-known services. /// TODO: Update LUT and SBD to use well-known ids and remove this abstraction (https://github.com/dotnet/roslyn/issues/44327). /// </remarks> internal readonly struct RemoteServiceName : IEquatable<RemoteServiceName> { internal const string Prefix = "roslyn"; internal const string Suffix64 = "64"; internal const string SuffixServerGC = "S"; internal const string SuffixCoreClr = "Core"; public readonly WellKnownServiceHubService WellKnownService; public readonly string? CustomServiceName; public RemoteServiceName(WellKnownServiceHubService wellKnownService) { WellKnownService = wellKnownService; CustomServiceName = null; } /// <summary> /// Exact service name - must be reflect the bitness of the ServiceHub process. /// </summary> public RemoteServiceName(string customServiceName) { WellKnownService = WellKnownServiceHubService.None; CustomServiceName = customServiceName; } public string ToString(bool isRemoteHostServerGC, bool isRemoteHostCoreClr) { if (CustomServiceName is not null) { return CustomServiceName; } var suffix = (isRemoteHostServerGC, isRemoteHostCoreClr) switch { (false, false) => Suffix64, (true, false) => Suffix64 + SuffixServerGC, (false, true) => SuffixCoreClr + Suffix64, (true, true) => SuffixCoreClr + Suffix64 + SuffixServerGC, }; return WellKnownService switch { WellKnownServiceHubService.RemoteHost => Prefix + nameof(WellKnownServiceHubService.RemoteHost) + suffix, _ => throw ExceptionUtilities.UnexpectedValue(WellKnownService), }; } public override bool Equals(object? obj) => obj is RemoteServiceName name && Equals(name); public override int GetHashCode() => Hash.Combine(CustomServiceName, (int)WellKnownService); public bool Equals(RemoteServiceName other) => CustomServiceName == other.CustomServiceName && WellKnownService == other.WellKnownService; public static bool operator ==(RemoteServiceName left, RemoteServiceName right) => left.Equals(right); public static bool operator !=(RemoteServiceName left, RemoteServiceName right) => !(left == right); public static implicit operator RemoteServiceName(WellKnownServiceHubService wellKnownService) => new(wellKnownService); } }
1
dotnet/roslyn
56,015
Remove obsolete APIs
Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
tmat
"2021-08-30T20:53:26Z"
"2021-09-02T16:56:01Z"
bdf1025480ad91f8db054959553257746f58f527
e782ce78f087060a3bc51737d3f07a6d102fb7b1
Remove obsolete APIs. Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
./src/Workspaces/Core/Portable/Remote/WellKnownServiceHubService.cs
// 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.Remote { internal enum WellKnownServiceHubService { None = 0, RemoteHost = 1, // obsolete: CodeAnalysis = 2, // obsolete: RemoteSymbolSearchUpdateService = 3, // obsolete: RemoteDesignerAttributeService = 4, // obsolete: RemoteProjectTelemetryService = 5, // obsolete: RemoteTodoCommentsService = 6, // obsolete: RemoteLanguageServer = 7, IntelliCode = 8, // obsolete: Razor = 9, // owned by Unit Testing team: // obsolete: UnitTestingAnalysisService = 10, // obsolete: LiveUnitTestingBuildService = 11, // obsolete: UnitTestingSourceLookupService = 12, } }
// 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.Remote { internal enum WellKnownServiceHubService { None = 0, RemoteHost = 1, // obsolete: CodeAnalysis = 2, // obsolete: RemoteSymbolSearchUpdateService = 3, // obsolete: RemoteDesignerAttributeService = 4, // obsolete: RemoteProjectTelemetryService = 5, // obsolete: RemoteTodoCommentsService = 6, // obsolete: RemoteLanguageServer = 7, // obsolete: IntelliCode = 8, // obsolete: Razor = 9, // owned by Unit Testing team: // obsolete: UnitTestingAnalysisService = 10, // obsolete: LiveUnitTestingBuildService = 11, // obsolete: UnitTestingSourceLookupService = 12, } }
1
dotnet/roslyn
56,015
Remove obsolete APIs
Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
tmat
"2021-08-30T20:53:26Z"
"2021-09-02T16:56:01Z"
bdf1025480ad91f8db054959553257746f58f527
e782ce78f087060a3bc51737d3f07a6d102fb7b1
Remove obsolete APIs. Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
./src/Workspaces/Remote/Core/ExternalAccess/Pythia/Api/PythiaRemoteHostClient.cs
// 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. using System; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Remote; #pragma warning disable 436 // duplicate types - can remove once PythiaRemoteHostClient is removed from Workspaces namespace Microsoft.CodeAnalysis.ExternalAccess.Pythia.Api { internal readonly struct PythiaRemoteHostClient { private readonly ServiceHubRemoteHostClient _client; private readonly PythiaServiceDescriptorsWrapper _serviceDescriptors; private readonly PythiaRemoteServiceCallbackDispatcherRegistry _callbackDispatchers; internal PythiaRemoteHostClient(ServiceHubRemoteHostClient client, PythiaServiceDescriptorsWrapper serviceDescriptors, PythiaRemoteServiceCallbackDispatcherRegistry callbackDispatchers) { _client = client; _serviceDescriptors = serviceDescriptors; _callbackDispatchers = callbackDispatchers; } public static async Task<PythiaRemoteHostClient?> TryGetClientAsync(HostWorkspaceServices services, PythiaServiceDescriptorsWrapper serviceDescriptors, PythiaRemoteServiceCallbackDispatcherRegistry callbackDispatchers, CancellationToken cancellationToken = default) { var client = await RemoteHostClient.TryGetClientAsync(services, cancellationToken).ConfigureAwait(false); if (client is null) return null; return new PythiaRemoteHostClient((ServiceHubRemoteHostClient)client, serviceDescriptors, callbackDispatchers); } private PythiaRemoteServiceConnectionWrapper<TService> CreateConnection<TService>(object? callbackTarget) where TService : class => new(_client.CreateConnection<TService>(_serviceDescriptors.UnderlyingObject, _callbackDispatchers, callbackTarget)); // no solution, no callback: public async ValueTask<bool> TryInvokeAsync<TService>(Func<TService, CancellationToken, ValueTask> invocation, CancellationToken cancellationToken) where TService : class { using var connection = CreateConnection<TService>(callbackTarget: null); return await connection.TryInvokeAsync(invocation, cancellationToken).ConfigureAwait(false); } public async ValueTask<Optional<TResult>> TryInvokeAsync<TService, TResult>(Func<TService, CancellationToken, ValueTask<TResult>> invocation, CancellationToken cancellationToken) where TService : class { using var connection = CreateConnection<TService>(callbackTarget: null); return await connection.TryInvokeAsync(invocation, cancellationToken).ConfigureAwait(false); } // no solution, callback: public async ValueTask<bool> TryInvokeAsync<TService>(Func<TService, PythiaRemoteServiceCallbackIdWrapper, CancellationToken, ValueTask> invocation, object callbackTarget, CancellationToken cancellationToken) where TService : class { using var connection = CreateConnection<TService>(callbackTarget); return await connection.TryInvokeAsync(invocation, cancellationToken).ConfigureAwait(false); } public async ValueTask<Optional<TResult>> TryInvokeAsync<TService, TResult>(Func<TService, PythiaRemoteServiceCallbackIdWrapper, CancellationToken, ValueTask<TResult>> invocation, object callbackTarget, CancellationToken cancellationToken) where TService : class { using var connection = CreateConnection<TService>(callbackTarget); return await connection.TryInvokeAsync(invocation, cancellationToken).ConfigureAwait(false); } // solution, no callback: public async ValueTask<bool> TryInvokeAsync<TService>(Solution solution, Func<TService, PythiaPinnedSolutionInfoWrapper, CancellationToken, ValueTask> invocation, CancellationToken cancellationToken) where TService : class { using var connection = CreateConnection<TService>(callbackTarget: null); return await connection.TryInvokeAsync(solution, invocation, cancellationToken).ConfigureAwait(false); } public async ValueTask<Optional<TResult>> TryInvokeAsync<TService, TResult>(Solution solution, Func<TService, PythiaPinnedSolutionInfoWrapper, CancellationToken, ValueTask<TResult>> invocation, CancellationToken cancellationToken) where TService : class { using var connection = CreateConnection<TService>(callbackTarget: null); return await connection.TryInvokeAsync(solution, invocation, cancellationToken).ConfigureAwait(false); } // solution, callback: public async ValueTask<bool> TryInvokeAsync<TService>(Solution solution, Func<TService, PythiaPinnedSolutionInfoWrapper, PythiaRemoteServiceCallbackIdWrapper, CancellationToken, ValueTask> invocation, object callbackTarget, CancellationToken cancellationToken) where TService : class { using var connection = CreateConnection<TService>(callbackTarget); return await connection.TryInvokeAsync(solution, invocation, cancellationToken).ConfigureAwait(false); } public async ValueTask<Optional<TResult>> TryInvokeAsync<TService, TResult>(Solution solution, Func<TService, PythiaPinnedSolutionInfoWrapper, PythiaRemoteServiceCallbackIdWrapper, CancellationToken, ValueTask<TResult>> invocation, object callbackTarget, CancellationToken cancellationToken) where TService : class { using var connection = CreateConnection<TService>(callbackTarget); return await connection.TryInvokeAsync(solution, invocation, cancellationToken).ConfigureAwait(false); } } }
// 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. using System; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Remote; namespace Microsoft.CodeAnalysis.ExternalAccess.Pythia.Api { internal readonly struct PythiaRemoteHostClient { private readonly ServiceHubRemoteHostClient _client; private readonly PythiaServiceDescriptorsWrapper _serviceDescriptors; private readonly PythiaRemoteServiceCallbackDispatcherRegistry _callbackDispatchers; internal PythiaRemoteHostClient(ServiceHubRemoteHostClient client, PythiaServiceDescriptorsWrapper serviceDescriptors, PythiaRemoteServiceCallbackDispatcherRegistry callbackDispatchers) { _client = client; _serviceDescriptors = serviceDescriptors; _callbackDispatchers = callbackDispatchers; } public static async Task<PythiaRemoteHostClient?> TryGetClientAsync(HostWorkspaceServices services, PythiaServiceDescriptorsWrapper serviceDescriptors, PythiaRemoteServiceCallbackDispatcherRegistry callbackDispatchers, CancellationToken cancellationToken = default) { var client = await RemoteHostClient.TryGetClientAsync(services, cancellationToken).ConfigureAwait(false); if (client is null) return null; return new PythiaRemoteHostClient((ServiceHubRemoteHostClient)client, serviceDescriptors, callbackDispatchers); } private PythiaRemoteServiceConnectionWrapper<TService> CreateConnection<TService>(object? callbackTarget) where TService : class => new(_client.CreateConnection<TService>(_serviceDescriptors.UnderlyingObject, _callbackDispatchers, callbackTarget)); // no solution, no callback: public async ValueTask<bool> TryInvokeAsync<TService>(Func<TService, CancellationToken, ValueTask> invocation, CancellationToken cancellationToken) where TService : class { using var connection = CreateConnection<TService>(callbackTarget: null); return await connection.TryInvokeAsync(invocation, cancellationToken).ConfigureAwait(false); } public async ValueTask<Optional<TResult>> TryInvokeAsync<TService, TResult>(Func<TService, CancellationToken, ValueTask<TResult>> invocation, CancellationToken cancellationToken) where TService : class { using var connection = CreateConnection<TService>(callbackTarget: null); return await connection.TryInvokeAsync(invocation, cancellationToken).ConfigureAwait(false); } // no solution, callback: public async ValueTask<bool> TryInvokeAsync<TService>(Func<TService, PythiaRemoteServiceCallbackIdWrapper, CancellationToken, ValueTask> invocation, object callbackTarget, CancellationToken cancellationToken) where TService : class { using var connection = CreateConnection<TService>(callbackTarget); return await connection.TryInvokeAsync(invocation, cancellationToken).ConfigureAwait(false); } public async ValueTask<Optional<TResult>> TryInvokeAsync<TService, TResult>(Func<TService, PythiaRemoteServiceCallbackIdWrapper, CancellationToken, ValueTask<TResult>> invocation, object callbackTarget, CancellationToken cancellationToken) where TService : class { using var connection = CreateConnection<TService>(callbackTarget); return await connection.TryInvokeAsync(invocation, cancellationToken).ConfigureAwait(false); } // solution, no callback: public async ValueTask<bool> TryInvokeAsync<TService>(Solution solution, Func<TService, PythiaPinnedSolutionInfoWrapper, CancellationToken, ValueTask> invocation, CancellationToken cancellationToken) where TService : class { using var connection = CreateConnection<TService>(callbackTarget: null); return await connection.TryInvokeAsync(solution, invocation, cancellationToken).ConfigureAwait(false); } public async ValueTask<Optional<TResult>> TryInvokeAsync<TService, TResult>(Solution solution, Func<TService, PythiaPinnedSolutionInfoWrapper, CancellationToken, ValueTask<TResult>> invocation, CancellationToken cancellationToken) where TService : class { using var connection = CreateConnection<TService>(callbackTarget: null); return await connection.TryInvokeAsync(solution, invocation, cancellationToken).ConfigureAwait(false); } // solution, callback: public async ValueTask<bool> TryInvokeAsync<TService>(Solution solution, Func<TService, PythiaPinnedSolutionInfoWrapper, PythiaRemoteServiceCallbackIdWrapper, CancellationToken, ValueTask> invocation, object callbackTarget, CancellationToken cancellationToken) where TService : class { using var connection = CreateConnection<TService>(callbackTarget); return await connection.TryInvokeAsync(solution, invocation, cancellationToken).ConfigureAwait(false); } public async ValueTask<Optional<TResult>> TryInvokeAsync<TService, TResult>(Solution solution, Func<TService, PythiaPinnedSolutionInfoWrapper, PythiaRemoteServiceCallbackIdWrapper, CancellationToken, ValueTask<TResult>> invocation, object callbackTarget, CancellationToken cancellationToken) where TService : class { using var connection = CreateConnection<TService>(callbackTarget); return await connection.TryInvokeAsync(solution, invocation, cancellationToken).ConfigureAwait(false); } } }
1
dotnet/roslyn
56,015
Remove obsolete APIs
Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
tmat
"2021-08-30T20:53:26Z"
"2021-09-02T16:56:01Z"
bdf1025480ad91f8db054959553257746f58f527
e782ce78f087060a3bc51737d3f07a6d102fb7b1
Remove obsolete APIs. Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
./src/Compilers/Core/Portable/CodeGen/ItemTokenMap.cs
// 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. using System.Collections.Concurrent; using System.Collections.Generic; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeGen { /// <summary> /// Handles storage of items referenced via tokens in metadata. When items are stored /// they are uniquely "associated" with fake tokens, which are basically sequential numbers. /// IL gen will use these fake tokens during codegen and later, when actual values /// are known, the method bodies will be patched. /// To support these two scenarios we need two maps - Item-->uint, and uint-->Item. (The second is really just a list). /// </summary> internal sealed class ItemTokenMap<T> where T : class { private readonly ConcurrentDictionary<T, uint> _itemToToken = new ConcurrentDictionary<T, uint>(ReferenceEqualityComparer.Instance); private readonly ArrayBuilder<T> _items = new ArrayBuilder<T>(); public uint GetOrAddTokenFor(T item) { uint token; // NOTE: cannot use GetOrAdd here since items and itemToToken must be in sync // so if we do need to add we have to take a lock and modify both collections. if (_itemToToken.TryGetValue(item, out token)) { return token; } return AddItem(item); } private uint AddItem(T item) { uint token; lock (_items) { if (_itemToToken.TryGetValue(item, out token)) { return token; } token = (uint)_items.Count; _items.Add(item); _itemToToken.Add(item, token); } return token; } public T GetItem(uint token) { lock (_items) { return _items[(int)token]; } } public IEnumerable<T> GetAllItems() { lock (_items) { return _items.ToArray(); } } } }
// 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. using System.Collections.Concurrent; using System.Collections.Generic; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeGen { /// <summary> /// Handles storage of items referenced via tokens in metadata. When items are stored /// they are uniquely "associated" with fake tokens, which are basically sequential numbers. /// IL gen will use these fake tokens during codegen and later, when actual values /// are known, the method bodies will be patched. /// To support these two scenarios we need two maps - Item-->uint, and uint-->Item. (The second is really just a list). /// </summary> internal sealed class ItemTokenMap<T> where T : class { private readonly ConcurrentDictionary<T, uint> _itemToToken = new ConcurrentDictionary<T, uint>(ReferenceEqualityComparer.Instance); private readonly ArrayBuilder<T> _items = new ArrayBuilder<T>(); public uint GetOrAddTokenFor(T item) { uint token; // NOTE: cannot use GetOrAdd here since items and itemToToken must be in sync // so if we do need to add we have to take a lock and modify both collections. if (_itemToToken.TryGetValue(item, out token)) { return token; } return AddItem(item); } private uint AddItem(T item) { uint token; lock (_items) { if (_itemToToken.TryGetValue(item, out token)) { return token; } token = (uint)_items.Count; _items.Add(item); _itemToToken.Add(item, token); } return token; } public T GetItem(uint token) { lock (_items) { return _items[(int)token]; } } public IEnumerable<T> GetAllItems() { lock (_items) { return _items.ToArray(); } } } }
-1
dotnet/roslyn
56,015
Remove obsolete APIs
Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
tmat
"2021-08-30T20:53:26Z"
"2021-09-02T16:56:01Z"
bdf1025480ad91f8db054959553257746f58f527
e782ce78f087060a3bc51737d3f07a6d102fb7b1
Remove obsolete APIs. Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
./src/Features/CSharp/Portable/Completion/KeywordRecommenders/PrivateKeywordRecommender.cs
// 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. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class PrivateKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public PrivateKeywordRecommender() : base(SyntaxKind.PrivateKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { return (context.IsGlobalStatementContext && context.SyntaxTree.IsScript()) || IsValidContextForAccessor(context) || IsValidContextForType(context, cancellationToken) || IsValidContextForMember(context, cancellationToken); } private static bool IsValidContextForAccessor(CSharpSyntaxContext context) { if (context.TargetToken.IsAccessorDeclarationContext<PropertyDeclarationSyntax>(context.Position) || context.TargetToken.IsAccessorDeclarationContext<IndexerDeclarationSyntax>(context.Position)) { return CheckPreviousAccessibilityModifiers(context); } return false; } private static bool IsValidContextForMember(CSharpSyntaxContext context, CancellationToken cancellationToken) { if (context.SyntaxTree.IsGlobalMemberDeclarationContext(context.Position, SyntaxKindSet.AllGlobalMemberModifiers, cancellationToken) || context.IsMemberDeclarationContext(validModifiers: SyntaxKindSet.AllMemberModifiers, validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructRecordTypeDeclarations, canBePartial: false, cancellationToken: cancellationToken)) { var modifiers = context.PrecedingModifiers; // can't have private + abstract/virtual/override/sealed if (modifiers.Contains(SyntaxKind.AbstractKeyword) || modifiers.Contains(SyntaxKind.VirtualKeyword) || modifiers.Contains(SyntaxKind.OverrideKeyword) || modifiers.Contains(SyntaxKind.SealedKeyword)) { return false; } return CheckPreviousAccessibilityModifiers(context); } return false; } private static bool IsValidContextForType(CSharpSyntaxContext context, CancellationToken cancellationToken) { if (context.IsTypeDeclarationContext(validModifiers: SyntaxKindSet.AllTypeModifiers, validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructRecordTypeDeclarations, canBePartial: false, cancellationToken: cancellationToken)) { // private things can't be in namespaces. var typeDecl = context.ContainingTypeDeclaration; if (typeDecl == null) { return false; } return CheckPreviousAccessibilityModifiers(context); } return false; } private static bool CheckPreviousAccessibilityModifiers(CSharpSyntaxContext context) { // We can show up after 'protected'. var precedingModifiers = context.PrecedingModifiers; return !precedingModifiers.Contains(SyntaxKind.PublicKeyword) && !precedingModifiers.Contains(SyntaxKind.InternalKeyword) && !precedingModifiers.Contains(SyntaxKind.PrivateKeyword); } } }
// 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. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class PrivateKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public PrivateKeywordRecommender() : base(SyntaxKind.PrivateKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { return (context.IsGlobalStatementContext && context.SyntaxTree.IsScript()) || IsValidContextForAccessor(context) || IsValidContextForType(context, cancellationToken) || IsValidContextForMember(context, cancellationToken); } private static bool IsValidContextForAccessor(CSharpSyntaxContext context) { if (context.TargetToken.IsAccessorDeclarationContext<PropertyDeclarationSyntax>(context.Position) || context.TargetToken.IsAccessorDeclarationContext<IndexerDeclarationSyntax>(context.Position)) { return CheckPreviousAccessibilityModifiers(context); } return false; } private static bool IsValidContextForMember(CSharpSyntaxContext context, CancellationToken cancellationToken) { if (context.SyntaxTree.IsGlobalMemberDeclarationContext(context.Position, SyntaxKindSet.AllGlobalMemberModifiers, cancellationToken) || context.IsMemberDeclarationContext(validModifiers: SyntaxKindSet.AllMemberModifiers, validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructRecordTypeDeclarations, canBePartial: false, cancellationToken: cancellationToken)) { var modifiers = context.PrecedingModifiers; // can't have private + abstract/virtual/override/sealed if (modifiers.Contains(SyntaxKind.AbstractKeyword) || modifiers.Contains(SyntaxKind.VirtualKeyword) || modifiers.Contains(SyntaxKind.OverrideKeyword) || modifiers.Contains(SyntaxKind.SealedKeyword)) { return false; } return CheckPreviousAccessibilityModifiers(context); } return false; } private static bool IsValidContextForType(CSharpSyntaxContext context, CancellationToken cancellationToken) { if (context.IsTypeDeclarationContext(validModifiers: SyntaxKindSet.AllTypeModifiers, validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructRecordTypeDeclarations, canBePartial: false, cancellationToken: cancellationToken)) { // private things can't be in namespaces. var typeDecl = context.ContainingTypeDeclaration; if (typeDecl == null) { return false; } return CheckPreviousAccessibilityModifiers(context); } return false; } private static bool CheckPreviousAccessibilityModifiers(CSharpSyntaxContext context) { // We can show up after 'protected'. var precedingModifiers = context.PrecedingModifiers; return !precedingModifiers.Contains(SyntaxKind.PublicKeyword) && !precedingModifiers.Contains(SyntaxKind.InternalKeyword) && !precedingModifiers.Contains(SyntaxKind.PrivateKeyword); } } }
-1
dotnet/roslyn
56,015
Remove obsolete APIs
Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
tmat
"2021-08-30T20:53:26Z"
"2021-09-02T16:56:01Z"
bdf1025480ad91f8db054959553257746f58f527
e782ce78f087060a3bc51737d3f07a6d102fb7b1
Remove obsolete APIs. Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
./src/Workspaces/Core/Portable/Workspace/Solution/TextLoader.cs
// 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. using System; using System.IO; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// A class that represents access to a source text and its version from a storage location. /// </summary> public abstract class TextLoader { private const double MaxDelaySecs = 1.0; private const int MaxRetries = 5; internal static readonly TimeSpan RetryDelay = TimeSpan.FromSeconds(MaxDelaySecs / MaxRetries); internal virtual string? FilePath => null; /// <summary> /// Load a text and a version of the document. /// </summary> /// <exception cref="IOException" /> /// <exception cref="InvalidDataException"/> /// <exception cref="OperationCanceledException"/> public abstract Task<TextAndVersion> LoadTextAndVersionAsync(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken); /// <summary> /// Load a text and a version of the document in the workspace. /// </summary> /// <exception cref="IOException" /> /// <exception cref="InvalidDataException"/> /// <exception cref="OperationCanceledException"/> internal virtual TextAndVersion LoadTextAndVersionSynchronously(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken) { // this implementation exists in case a custom derived type does not have access to internals return LoadTextAndVersionAsync(workspace, documentId, cancellationToken).WaitAndGetResult_CanCallOnBackground(cancellationToken); } internal async Task<TextAndVersion> LoadTextAsync(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken) { var retries = 0; while (true) { try { return await LoadTextAndVersionAsync(workspace, documentId, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } catch (IOException e) { if (++retries > MaxRetries) { return CreateFailedText(workspace, documentId, e.Message); } // fall out to try again } catch (InvalidDataException e) { return CreateFailedText(workspace, documentId, e.Message); } // try again after a delay await Task.Delay(RetryDelay, cancellationToken).ConfigureAwait(false); } } internal TextAndVersion LoadTextSynchronously(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken) { var retries = 0; while (true) { try { return LoadTextAndVersionSynchronously(workspace, documentId, cancellationToken); } catch (IOException e) { if (++retries > MaxRetries) { return CreateFailedText(workspace, documentId, e.Message); } // fall out to try again } catch (InvalidDataException e) { return CreateFailedText(workspace, documentId, e.Message); } // try again after a delay Thread.Sleep(RetryDelay); } } private TextAndVersion CreateFailedText(Workspace workspace, DocumentId documentId, string message) { // Notify workspace for backwards compatibility. workspace.OnWorkspaceFailed(new DocumentDiagnostic(WorkspaceDiagnosticKind.Failure, message, documentId)); Location location; string display; var filePath = FilePath; if (filePath == null) { location = Location.None; display = documentId.ToString(); } else { location = Location.Create(filePath, textSpan: default, lineSpan: default); display = filePath; } return TextAndVersion.Create( SourceText.From(string.Empty, Encoding.UTF8), VersionStamp.Default, string.Empty, Diagnostic.Create(WorkspaceDiagnosticDescriptors.ErrorReadingFileContent, location, new[] { display, message })); } /// <summary> /// Creates a new <see cref="TextLoader"/> from an already existing source text and version. /// </summary> public static TextLoader From(TextAndVersion textAndVersion) { if (textAndVersion == null) { throw new ArgumentNullException(nameof(textAndVersion)); } return new TextDocumentLoader(textAndVersion); } /// <summary> /// Creates a <see cref="TextLoader"/> from a <see cref="SourceTextContainer"/> and version. /// /// The text obtained from the loader will be the current text of the container at the time /// the loader is accessed. /// </summary> public static TextLoader From(SourceTextContainer container, VersionStamp version, string? filePath = null) { if (container == null) { throw new ArgumentNullException(nameof(container)); } return new TextContainerLoader(container, version, filePath); } private sealed class TextDocumentLoader : TextLoader { private readonly TextAndVersion _textAndVersion; internal TextDocumentLoader(TextAndVersion textAndVersion) => _textAndVersion = textAndVersion; public override Task<TextAndVersion> LoadTextAndVersionAsync(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken) => Task.FromResult(_textAndVersion); internal override TextAndVersion LoadTextAndVersionSynchronously(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken) => _textAndVersion; } private sealed class TextContainerLoader : TextLoader { private readonly SourceTextContainer _container; private readonly VersionStamp _version; private readonly string? _filePath; internal TextContainerLoader(SourceTextContainer container, VersionStamp version, string? filePath) { _container = container; _version = version; _filePath = filePath; } public override Task<TextAndVersion> LoadTextAndVersionAsync(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken) => Task.FromResult(LoadTextAndVersionSynchronously(workspace, documentId, cancellationToken)); internal override TextAndVersion LoadTextAndVersionSynchronously(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken) => TextAndVersion.Create(_container.CurrentText, _version, _filePath); } } }
// 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. using System; using System.IO; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// A class that represents access to a source text and its version from a storage location. /// </summary> public abstract class TextLoader { private const double MaxDelaySecs = 1.0; private const int MaxRetries = 5; internal static readonly TimeSpan RetryDelay = TimeSpan.FromSeconds(MaxDelaySecs / MaxRetries); internal virtual string? FilePath => null; /// <summary> /// Load a text and a version of the document. /// </summary> /// <exception cref="IOException" /> /// <exception cref="InvalidDataException"/> /// <exception cref="OperationCanceledException"/> public abstract Task<TextAndVersion> LoadTextAndVersionAsync(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken); /// <summary> /// Load a text and a version of the document in the workspace. /// </summary> /// <exception cref="IOException" /> /// <exception cref="InvalidDataException"/> /// <exception cref="OperationCanceledException"/> internal virtual TextAndVersion LoadTextAndVersionSynchronously(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken) { // this implementation exists in case a custom derived type does not have access to internals return LoadTextAndVersionAsync(workspace, documentId, cancellationToken).WaitAndGetResult_CanCallOnBackground(cancellationToken); } internal async Task<TextAndVersion> LoadTextAsync(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken) { var retries = 0; while (true) { try { return await LoadTextAndVersionAsync(workspace, documentId, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } catch (IOException e) { if (++retries > MaxRetries) { return CreateFailedText(workspace, documentId, e.Message); } // fall out to try again } catch (InvalidDataException e) { return CreateFailedText(workspace, documentId, e.Message); } // try again after a delay await Task.Delay(RetryDelay, cancellationToken).ConfigureAwait(false); } } internal TextAndVersion LoadTextSynchronously(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken) { var retries = 0; while (true) { try { return LoadTextAndVersionSynchronously(workspace, documentId, cancellationToken); } catch (IOException e) { if (++retries > MaxRetries) { return CreateFailedText(workspace, documentId, e.Message); } // fall out to try again } catch (InvalidDataException e) { return CreateFailedText(workspace, documentId, e.Message); } // try again after a delay Thread.Sleep(RetryDelay); } } private TextAndVersion CreateFailedText(Workspace workspace, DocumentId documentId, string message) { // Notify workspace for backwards compatibility. workspace.OnWorkspaceFailed(new DocumentDiagnostic(WorkspaceDiagnosticKind.Failure, message, documentId)); Location location; string display; var filePath = FilePath; if (filePath == null) { location = Location.None; display = documentId.ToString(); } else { location = Location.Create(filePath, textSpan: default, lineSpan: default); display = filePath; } return TextAndVersion.Create( SourceText.From(string.Empty, Encoding.UTF8), VersionStamp.Default, string.Empty, Diagnostic.Create(WorkspaceDiagnosticDescriptors.ErrorReadingFileContent, location, new[] { display, message })); } /// <summary> /// Creates a new <see cref="TextLoader"/> from an already existing source text and version. /// </summary> public static TextLoader From(TextAndVersion textAndVersion) { if (textAndVersion == null) { throw new ArgumentNullException(nameof(textAndVersion)); } return new TextDocumentLoader(textAndVersion); } /// <summary> /// Creates a <see cref="TextLoader"/> from a <see cref="SourceTextContainer"/> and version. /// /// The text obtained from the loader will be the current text of the container at the time /// the loader is accessed. /// </summary> public static TextLoader From(SourceTextContainer container, VersionStamp version, string? filePath = null) { if (container == null) { throw new ArgumentNullException(nameof(container)); } return new TextContainerLoader(container, version, filePath); } private sealed class TextDocumentLoader : TextLoader { private readonly TextAndVersion _textAndVersion; internal TextDocumentLoader(TextAndVersion textAndVersion) => _textAndVersion = textAndVersion; public override Task<TextAndVersion> LoadTextAndVersionAsync(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken) => Task.FromResult(_textAndVersion); internal override TextAndVersion LoadTextAndVersionSynchronously(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken) => _textAndVersion; } private sealed class TextContainerLoader : TextLoader { private readonly SourceTextContainer _container; private readonly VersionStamp _version; private readonly string? _filePath; internal TextContainerLoader(SourceTextContainer container, VersionStamp version, string? filePath) { _container = container; _version = version; _filePath = filePath; } public override Task<TextAndVersion> LoadTextAndVersionAsync(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken) => Task.FromResult(LoadTextAndVersionSynchronously(workspace, documentId, cancellationToken)); internal override TextAndVersion LoadTextAndVersionSynchronously(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken) => TextAndVersion.Create(_container.CurrentText, _version, _filePath); } } }
-1
dotnet/roslyn
56,015
Remove obsolete APIs
Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
tmat
"2021-08-30T20:53:26Z"
"2021-09-02T16:56:01Z"
bdf1025480ad91f8db054959553257746f58f527
e782ce78f087060a3bc51737d3f07a6d102fb7b1
Remove obsolete APIs. Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
./src/EditorFeatures/Test/Extensions/ITextLineExtensionsTests.cs
// 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. #nullable disable using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Extensions { public class ITextLineExtensionsTests { [Fact] public void GetFirstNonWhitespacePosition_EmptyLineReturnsNull() { var position = GetFirstNonWhitespacePosition(string.Empty); Assert.Null(position); } [Fact] public void GetFirstNonWhitespacePosition_WhitespaceLineReturnsNull1() { var position = GetFirstNonWhitespacePosition(" "); Assert.Null(position); } [Fact] public void GetFirstNonWhitespacePosition_WhitespaceLineReturnsNull2() { var position = GetFirstNonWhitespacePosition("\t\t"); Assert.Null(position); } [Fact] public void GetFirstNonWhitespacePosition_WhitespaceLineReturnsNull3() { var position = GetFirstNonWhitespacePosition(" \t "); Assert.Null(position); } [Fact] public void GetFirstNonWhitespacePosition_TextLine() { var position = GetFirstNonWhitespacePosition("Goo"); Assert.Equal(0, position.Value); } [Fact] public void GetFirstNonWhitespacePosition_TextLineStartingWithWhitespace1() { var position = GetFirstNonWhitespacePosition(" Goo"); Assert.Equal(4, position.Value); } [Fact] public void GetFirstNonWhitespacePosition_TextLineStartingWithWhitespace2() { var position = GetFirstNonWhitespacePosition(" \t Goo"); Assert.Equal(3, position.Value); } [Fact] public void GetFirstNonWhitespacePosition_TextLineStartingWithWhitespace3() { var position = GetFirstNonWhitespacePosition("\t\tGoo"); Assert.Equal(2, position.Value); } [Fact] public void IsEmptyOrWhitespace_EmptyLineReturnsTrue() { var value = IsEmptyOrWhitespace(string.Empty); Assert.True(value); } [Fact] public void IsEmptyOrWhitespace_WhitespaceLineReturnsTrue1() { var value = IsEmptyOrWhitespace(" "); Assert.True(value); } [Fact] public void IsEmptyOrWhitespace_WhitespaceLineReturnsTrue2() { var value = IsEmptyOrWhitespace("\t\t"); Assert.True(value); } [Fact] public void IsEmptyOrWhitespace_WhitespaceLineReturnsTrue3() { var value = IsEmptyOrWhitespace(" \t "); Assert.True(value); } [Fact] public void IsEmptyOrWhitespace_TextLineReturnsFalse() { var value = IsEmptyOrWhitespace("Goo"); Assert.False(value); } [Fact] public void IsEmptyOrWhitespace_TextLineStartingWithWhitespaceReturnsFalse1() { var value = IsEmptyOrWhitespace(" Goo"); Assert.False(value); } [Fact] public void IsEmptyOrWhitespace_TextLineStartingWithWhitespaceReturnsFalse2() { var value = IsEmptyOrWhitespace(" \t Goo"); Assert.False(value); } [Fact] public void IsEmptyOrWhitespace_TextLineStartingWithWhitespaceReturnsFalse3() { var value = IsEmptyOrWhitespace("\t\tGoo"); Assert.False(value); } private static TextLine GetLine(string codeLine) { var text = SourceText.From(codeLine); return text.Lines[0]; } private static bool IsEmptyOrWhitespace(string codeLine) { var line = GetLine(codeLine); return line.IsEmptyOrWhitespace(); } private static int? GetFirstNonWhitespacePosition(string codeLine) { var line = GetLine(codeLine); return line.GetFirstNonWhitespacePosition(); } } }
// 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. #nullable disable using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Extensions { public class ITextLineExtensionsTests { [Fact] public void GetFirstNonWhitespacePosition_EmptyLineReturnsNull() { var position = GetFirstNonWhitespacePosition(string.Empty); Assert.Null(position); } [Fact] public void GetFirstNonWhitespacePosition_WhitespaceLineReturnsNull1() { var position = GetFirstNonWhitespacePosition(" "); Assert.Null(position); } [Fact] public void GetFirstNonWhitespacePosition_WhitespaceLineReturnsNull2() { var position = GetFirstNonWhitespacePosition("\t\t"); Assert.Null(position); } [Fact] public void GetFirstNonWhitespacePosition_WhitespaceLineReturnsNull3() { var position = GetFirstNonWhitespacePosition(" \t "); Assert.Null(position); } [Fact] public void GetFirstNonWhitespacePosition_TextLine() { var position = GetFirstNonWhitespacePosition("Goo"); Assert.Equal(0, position.Value); } [Fact] public void GetFirstNonWhitespacePosition_TextLineStartingWithWhitespace1() { var position = GetFirstNonWhitespacePosition(" Goo"); Assert.Equal(4, position.Value); } [Fact] public void GetFirstNonWhitespacePosition_TextLineStartingWithWhitespace2() { var position = GetFirstNonWhitespacePosition(" \t Goo"); Assert.Equal(3, position.Value); } [Fact] public void GetFirstNonWhitespacePosition_TextLineStartingWithWhitespace3() { var position = GetFirstNonWhitespacePosition("\t\tGoo"); Assert.Equal(2, position.Value); } [Fact] public void IsEmptyOrWhitespace_EmptyLineReturnsTrue() { var value = IsEmptyOrWhitespace(string.Empty); Assert.True(value); } [Fact] public void IsEmptyOrWhitespace_WhitespaceLineReturnsTrue1() { var value = IsEmptyOrWhitespace(" "); Assert.True(value); } [Fact] public void IsEmptyOrWhitespace_WhitespaceLineReturnsTrue2() { var value = IsEmptyOrWhitespace("\t\t"); Assert.True(value); } [Fact] public void IsEmptyOrWhitespace_WhitespaceLineReturnsTrue3() { var value = IsEmptyOrWhitespace(" \t "); Assert.True(value); } [Fact] public void IsEmptyOrWhitespace_TextLineReturnsFalse() { var value = IsEmptyOrWhitespace("Goo"); Assert.False(value); } [Fact] public void IsEmptyOrWhitespace_TextLineStartingWithWhitespaceReturnsFalse1() { var value = IsEmptyOrWhitespace(" Goo"); Assert.False(value); } [Fact] public void IsEmptyOrWhitespace_TextLineStartingWithWhitespaceReturnsFalse2() { var value = IsEmptyOrWhitespace(" \t Goo"); Assert.False(value); } [Fact] public void IsEmptyOrWhitespace_TextLineStartingWithWhitespaceReturnsFalse3() { var value = IsEmptyOrWhitespace("\t\tGoo"); Assert.False(value); } private static TextLine GetLine(string codeLine) { var text = SourceText.From(codeLine); return text.Lines[0]; } private static bool IsEmptyOrWhitespace(string codeLine) { var line = GetLine(codeLine); return line.IsEmptyOrWhitespace(); } private static int? GetFirstNonWhitespacePosition(string codeLine) { var line = GetLine(codeLine); return line.GetFirstNonWhitespacePosition(); } } }
-1
dotnet/roslyn
56,015
Remove obsolete APIs
Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
tmat
"2021-08-30T20:53:26Z"
"2021-09-02T16:56:01Z"
bdf1025480ad91f8db054959553257746f58f527
e782ce78f087060a3bc51737d3f07a6d102fb7b1
Remove obsolete APIs. Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
./src/VisualStudio/Core/Def/Implementation/Workspace/GlobalUndoServiceFactory.NoOpUndoPrimitive.cs
// 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. #nullable disable using Microsoft.VisualStudio.Text.Operations; namespace Microsoft.VisualStudio.LanguageServices.Implementation { internal partial class GlobalUndoServiceFactory { /// <summary> /// no op undo primitive /// </summary> private class NoOpUndoPrimitive : ITextUndoPrimitive { public ITextUndoTransaction Parent { get; set; } public bool CanRedo { get { return true; } } public bool CanUndo { get { return true; } } public void Do() { } public void Undo() { } public bool CanMerge(ITextUndoPrimitive older) => true; public ITextUndoPrimitive Merge(ITextUndoPrimitive older) => older; } } }
// 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. #nullable disable using Microsoft.VisualStudio.Text.Operations; namespace Microsoft.VisualStudio.LanguageServices.Implementation { internal partial class GlobalUndoServiceFactory { /// <summary> /// no op undo primitive /// </summary> private class NoOpUndoPrimitive : ITextUndoPrimitive { public ITextUndoTransaction Parent { get; set; } public bool CanRedo { get { return true; } } public bool CanUndo { get { return true; } } public void Do() { } public void Undo() { } public bool CanMerge(ITextUndoPrimitive older) => true; public ITextUndoPrimitive Merge(ITextUndoPrimitive older) => older; } } }
-1
dotnet/roslyn
56,015
Remove obsolete APIs
Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
tmat
"2021-08-30T20:53:26Z"
"2021-09-02T16:56:01Z"
bdf1025480ad91f8db054959553257746f58f527
e782ce78f087060a3bc51737d3f07a6d102fb7b1
Remove obsolete APIs. Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
./src/Compilers/CSharp/Test/Emit/CodeGen/CodeGenRefOutTests.cs
// 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. #nullable disable using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen { public class CodeGenRefOutTests : CSharpTestBase { [Fact] public void TestOutParamSignature() { var source = @" class C { void M(out int x) { x = 0; } }"; CompileAndVerify(source, expectedSignatures: new[] { Signature("C", "M", ".method private hidebysig instance System.Void M([out] System.Int32& x) cil managed") }); } [Fact] public void TestRefParamSignature() { var source = @" class C { void M(ref int x) { } }"; CompileAndVerify(source, expectedSignatures: new[] { Signature("C", "M", ".method private hidebysig instance System.Void M(System.Int32& x) cil managed") }); } [Fact] public void TestOneReferenceMultipleParameters() { var source = @" class C { static void Main() { int z = 0; Test(ref z, out z); System.Console.WriteLine(z); } static void Test(ref int x, out int y) { x = 1; y = 2; } }"; CompileAndVerify(source, expectedOutput: "2"); } [Fact] public void TestReferenceParameterOrder() { var source = @" public class Test { static int[] array = new int[1]; public static void Main(string[] args) { // Named parameters are in reversed order // Arguments have side effects // Arguments refer to the same array element Goo(y: out GetArray(""A"")[GetIndex(""B"")], x: ref GetArray(""C"")[GetIndex(""D"")]); System.Console.WriteLine(array[0]); } static void Goo(ref int x, out int y) { x = 1; y = 2; } static int GetIndex(string msg) { System.Console.WriteLine(""Index {0}"", msg); return 0; } static int[] GetArray(string msg) { System.Console.WriteLine(""Array {0}"", msg); return array; } }"; CompileAndVerify(source, expectedOutput: @" Array A Index B Array C Index D 2"); } [Fact] public void TestPassMutableStructByReference() { var source = @" class C { static void Main() { MutableStruct s1 = new MutableStruct(); s1.Dump(); ByRef(ref s1, 2); s1.Dump(); System.Console.WriteLine(); MutableStruct s2 = new MutableStruct(); s2.Dump(); ByVal(s2, 2); s2.Dump(); } static void ByRef(ref MutableStruct s, int depth) { if (depth <= 0) { s.Flag(); } else { s.Dump(); ByRef(ref s, depth - 1); s.Dump(); } } static void ByVal(MutableStruct s, int depth) { if (depth <= 0) { s.Flag(); } else { s.Dump(); ByVal(s, depth - 1); s.Dump(); } } } struct MutableStruct { private bool flagged; public void Flag() { this.flagged = true; } public void Dump() { System.Console.WriteLine(flagged ? ""Flagged"" : ""Unflagged""); } }"; CompileAndVerify(source, expectedOutput: @" Unflagged Unflagged Unflagged Flagged Flagged Flagged Unflagged Unflagged Unflagged Unflagged Unflagged Unflagged"); } [Fact] public void TestPassFieldByReference() { var source = @" class C { int field; int[] arrayField = new int[1]; static int staticField; static int[] staticArrayField = new int[1]; static void Main() { C c = new C(); System.Console.WriteLine(c.field); TestRef(ref c.field); System.Console.WriteLine(c.field); System.Console.WriteLine(c.arrayField[0]); TestRef(ref c.arrayField[0]); System.Console.WriteLine(c.arrayField[0]); System.Console.WriteLine(C.staticField); TestRef(ref C.staticField); System.Console.WriteLine(C.staticField); System.Console.WriteLine(C.staticArrayField[0]); TestRef(ref C.staticArrayField[0]); System.Console.WriteLine(C.staticArrayField[0]); } static void TestRef(ref int x) { x++; } }"; CompileAndVerify(source, expectedOutput: @" 0 1 0 1 0 1 0 1"); } [Fact] public void TestSetFieldViaOutParameter() { var source = @" class C { int field; int[] arrayField = new int[1]; static int staticField; static int[] staticArrayField = new int[1]; static void Main() { C c = new C(); System.Console.WriteLine(c.field); TestOut(out c.field); System.Console.WriteLine(c.field); System.Console.WriteLine(c.arrayField[0]); TestOut(out c.arrayField[0]); System.Console.WriteLine(c.arrayField[0]); System.Console.WriteLine(C.staticField); TestOut(out C.staticField); System.Console.WriteLine(C.staticField); System.Console.WriteLine(C.staticArrayField[0]); TestOut(out C.staticArrayField[0]); System.Console.WriteLine(C.staticArrayField[0]); } static void TestOut(out int x) { x = 1; } }"; CompileAndVerify(source, expectedOutput: @" 0 1 0 1 0 1 0 1"); } [WorkItem(543521, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543521")] [Fact()] public void TestConstructorWithOutParameter() { CompileAndVerify(@" class Class1 { Class1(out bool outParam) { outParam = true; } static void Main() { var b = false; var c1 = new Class1(out b); } }"); } [WorkItem(24014, "https://github.com/dotnet/roslyn/issues/24014")] [Fact] public void RefExtensionMethods_OutParam() { var code = @" using System; public class C { public static void Main() { var inst = new S1(); int orig; var result = inst.Mutate(out orig); System.Console.Write(orig); System.Console.Write(inst.x); } } public static class S1_Ex { public static bool Mutate(ref this S1 instance, out int orig) { orig = instance.x; instance.x = 42; return true; } } public struct S1 { public int x; } "; var compilation = CreateCompilationWithMscorlib40AndSystemCore(code, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(compilation, expectedOutput: "042"); verifier.VerifyIL("C.Main", @" { // Code size 36 (0x24) .maxstack 2 .locals init (S1 V_0, //inst int V_1) //orig IL_0000: ldloca.s V_0 IL_0002: initobj ""S1"" IL_0008: ldloca.s V_0 IL_000a: ldloca.s V_1 IL_000c: call ""bool S1_Ex.Mutate(ref S1, out int)"" IL_0011: pop IL_0012: ldloc.1 IL_0013: call ""void System.Console.Write(int)"" IL_0018: ldloc.0 IL_0019: ldfld ""int S1.x"" IL_001e: call ""void System.Console.Write(int)"" IL_0023: ret }"); } [WorkItem(24014, "https://github.com/dotnet/roslyn/issues/24014")] [Fact] public void OutParamAndOptional() { var code = @" using System; public class C { public static C cc => new C(); readonly int x; readonly int y; public static void Main() { var v = new C(1); System.Console.WriteLine('Q'); } private C() { } private C(int x) { var c = C.cc.Test(1, this, out x, out y); } public C Test(object arg1, C arg2, out int i1, out int i2, object opt = null) { i1 = 1; i2 = 2; return arg2; } } "; var compilation = CreateCompilationWithMscorlib40AndSystemCore(code, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(compilation, expectedOutput: "Q"); verifier.VerifyIL("C..ctor(int)", @" { // Code size 34 (0x22) .maxstack 6 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: call ""C C.cc.get"" IL_000b: ldc.i4.1 IL_000c: box ""int"" IL_0011: ldarg.0 IL_0012: ldarga.s V_1 IL_0014: ldarg.0 IL_0015: ldflda ""int C.y"" IL_001a: ldnull IL_001b: callvirt ""C C.Test(object, C, out int, out int, object)"" IL_0020: pop IL_0021: ret }"); } [WorkItem(24014, "https://github.com/dotnet/roslyn/issues/24014")] [Fact] public void OutParamAndOptionalNested() { var code = @" using System; public class C { public static C cc => new C(); readonly int y; public static void Main() { var v = new C(1); System.Console.WriteLine('Q'); } private C() { } private C(int x) { var captured = 2; C Test(object arg1, C arg2, out int i1, out int i2, object opt = null) { i1 = 1; i2 = captured++; return arg2; } var c = Test(1, this, out x, out y); } } "; var compilation = CreateCompilationWithMscorlib40AndSystemCore(code, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(compilation, expectedOutput: "Q"); verifier.VerifyIL("C..ctor(int)", @" { // Code size 39 (0x27) .maxstack 6 .locals init (C.<>c__DisplayClass5_0 V_0) //CS$<>8__locals0 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ldloca.s V_0 IL_0008: ldc.i4.2 IL_0009: stfld ""int C.<>c__DisplayClass5_0.captured"" IL_000e: ldc.i4.1 IL_000f: box ""int"" IL_0014: ldarg.0 IL_0015: ldarga.s V_1 IL_0017: ldarg.0 IL_0018: ldflda ""int C.y"" IL_001d: ldnull IL_001e: ldloca.s V_0 IL_0020: call ""C C.<.ctor>g__Test|5_0(object, C, out int, out int, object, ref C.<>c__DisplayClass5_0)"" IL_0025: pop IL_0026: ret }"); } } }
// 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. #nullable disable using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen { public class CodeGenRefOutTests : CSharpTestBase { [Fact] public void TestOutParamSignature() { var source = @" class C { void M(out int x) { x = 0; } }"; CompileAndVerify(source, expectedSignatures: new[] { Signature("C", "M", ".method private hidebysig instance System.Void M([out] System.Int32& x) cil managed") }); } [Fact] public void TestRefParamSignature() { var source = @" class C { void M(ref int x) { } }"; CompileAndVerify(source, expectedSignatures: new[] { Signature("C", "M", ".method private hidebysig instance System.Void M(System.Int32& x) cil managed") }); } [Fact] public void TestOneReferenceMultipleParameters() { var source = @" class C { static void Main() { int z = 0; Test(ref z, out z); System.Console.WriteLine(z); } static void Test(ref int x, out int y) { x = 1; y = 2; } }"; CompileAndVerify(source, expectedOutput: "2"); } [Fact] public void TestReferenceParameterOrder() { var source = @" public class Test { static int[] array = new int[1]; public static void Main(string[] args) { // Named parameters are in reversed order // Arguments have side effects // Arguments refer to the same array element Goo(y: out GetArray(""A"")[GetIndex(""B"")], x: ref GetArray(""C"")[GetIndex(""D"")]); System.Console.WriteLine(array[0]); } static void Goo(ref int x, out int y) { x = 1; y = 2; } static int GetIndex(string msg) { System.Console.WriteLine(""Index {0}"", msg); return 0; } static int[] GetArray(string msg) { System.Console.WriteLine(""Array {0}"", msg); return array; } }"; CompileAndVerify(source, expectedOutput: @" Array A Index B Array C Index D 2"); } [Fact] public void TestPassMutableStructByReference() { var source = @" class C { static void Main() { MutableStruct s1 = new MutableStruct(); s1.Dump(); ByRef(ref s1, 2); s1.Dump(); System.Console.WriteLine(); MutableStruct s2 = new MutableStruct(); s2.Dump(); ByVal(s2, 2); s2.Dump(); } static void ByRef(ref MutableStruct s, int depth) { if (depth <= 0) { s.Flag(); } else { s.Dump(); ByRef(ref s, depth - 1); s.Dump(); } } static void ByVal(MutableStruct s, int depth) { if (depth <= 0) { s.Flag(); } else { s.Dump(); ByVal(s, depth - 1); s.Dump(); } } } struct MutableStruct { private bool flagged; public void Flag() { this.flagged = true; } public void Dump() { System.Console.WriteLine(flagged ? ""Flagged"" : ""Unflagged""); } }"; CompileAndVerify(source, expectedOutput: @" Unflagged Unflagged Unflagged Flagged Flagged Flagged Unflagged Unflagged Unflagged Unflagged Unflagged Unflagged"); } [Fact] public void TestPassFieldByReference() { var source = @" class C { int field; int[] arrayField = new int[1]; static int staticField; static int[] staticArrayField = new int[1]; static void Main() { C c = new C(); System.Console.WriteLine(c.field); TestRef(ref c.field); System.Console.WriteLine(c.field); System.Console.WriteLine(c.arrayField[0]); TestRef(ref c.arrayField[0]); System.Console.WriteLine(c.arrayField[0]); System.Console.WriteLine(C.staticField); TestRef(ref C.staticField); System.Console.WriteLine(C.staticField); System.Console.WriteLine(C.staticArrayField[0]); TestRef(ref C.staticArrayField[0]); System.Console.WriteLine(C.staticArrayField[0]); } static void TestRef(ref int x) { x++; } }"; CompileAndVerify(source, expectedOutput: @" 0 1 0 1 0 1 0 1"); } [Fact] public void TestSetFieldViaOutParameter() { var source = @" class C { int field; int[] arrayField = new int[1]; static int staticField; static int[] staticArrayField = new int[1]; static void Main() { C c = new C(); System.Console.WriteLine(c.field); TestOut(out c.field); System.Console.WriteLine(c.field); System.Console.WriteLine(c.arrayField[0]); TestOut(out c.arrayField[0]); System.Console.WriteLine(c.arrayField[0]); System.Console.WriteLine(C.staticField); TestOut(out C.staticField); System.Console.WriteLine(C.staticField); System.Console.WriteLine(C.staticArrayField[0]); TestOut(out C.staticArrayField[0]); System.Console.WriteLine(C.staticArrayField[0]); } static void TestOut(out int x) { x = 1; } }"; CompileAndVerify(source, expectedOutput: @" 0 1 0 1 0 1 0 1"); } [WorkItem(543521, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543521")] [Fact()] public void TestConstructorWithOutParameter() { CompileAndVerify(@" class Class1 { Class1(out bool outParam) { outParam = true; } static void Main() { var b = false; var c1 = new Class1(out b); } }"); } [WorkItem(24014, "https://github.com/dotnet/roslyn/issues/24014")] [Fact] public void RefExtensionMethods_OutParam() { var code = @" using System; public class C { public static void Main() { var inst = new S1(); int orig; var result = inst.Mutate(out orig); System.Console.Write(orig); System.Console.Write(inst.x); } } public static class S1_Ex { public static bool Mutate(ref this S1 instance, out int orig) { orig = instance.x; instance.x = 42; return true; } } public struct S1 { public int x; } "; var compilation = CreateCompilationWithMscorlib40AndSystemCore(code, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(compilation, expectedOutput: "042"); verifier.VerifyIL("C.Main", @" { // Code size 36 (0x24) .maxstack 2 .locals init (S1 V_0, //inst int V_1) //orig IL_0000: ldloca.s V_0 IL_0002: initobj ""S1"" IL_0008: ldloca.s V_0 IL_000a: ldloca.s V_1 IL_000c: call ""bool S1_Ex.Mutate(ref S1, out int)"" IL_0011: pop IL_0012: ldloc.1 IL_0013: call ""void System.Console.Write(int)"" IL_0018: ldloc.0 IL_0019: ldfld ""int S1.x"" IL_001e: call ""void System.Console.Write(int)"" IL_0023: ret }"); } [WorkItem(24014, "https://github.com/dotnet/roslyn/issues/24014")] [Fact] public void OutParamAndOptional() { var code = @" using System; public class C { public static C cc => new C(); readonly int x; readonly int y; public static void Main() { var v = new C(1); System.Console.WriteLine('Q'); } private C() { } private C(int x) { var c = C.cc.Test(1, this, out x, out y); } public C Test(object arg1, C arg2, out int i1, out int i2, object opt = null) { i1 = 1; i2 = 2; return arg2; } } "; var compilation = CreateCompilationWithMscorlib40AndSystemCore(code, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(compilation, expectedOutput: "Q"); verifier.VerifyIL("C..ctor(int)", @" { // Code size 34 (0x22) .maxstack 6 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: call ""C C.cc.get"" IL_000b: ldc.i4.1 IL_000c: box ""int"" IL_0011: ldarg.0 IL_0012: ldarga.s V_1 IL_0014: ldarg.0 IL_0015: ldflda ""int C.y"" IL_001a: ldnull IL_001b: callvirt ""C C.Test(object, C, out int, out int, object)"" IL_0020: pop IL_0021: ret }"); } [WorkItem(24014, "https://github.com/dotnet/roslyn/issues/24014")] [Fact] public void OutParamAndOptionalNested() { var code = @" using System; public class C { public static C cc => new C(); readonly int y; public static void Main() { var v = new C(1); System.Console.WriteLine('Q'); } private C() { } private C(int x) { var captured = 2; C Test(object arg1, C arg2, out int i1, out int i2, object opt = null) { i1 = 1; i2 = captured++; return arg2; } var c = Test(1, this, out x, out y); } } "; var compilation = CreateCompilationWithMscorlib40AndSystemCore(code, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(compilation, expectedOutput: "Q"); verifier.VerifyIL("C..ctor(int)", @" { // Code size 39 (0x27) .maxstack 6 .locals init (C.<>c__DisplayClass5_0 V_0) //CS$<>8__locals0 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ldloca.s V_0 IL_0008: ldc.i4.2 IL_0009: stfld ""int C.<>c__DisplayClass5_0.captured"" IL_000e: ldc.i4.1 IL_000f: box ""int"" IL_0014: ldarg.0 IL_0015: ldarga.s V_1 IL_0017: ldarg.0 IL_0018: ldflda ""int C.y"" IL_001d: ldnull IL_001e: ldloca.s V_0 IL_0020: call ""C C.<.ctor>g__Test|5_0(object, C, out int, out int, object, ref C.<>c__DisplayClass5_0)"" IL_0025: pop IL_0026: ret }"); } } }
-1
dotnet/roslyn
56,015
Remove obsolete APIs
Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
tmat
"2021-08-30T20:53:26Z"
"2021-09-02T16:56:01Z"
bdf1025480ad91f8db054959553257746f58f527
e782ce78f087060a3bc51737d3f07a6d102fb7b1
Remove obsolete APIs. Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
./src/EditorFeatures/DiagnosticsTestUtilities/MoveType/AbstractMoveTypeTest.cs
// 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. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CodeRefactorings.MoveType; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.UnitTests; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.MoveType { public abstract class AbstractMoveTypeTest : AbstractCodeActionTest { private readonly string RenameFileCodeActionTitle = FeaturesResources.Rename_file_to_0; private readonly string RenameTypeCodeActionTitle = FeaturesResources.Rename_type_to_0; // TODO: Requires WPF due to IInlineRenameService dependency (https://github.com/dotnet/roslyn/issues/46153) protected override TestComposition GetComposition() => EditorTestCompositions.EditorFeaturesWpf .AddExcludedPartTypes(typeof(IDiagnosticUpdateSourceRegistrationService)) .AddParts(typeof(MockDiagnosticUpdateSourceRegistrationService)); protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new MoveTypeCodeRefactoringProvider(); protected async Task TestRenameTypeToMatchFileAsync( string originalCode, string expectedCode = null, bool expectedCodeAction = true, object fixProviderData = null) { var testOptions = new TestParameters(fixProviderData: fixProviderData); using (var workspace = CreateWorkspaceFromOptions(originalCode, testOptions)) { if (expectedCodeAction) { Assert.True(expectedCode != null, $"{nameof(expectedCode)} should be present if {nameof(expectedCodeAction)} is true."); var documentId = workspace.Documents[0].Id; var documentName = workspace.Documents[0].Name; MarkupTestFile.GetSpan(expectedCode, out var expectedText, out var span); var codeActionTitle = string.Format(RenameTypeCodeActionTitle, expectedText.Substring(span.Start, span.Length)); var oldSolutionAndNewSolution = await TestOperationAsync( testOptions, workspace, expectedText, codeActionTitle); // the original source document does not exist in the new solution. var newSolution = oldSolutionAndNewSolution.Item2; var document = newSolution.GetDocument(documentId); Assert.NotNull(document); Assert.Equal(documentName, document.Name); } else { var (actions, _) = await GetCodeActionsAsync(workspace, testOptions); if (actions.Length > 0) { var renameFileAction = actions.Any(action => action.Title.StartsWith(RenameTypeCodeActionTitle)); Assert.False(renameFileAction, "Rename Type to match file name code action was not expected, but shows up."); } } } } protected async Task TestRenameFileToMatchTypeAsync( string originalCode, string expectedDocumentName = null, bool expectedCodeAction = true, IList<string> destinationDocumentContainers = null, object fixProviderData = null) { var testOptions = new TestParameters(fixProviderData: fixProviderData); using (var workspace = CreateWorkspaceFromOptions(originalCode, testOptions)) { if (expectedCodeAction) { Assert.True(expectedDocumentName != null, $"{nameof(expectedDocumentName)} should be present if {nameof(expectedCodeAction)} is true."); var oldDocumentId = workspace.Documents[0].Id; var expectedText = workspace.Documents[0].GetTextBuffer().CurrentSnapshot.GetText(); var spans = workspace.Documents[0].SelectedSpans; var codeActionTitle = string.Format(RenameFileCodeActionTitle, expectedDocumentName); var oldSolutionAndNewSolution = await TestOperationAsync( testOptions, workspace, expectedText, codeActionTitle); // The code action updated the Name of the file in-place var newSolution = oldSolutionAndNewSolution.Item2; var newDocument = newSolution.GetDocument(oldDocumentId); Assert.Equal(expectedDocumentName, newDocument.Name); if (destinationDocumentContainers != null) { Assert.Equal(destinationDocumentContainers, newDocument.Folders); } } else { var (actions, _) = await GetCodeActionsAsync(workspace, testOptions); if (actions.Length > 0) { var renameFileAction = actions.Any(action => action.Title.StartsWith(RenameFileCodeActionTitle)); Assert.False(renameFileAction, "Rename File to match type code action was not expected, but shows up."); } } } } private async Task<Tuple<Solution, Solution>> TestOperationAsync( TestParameters parameters, Workspaces.TestWorkspace workspace, string expectedCode, string operation) { var (actions, _) = await GetCodeActionsAsync(workspace, parameters); var action = actions.Single(a => a.Title.Equals(operation, StringComparison.CurrentCulture)); var operations = await action.GetOperationsAsync(CancellationToken.None); return await TestOperationsAsync(workspace, expectedText: expectedCode, operations: operations, conflictSpans: ImmutableArray<TextSpan>.Empty, renameSpans: ImmutableArray<TextSpan>.Empty, warningSpans: ImmutableArray<TextSpan>.Empty, navigationSpans: ImmutableArray<TextSpan>.Empty, expectedChangedDocumentId: null); } protected async Task TestMoveTypeToNewFileAsync( string originalCode, string expectedSourceTextAfterRefactoring, string expectedDocumentName, string destinationDocumentText, ImmutableArray<string> destinationDocumentContainers = default, bool expectedCodeAction = true, int index = 0, Action<Workspace> onAfterWorkspaceCreated = null) { var testOptions = new TestParameters(index: index); if (expectedCodeAction) { using var workspace = CreateWorkspaceFromOptions(originalCode, testOptions); onAfterWorkspaceCreated?.Invoke(workspace); // replace with default values on null. destinationDocumentContainers = destinationDocumentContainers.NullToEmpty(); var sourceDocumentId = workspace.Documents[0].Id; // Verify the newly added document and its text var oldSolutionAndNewSolution = await TestAddDocumentAsync( testOptions, workspace, destinationDocumentText, expectedDocumentName, destinationDocumentContainers); // Verify source document's text after moving type. var oldSolution = oldSolutionAndNewSolution.Item1; var newSolution = oldSolutionAndNewSolution.Item2; var changedDocumentIds = SolutionUtilities.GetChangedDocuments(oldSolution, newSolution); Assert.True(changedDocumentIds.Contains(sourceDocumentId), "source document was not changed."); var modifiedSourceDocument = newSolution.GetDocument(sourceDocumentId); var actualSourceTextAfterRefactoring = (await modifiedSourceDocument.GetTextAsync()).ToString(); Assert.Equal(expectedSourceTextAfterRefactoring, actualSourceTextAfterRefactoring); } else { await TestMissingAsync(originalCode); } } } }
// 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. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CodeRefactorings.MoveType; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.UnitTests; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.MoveType { public abstract class AbstractMoveTypeTest : AbstractCodeActionTest { private readonly string RenameFileCodeActionTitle = FeaturesResources.Rename_file_to_0; private readonly string RenameTypeCodeActionTitle = FeaturesResources.Rename_type_to_0; // TODO: Requires WPF due to IInlineRenameService dependency (https://github.com/dotnet/roslyn/issues/46153) protected override TestComposition GetComposition() => EditorTestCompositions.EditorFeaturesWpf .AddExcludedPartTypes(typeof(IDiagnosticUpdateSourceRegistrationService)) .AddParts(typeof(MockDiagnosticUpdateSourceRegistrationService)); protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new MoveTypeCodeRefactoringProvider(); protected async Task TestRenameTypeToMatchFileAsync( string originalCode, string expectedCode = null, bool expectedCodeAction = true, object fixProviderData = null) { var testOptions = new TestParameters(fixProviderData: fixProviderData); using (var workspace = CreateWorkspaceFromOptions(originalCode, testOptions)) { if (expectedCodeAction) { Assert.True(expectedCode != null, $"{nameof(expectedCode)} should be present if {nameof(expectedCodeAction)} is true."); var documentId = workspace.Documents[0].Id; var documentName = workspace.Documents[0].Name; MarkupTestFile.GetSpan(expectedCode, out var expectedText, out var span); var codeActionTitle = string.Format(RenameTypeCodeActionTitle, expectedText.Substring(span.Start, span.Length)); var oldSolutionAndNewSolution = await TestOperationAsync( testOptions, workspace, expectedText, codeActionTitle); // the original source document does not exist in the new solution. var newSolution = oldSolutionAndNewSolution.Item2; var document = newSolution.GetDocument(documentId); Assert.NotNull(document); Assert.Equal(documentName, document.Name); } else { var (actions, _) = await GetCodeActionsAsync(workspace, testOptions); if (actions.Length > 0) { var renameFileAction = actions.Any(action => action.Title.StartsWith(RenameTypeCodeActionTitle)); Assert.False(renameFileAction, "Rename Type to match file name code action was not expected, but shows up."); } } } } protected async Task TestRenameFileToMatchTypeAsync( string originalCode, string expectedDocumentName = null, bool expectedCodeAction = true, IList<string> destinationDocumentContainers = null, object fixProviderData = null) { var testOptions = new TestParameters(fixProviderData: fixProviderData); using (var workspace = CreateWorkspaceFromOptions(originalCode, testOptions)) { if (expectedCodeAction) { Assert.True(expectedDocumentName != null, $"{nameof(expectedDocumentName)} should be present if {nameof(expectedCodeAction)} is true."); var oldDocumentId = workspace.Documents[0].Id; var expectedText = workspace.Documents[0].GetTextBuffer().CurrentSnapshot.GetText(); var spans = workspace.Documents[0].SelectedSpans; var codeActionTitle = string.Format(RenameFileCodeActionTitle, expectedDocumentName); var oldSolutionAndNewSolution = await TestOperationAsync( testOptions, workspace, expectedText, codeActionTitle); // The code action updated the Name of the file in-place var newSolution = oldSolutionAndNewSolution.Item2; var newDocument = newSolution.GetDocument(oldDocumentId); Assert.Equal(expectedDocumentName, newDocument.Name); if (destinationDocumentContainers != null) { Assert.Equal(destinationDocumentContainers, newDocument.Folders); } } else { var (actions, _) = await GetCodeActionsAsync(workspace, testOptions); if (actions.Length > 0) { var renameFileAction = actions.Any(action => action.Title.StartsWith(RenameFileCodeActionTitle)); Assert.False(renameFileAction, "Rename File to match type code action was not expected, but shows up."); } } } } private async Task<Tuple<Solution, Solution>> TestOperationAsync( TestParameters parameters, Workspaces.TestWorkspace workspace, string expectedCode, string operation) { var (actions, _) = await GetCodeActionsAsync(workspace, parameters); var action = actions.Single(a => a.Title.Equals(operation, StringComparison.CurrentCulture)); var operations = await action.GetOperationsAsync(CancellationToken.None); return await TestOperationsAsync(workspace, expectedText: expectedCode, operations: operations, conflictSpans: ImmutableArray<TextSpan>.Empty, renameSpans: ImmutableArray<TextSpan>.Empty, warningSpans: ImmutableArray<TextSpan>.Empty, navigationSpans: ImmutableArray<TextSpan>.Empty, expectedChangedDocumentId: null); } protected async Task TestMoveTypeToNewFileAsync( string originalCode, string expectedSourceTextAfterRefactoring, string expectedDocumentName, string destinationDocumentText, ImmutableArray<string> destinationDocumentContainers = default, bool expectedCodeAction = true, int index = 0, Action<Workspace> onAfterWorkspaceCreated = null) { var testOptions = new TestParameters(index: index); if (expectedCodeAction) { using var workspace = CreateWorkspaceFromOptions(originalCode, testOptions); onAfterWorkspaceCreated?.Invoke(workspace); // replace with default values on null. destinationDocumentContainers = destinationDocumentContainers.NullToEmpty(); var sourceDocumentId = workspace.Documents[0].Id; // Verify the newly added document and its text var oldSolutionAndNewSolution = await TestAddDocumentAsync( testOptions, workspace, destinationDocumentText, expectedDocumentName, destinationDocumentContainers); // Verify source document's text after moving type. var oldSolution = oldSolutionAndNewSolution.Item1; var newSolution = oldSolutionAndNewSolution.Item2; var changedDocumentIds = SolutionUtilities.GetChangedDocuments(oldSolution, newSolution); Assert.True(changedDocumentIds.Contains(sourceDocumentId), "source document was not changed."); var modifiedSourceDocument = newSolution.GetDocument(sourceDocumentId); var actualSourceTextAfterRefactoring = (await modifiedSourceDocument.GetTextAsync()).ToString(); Assert.Equal(expectedSourceTextAfterRefactoring, actualSourceTextAfterRefactoring); } else { await TestMissingAsync(originalCode); } } } }
-1
dotnet/roslyn
56,015
Remove obsolete APIs
Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
tmat
"2021-08-30T20:53:26Z"
"2021-09-02T16:56:01Z"
bdf1025480ad91f8db054959553257746f58f527
e782ce78f087060a3bc51737d3f07a6d102fb7b1
Remove obsolete APIs. Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
./src/Compilers/CSharp/Portable/Lowering/StateMachineRewriter/CapturedSymbol.cs
// 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. #nullable disable using System; using System.Collections.Immutable; using Microsoft.CodeAnalysis.CSharp.Symbols; namespace Microsoft.CodeAnalysis.CSharp { internal abstract class CapturedSymbolReplacement { public readonly bool IsReusable; public CapturedSymbolReplacement(bool isReusable) { this.IsReusable = isReusable; } /// <summary> /// Rewrite the replacement expression for the hoisted local so all synthesized field are accessed as members /// of the appropriate frame. /// </summary> public abstract BoundExpression Replacement(SyntaxNode node, Func<NamedTypeSymbol, BoundExpression> makeFrame); } internal sealed class CapturedToFrameSymbolReplacement : CapturedSymbolReplacement { public readonly LambdaCapturedVariable HoistedField; public CapturedToFrameSymbolReplacement(LambdaCapturedVariable hoistedField, bool isReusable) : base(isReusable) { this.HoistedField = hoistedField; } public override BoundExpression Replacement(SyntaxNode node, Func<NamedTypeSymbol, BoundExpression> makeFrame) { var frame = makeFrame(this.HoistedField.ContainingType); var field = this.HoistedField.AsMember((NamedTypeSymbol)frame.Type); return new BoundFieldAccess(node, frame, field, constantValueOpt: null); } } internal sealed class CapturedToStateMachineFieldReplacement : CapturedSymbolReplacement { public readonly StateMachineFieldSymbol HoistedField; public CapturedToStateMachineFieldReplacement(StateMachineFieldSymbol hoistedField, bool isReusable) : base(isReusable) { this.HoistedField = hoistedField; } public override BoundExpression Replacement(SyntaxNode node, Func<NamedTypeSymbol, BoundExpression> makeFrame) { var frame = makeFrame(this.HoistedField.ContainingType); var field = this.HoistedField.AsMember((NamedTypeSymbol)frame.Type); return new BoundFieldAccess(node, frame, field, constantValueOpt: null); } } internal sealed class CapturedToExpressionSymbolReplacement : CapturedSymbolReplacement { private readonly BoundExpression _replacement; public readonly ImmutableArray<StateMachineFieldSymbol> HoistedFields; public CapturedToExpressionSymbolReplacement(BoundExpression replacement, ImmutableArray<StateMachineFieldSymbol> hoistedFields, bool isReusable) : base(isReusable) { _replacement = replacement; this.HoistedFields = hoistedFields; } public override BoundExpression Replacement(SyntaxNode node, Func<NamedTypeSymbol, BoundExpression> makeFrame) { // By returning the same replacement each time, it is possible we // are constructing a DAG instead of a tree for the translation. // Because the bound trees are immutable that is usually harmless. return _replacement; } } }
// 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. #nullable disable using System; using System.Collections.Immutable; using Microsoft.CodeAnalysis.CSharp.Symbols; namespace Microsoft.CodeAnalysis.CSharp { internal abstract class CapturedSymbolReplacement { public readonly bool IsReusable; public CapturedSymbolReplacement(bool isReusable) { this.IsReusable = isReusable; } /// <summary> /// Rewrite the replacement expression for the hoisted local so all synthesized field are accessed as members /// of the appropriate frame. /// </summary> public abstract BoundExpression Replacement(SyntaxNode node, Func<NamedTypeSymbol, BoundExpression> makeFrame); } internal sealed class CapturedToFrameSymbolReplacement : CapturedSymbolReplacement { public readonly LambdaCapturedVariable HoistedField; public CapturedToFrameSymbolReplacement(LambdaCapturedVariable hoistedField, bool isReusable) : base(isReusable) { this.HoistedField = hoistedField; } public override BoundExpression Replacement(SyntaxNode node, Func<NamedTypeSymbol, BoundExpression> makeFrame) { var frame = makeFrame(this.HoistedField.ContainingType); var field = this.HoistedField.AsMember((NamedTypeSymbol)frame.Type); return new BoundFieldAccess(node, frame, field, constantValueOpt: null); } } internal sealed class CapturedToStateMachineFieldReplacement : CapturedSymbolReplacement { public readonly StateMachineFieldSymbol HoistedField; public CapturedToStateMachineFieldReplacement(StateMachineFieldSymbol hoistedField, bool isReusable) : base(isReusable) { this.HoistedField = hoistedField; } public override BoundExpression Replacement(SyntaxNode node, Func<NamedTypeSymbol, BoundExpression> makeFrame) { var frame = makeFrame(this.HoistedField.ContainingType); var field = this.HoistedField.AsMember((NamedTypeSymbol)frame.Type); return new BoundFieldAccess(node, frame, field, constantValueOpt: null); } } internal sealed class CapturedToExpressionSymbolReplacement : CapturedSymbolReplacement { private readonly BoundExpression _replacement; public readonly ImmutableArray<StateMachineFieldSymbol> HoistedFields; public CapturedToExpressionSymbolReplacement(BoundExpression replacement, ImmutableArray<StateMachineFieldSymbol> hoistedFields, bool isReusable) : base(isReusable) { _replacement = replacement; this.HoistedFields = hoistedFields; } public override BoundExpression Replacement(SyntaxNode node, Func<NamedTypeSymbol, BoundExpression> makeFrame) { // By returning the same replacement each time, it is possible we // are constructing a DAG instead of a tree for the translation. // Because the bound trees are immutable that is usually harmless. return _replacement; } } }
-1
dotnet/roslyn
56,015
Remove obsolete APIs
Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
tmat
"2021-08-30T20:53:26Z"
"2021-09-02T16:56:01Z"
bdf1025480ad91f8db054959553257746f58f527
e782ce78f087060a3bc51737d3f07a6d102fb7b1
Remove obsolete APIs. Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
./src/Compilers/CSharp/Test/Emit/Attributes/AttributeTests_Embedded.cs
// 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. #nullable disable using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using System.Linq; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class AttributeTests_Embedded : CSharpTestBase { [Fact] public void ReferencingEmbeddedAttributesFromTheSameAssemblySucceeds() { var code = @" namespace Microsoft.CodeAnalysis { internal class EmbeddedAttribute : System.Attribute { } } namespace TestReference { [Microsoft.CodeAnalysis.Embedded] internal class TestType1 { } [Microsoft.CodeAnalysis.EmbeddedAttribute] internal class TestType2 { } internal class TestType3 { } } class Program { public static void Main() { var obj1 = new TestReference.TestType1(); var obj2 = new TestReference.TestType2(); var obj3 = new TestReference.TestType3(); } }"; CreateCompilation(code).VerifyEmitDiagnostics(); } [Fact] public void ReferencingEmbeddedAttributesFromADifferentAssemblyFails_Internal() { var reference = CreateCompilation(@" [assembly:System.Runtime.CompilerServices.InternalsVisibleToAttribute(""Source"")] namespace Microsoft.CodeAnalysis { internal class EmbeddedAttribute : System.Attribute { } } namespace TestReference { [Microsoft.CodeAnalysis.Embedded] internal class TestType1 { } [Microsoft.CodeAnalysis.EmbeddedAttribute] internal class TestType2 { } internal class TestType3 { } }"); var code = @" class Program { public static void Main() { var obj1 = new TestReference.TestType1(); var obj2 = new TestReference.TestType2(); var obj3 = new TestReference.TestType3(); // This should be fine } }"; CreateCompilation(code, references: new[] { reference.ToMetadataReference() }, assemblyName: "Source").VerifyDiagnostics( // (6,38): error CS0234: The type or namespace name 'TestType1' does not exist in the namespace 'TestReference' (are you missing an assembly reference?) // var obj1 = new TestReference.TestType1(); Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "TestType1").WithArguments("TestType1", "TestReference").WithLocation(6, 38), // (7,38): error CS0234: The type or namespace name 'TestType2' does not exist in the namespace 'TestReference' (are you missing an assembly reference?) // var obj2 = new TestReference.TestType2(); Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "TestType2").WithArguments("TestType2", "TestReference").WithLocation(7, 38)); } [Fact] public void ReferencingEmbeddedAttributesFromADifferentAssemblyFails_Module() { var module = CreateCompilation(@" namespace Microsoft.CodeAnalysis { internal class EmbeddedAttribute : System.Attribute { } } namespace TestReference { [Microsoft.CodeAnalysis.Embedded] internal class TestType1 { } [Microsoft.CodeAnalysis.EmbeddedAttribute] internal class TestType2 { } internal class TestType3 { } }", options: TestOptions.ReleaseModule); var reference = ModuleMetadata.CreateFromImage(module.EmitToArray()).GetReference(); var code = @" class Program { public static void Main() { var obj1 = new TestReference.TestType1(); var obj2 = new TestReference.TestType2(); var obj3 = new TestReference.TestType3(); // This should be fine } }"; CreateCompilation(code, references: new[] { reference }, assemblyName: "Source").VerifyDiagnostics( // (6,38): error CS0234: The type or namespace name 'TestType1' does not exist in the namespace 'TestReference' (are you missing an assembly reference?) // var obj1 = new TestReference.TestType1(); Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "TestType1").WithArguments("TestType1", "TestReference").WithLocation(6, 38), // (7,38): error CS0234: The type or namespace name 'TestType2' does not exist in the namespace 'TestReference' (are you missing an assembly reference?) // var obj2 = new TestReference.TestType2(); Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "TestType2").WithArguments("TestType2", "TestReference").WithLocation(7, 38)); } [Fact] public void ReferencingEmbeddedAttributesFromADifferentAssemblyFails_Public() { var reference = CreateCompilation(@" namespace Microsoft.CodeAnalysis { internal class EmbeddedAttribute : System.Attribute { } } namespace TestReference { [Microsoft.CodeAnalysis.Embedded] public class TestType1 { } [Microsoft.CodeAnalysis.EmbeddedAttribute] public class TestType2 { } public class TestType3 { } }"); var code = @" class Program { public static void Main() { var obj1 = new TestReference.TestType1(); var obj2 = new TestReference.TestType2(); var obj3 = new TestReference.TestType3(); // This should be fine } }"; CreateCompilation(code, references: new[] { reference.ToMetadataReference() }).VerifyDiagnostics( // (6,38): error CS0234: The type or namespace name 'TestType1' does not exist in the namespace 'TestReference' (are you missing an assembly reference?) // var obj1 = new TestReference.TestType1(); Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "TestType1").WithArguments("TestType1", "TestReference").WithLocation(6, 38), // (7,38): error CS0234: The type or namespace name 'TestType2' does not exist in the namespace 'TestReference' (are you missing an assembly reference?) // var obj2 = new TestReference.TestType2(); Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "TestType2").WithArguments("TestType2", "TestReference").WithLocation(7, 38)); } [Fact] public void EmbeddedAttributeInSourceIsAllowedIfCompilerDoesNotNeedToGenerateOne() { var code = @" namespace Microsoft.CodeAnalysis { public class EmbeddedAttribute : System.Attribute { } } namespace OtherNamespace { [Microsoft.CodeAnalysis.EmbeddedAttribute] public class TestReference { public static int GetValue() => 3; } } class Test { public static void Main() { // This should be fine, as the compiler doesn't need to use an embedded attribute for this compilation System.Console.Write(OtherNamespace.TestReference.GetValue()); } }"; CompileAndVerify(code, verify: Verification.Passes, expectedOutput: "3"); } [Fact] public void EmbeddedAttributeInSourceShouldTriggerAnErrorIfCompilerNeedsToGenerateOne() { var code = @" namespace Microsoft.CodeAnalysis { public class EmbeddedAttribute : System.Attribute { } } class Test { public void M(in int p) { // This should trigger generating another EmbeddedAttribute } }"; CreateCompilation(code, assemblyName: "testModule").VerifyEmitDiagnostics( // (4,18): error CS8336: The type name 'Microsoft.CodeAnalysis.EmbeddedAttribute' is reserved to be used by the compiler. // public class EmbeddedAttribute : System.Attribute { } Diagnostic(ErrorCode.ERR_TypeReserved, "EmbeddedAttribute").WithArguments("Microsoft.CodeAnalysis.EmbeddedAttribute").WithLocation(4, 18)); } [Fact] public void EmbeddedAttributeInReferencedModuleShouldTriggerAnErrorIfCompilerNeedsToGenerateOne() { var module = CreateCompilation(options: TestOptions.ReleaseModule, assemblyName: "testModule", source: @" namespace Microsoft.CodeAnalysis { public class EmbeddedAttribute : System.Attribute { } }"); var moduleRef = ModuleMetadata.CreateFromImage(module.EmitToArray()).GetReference(); var code = @" class Test { public void M(in int p) { // This should trigger generating another EmbeddedAttribute } }"; CreateCompilation(code, references: new[] { moduleRef }).VerifyEmitDiagnostics( // error CS8004: Type 'EmbeddedAttribute' exported from module 'testModule.netmodule' conflicts with type declared in primary module of this assembly. Diagnostic(ErrorCode.ERR_ExportedTypeConflictsWithDeclaration).WithArguments("Microsoft.CodeAnalysis.EmbeddedAttribute", "testModule.netmodule").WithLocation(1, 1)); } [Fact] public void EmbeddedAttributeForwardedToAnotherAssemblyShouldTriggerAnError() { var reference = CreateCompilation(@" namespace Microsoft.CodeAnalysis { public class EmbeddedAttribute : System.Attribute { } }", assemblyName: "reference").ToMetadataReference(); var code = @" [assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(Microsoft.CodeAnalysis.EmbeddedAttribute))] class Test { public void M(in int p) { // This should trigger generating another EmbeddedAttribute } }"; CreateCompilation(code, references: new[] { reference }).VerifyEmitDiagnostics( // error CS8006: Forwarded type 'EmbeddedAttribute' conflicts with type declared in primary module of this assembly. Diagnostic(ErrorCode.ERR_ForwardedTypeConflictsWithDeclaration).WithArguments("Microsoft.CodeAnalysis.EmbeddedAttribute").WithLocation(1, 1)); } [Fact] public void CompilerShouldIgnorePublicEmbeddedAttributesInReferencedAssemblies() { var reference = CreateCompilation(assemblyName: "testRef", source: @" namespace Microsoft.CodeAnalysis { public class EmbeddedAttribute : System.Attribute { } } namespace OtherNamespace { public class TestReference { } }").ToMetadataReference(); var code = @" class Test { // This should trigger generating another EmbeddedAttribute public void M(in int p) { var obj = new OtherNamespace.TestReference(); // This should be fine } }"; CompileAndVerify(code, verify: Verification.Passes, references: new[] { reference }, symbolValidator: module => { var attributeName = AttributeDescription.CodeAnalysisEmbeddedAttribute.FullName; var referenceAttribute = module.GetReferencedAssemblySymbols().Single(assembly => assembly.Name == "testRef").GetTypeByMetadataName(attributeName); Assert.NotNull(referenceAttribute); var generatedAttribute = module.ContainingAssembly.GetTypeByMetadataName(attributeName); Assert.NotNull(generatedAttribute); Assert.False(referenceAttribute.Equals(generatedAttribute)); }); } [Fact] public void SynthesizingAttributeRequiresSystemAttribute_NonExisting() { var code = @" namespace System { public class Object {} public class Void {} } public class Test { public void M(in object x) { } // should trigger synthesizing IsReadOnly }"; CreateEmptyCompilation(code).VerifyEmitDiagnostics(CodeAnalysis.Emit.EmitOptions.Default.WithRuntimeMetadataVersion("v4.0.30319"), // error CS0518: Predefined type 'System.Attribute' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1), // error CS0518: Predefined type 'System.Attribute' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1)); } [Fact] public void SynthesizingAttributeRequiresSystemAttribute_NoSystemObject() { var code = @" namespace System { public class Attribute {} public class Void {} } public class Test { public object M(in object x) { return x; } // should trigger synthesizing IsReadOnly }"; CreateEmptyCompilation(code).VerifyEmitDiagnostics(CodeAnalysis.Emit.EmitOptions.Default.WithRuntimeMetadataVersion("v4.0.30319"), // (5,18): error CS0518: Predefined type 'System.Object' is not defined or imported // public class Void {} Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "Void").WithArguments("System.Object").WithLocation(5, 18), // (7,14): error CS0518: Predefined type 'System.Object' is not defined or imported // public class Test Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "Test").WithArguments("System.Object").WithLocation(7, 14), // (4,18): error CS0518: Predefined type 'System.Object' is not defined or imported // public class Attribute {} Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "Attribute").WithArguments("System.Object").WithLocation(4, 18), // (9,24): error CS0518: Predefined type 'System.Object' is not defined or imported // public object M(in object x) { return x; } // should trigger synthesizing IsReadOnly Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "object").WithArguments("System.Object").WithLocation(9, 24), // (9,12): error CS0518: Predefined type 'System.Object' is not defined or imported // public object M(in object x) { return x; } // should trigger synthesizing IsReadOnly Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "object").WithArguments("System.Object").WithLocation(9, 12), // (4,18): error CS1729: 'object' does not contain a constructor that takes 0 arguments // public class Attribute {} Diagnostic(ErrorCode.ERR_BadCtorArgCount, "Attribute").WithArguments("object", "0").WithLocation(4, 18), // (5,18): error CS1729: 'object' does not contain a constructor that takes 0 arguments // public class Void {} Diagnostic(ErrorCode.ERR_BadCtorArgCount, "Void").WithArguments("object", "0").WithLocation(5, 18), // (7,14): error CS1729: 'object' does not contain a constructor that takes 0 arguments // public class Test Diagnostic(ErrorCode.ERR_BadCtorArgCount, "Test").WithArguments("object", "0").WithLocation(7, 14)); } [Fact] public void SynthesizingAttributeRequiresSystemAttribute_NoSystemVoid() { var code = @" namespace System { public class Attribute {} public class Object {} } public class Test { public object M(in object x) { return x; } // should trigger synthesizing IsReadOnly }"; CreateEmptyCompilation(code).VerifyEmitDiagnostics(CodeAnalysis.Emit.EmitOptions.Default.WithRuntimeMetadataVersion("v4.0.30319"), // (4,18): error CS0518: Predefined type 'System.Void' is not defined or imported // public class Attribute {} Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "Attribute").WithArguments("System.Void").WithLocation(4, 18), // (7,14): error CS0518: Predefined type 'System.Void' is not defined or imported // public class Test Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "Test").WithArguments("System.Void").WithLocation(7, 14), // error CS0518: Predefined type 'System.Void' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Void").WithLocation(1, 1), // error CS0518: Predefined type 'System.Void' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Void").WithLocation(1, 1)); } [Fact] public void SynthesizingAttributeRequiresSystemAttribute_NoDefaultConstructor() { var code = @" namespace System { public class Object {} public class Void {} public class Attribute { public Attribute(object p) { } } } public class Test { public void M(in object x) { } // should trigger synthesizing IsReadOnly }"; CreateEmptyCompilation(code).VerifyEmitDiagnostics(CodeAnalysis.Emit.EmitOptions.Default.WithRuntimeMetadataVersion("v4.0.30319"), // error CS1729: 'Attribute' does not contain a constructor that takes 0 arguments Diagnostic(ErrorCode.ERR_BadCtorArgCount).WithArguments("System.Attribute", "0").WithLocation(1, 1), // error CS1729: 'Attribute' does not contain a constructor that takes 0 arguments Diagnostic(ErrorCode.ERR_BadCtorArgCount).WithArguments("System.Attribute", "0").WithLocation(1, 1)); } [Fact] public void EmbeddedTypesInAnAssemblyAreNotExposedExternally() { var compilation1 = CreateCompilation(@" namespace Microsoft.CodeAnalysis { public class EmbeddedAttribute : System.Attribute { } } [Microsoft.CodeAnalysis.Embedded] public class TestReference1 { } public class TestReference2 { } "); Assert.NotNull(compilation1.GetTypeByMetadataName("TestReference1")); Assert.NotNull(compilation1.GetTypeByMetadataName("TestReference2")); var compilation2 = CreateCompilation("", references: new[] { compilation1.EmitToImageReference() }); Assert.Null(compilation2.GetTypeByMetadataName("TestReference1")); Assert.NotNull(compilation2.GetTypeByMetadataName("TestReference2")); } } }
// 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. #nullable disable using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using System.Linq; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class AttributeTests_Embedded : CSharpTestBase { [Fact] public void ReferencingEmbeddedAttributesFromTheSameAssemblySucceeds() { var code = @" namespace Microsoft.CodeAnalysis { internal class EmbeddedAttribute : System.Attribute { } } namespace TestReference { [Microsoft.CodeAnalysis.Embedded] internal class TestType1 { } [Microsoft.CodeAnalysis.EmbeddedAttribute] internal class TestType2 { } internal class TestType3 { } } class Program { public static void Main() { var obj1 = new TestReference.TestType1(); var obj2 = new TestReference.TestType2(); var obj3 = new TestReference.TestType3(); } }"; CreateCompilation(code).VerifyEmitDiagnostics(); } [Fact] public void ReferencingEmbeddedAttributesFromADifferentAssemblyFails_Internal() { var reference = CreateCompilation(@" [assembly:System.Runtime.CompilerServices.InternalsVisibleToAttribute(""Source"")] namespace Microsoft.CodeAnalysis { internal class EmbeddedAttribute : System.Attribute { } } namespace TestReference { [Microsoft.CodeAnalysis.Embedded] internal class TestType1 { } [Microsoft.CodeAnalysis.EmbeddedAttribute] internal class TestType2 { } internal class TestType3 { } }"); var code = @" class Program { public static void Main() { var obj1 = new TestReference.TestType1(); var obj2 = new TestReference.TestType2(); var obj3 = new TestReference.TestType3(); // This should be fine } }"; CreateCompilation(code, references: new[] { reference.ToMetadataReference() }, assemblyName: "Source").VerifyDiagnostics( // (6,38): error CS0234: The type or namespace name 'TestType1' does not exist in the namespace 'TestReference' (are you missing an assembly reference?) // var obj1 = new TestReference.TestType1(); Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "TestType1").WithArguments("TestType1", "TestReference").WithLocation(6, 38), // (7,38): error CS0234: The type or namespace name 'TestType2' does not exist in the namespace 'TestReference' (are you missing an assembly reference?) // var obj2 = new TestReference.TestType2(); Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "TestType2").WithArguments("TestType2", "TestReference").WithLocation(7, 38)); } [Fact] public void ReferencingEmbeddedAttributesFromADifferentAssemblyFails_Module() { var module = CreateCompilation(@" namespace Microsoft.CodeAnalysis { internal class EmbeddedAttribute : System.Attribute { } } namespace TestReference { [Microsoft.CodeAnalysis.Embedded] internal class TestType1 { } [Microsoft.CodeAnalysis.EmbeddedAttribute] internal class TestType2 { } internal class TestType3 { } }", options: TestOptions.ReleaseModule); var reference = ModuleMetadata.CreateFromImage(module.EmitToArray()).GetReference(); var code = @" class Program { public static void Main() { var obj1 = new TestReference.TestType1(); var obj2 = new TestReference.TestType2(); var obj3 = new TestReference.TestType3(); // This should be fine } }"; CreateCompilation(code, references: new[] { reference }, assemblyName: "Source").VerifyDiagnostics( // (6,38): error CS0234: The type or namespace name 'TestType1' does not exist in the namespace 'TestReference' (are you missing an assembly reference?) // var obj1 = new TestReference.TestType1(); Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "TestType1").WithArguments("TestType1", "TestReference").WithLocation(6, 38), // (7,38): error CS0234: The type or namespace name 'TestType2' does not exist in the namespace 'TestReference' (are you missing an assembly reference?) // var obj2 = new TestReference.TestType2(); Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "TestType2").WithArguments("TestType2", "TestReference").WithLocation(7, 38)); } [Fact] public void ReferencingEmbeddedAttributesFromADifferentAssemblyFails_Public() { var reference = CreateCompilation(@" namespace Microsoft.CodeAnalysis { internal class EmbeddedAttribute : System.Attribute { } } namespace TestReference { [Microsoft.CodeAnalysis.Embedded] public class TestType1 { } [Microsoft.CodeAnalysis.EmbeddedAttribute] public class TestType2 { } public class TestType3 { } }"); var code = @" class Program { public static void Main() { var obj1 = new TestReference.TestType1(); var obj2 = new TestReference.TestType2(); var obj3 = new TestReference.TestType3(); // This should be fine } }"; CreateCompilation(code, references: new[] { reference.ToMetadataReference() }).VerifyDiagnostics( // (6,38): error CS0234: The type or namespace name 'TestType1' does not exist in the namespace 'TestReference' (are you missing an assembly reference?) // var obj1 = new TestReference.TestType1(); Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "TestType1").WithArguments("TestType1", "TestReference").WithLocation(6, 38), // (7,38): error CS0234: The type or namespace name 'TestType2' does not exist in the namespace 'TestReference' (are you missing an assembly reference?) // var obj2 = new TestReference.TestType2(); Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "TestType2").WithArguments("TestType2", "TestReference").WithLocation(7, 38)); } [Fact] public void EmbeddedAttributeInSourceIsAllowedIfCompilerDoesNotNeedToGenerateOne() { var code = @" namespace Microsoft.CodeAnalysis { public class EmbeddedAttribute : System.Attribute { } } namespace OtherNamespace { [Microsoft.CodeAnalysis.EmbeddedAttribute] public class TestReference { public static int GetValue() => 3; } } class Test { public static void Main() { // This should be fine, as the compiler doesn't need to use an embedded attribute for this compilation System.Console.Write(OtherNamespace.TestReference.GetValue()); } }"; CompileAndVerify(code, verify: Verification.Passes, expectedOutput: "3"); } [Fact] public void EmbeddedAttributeInSourceShouldTriggerAnErrorIfCompilerNeedsToGenerateOne() { var code = @" namespace Microsoft.CodeAnalysis { public class EmbeddedAttribute : System.Attribute { } } class Test { public void M(in int p) { // This should trigger generating another EmbeddedAttribute } }"; CreateCompilation(code, assemblyName: "testModule").VerifyEmitDiagnostics( // (4,18): error CS8336: The type name 'Microsoft.CodeAnalysis.EmbeddedAttribute' is reserved to be used by the compiler. // public class EmbeddedAttribute : System.Attribute { } Diagnostic(ErrorCode.ERR_TypeReserved, "EmbeddedAttribute").WithArguments("Microsoft.CodeAnalysis.EmbeddedAttribute").WithLocation(4, 18)); } [Fact] public void EmbeddedAttributeInReferencedModuleShouldTriggerAnErrorIfCompilerNeedsToGenerateOne() { var module = CreateCompilation(options: TestOptions.ReleaseModule, assemblyName: "testModule", source: @" namespace Microsoft.CodeAnalysis { public class EmbeddedAttribute : System.Attribute { } }"); var moduleRef = ModuleMetadata.CreateFromImage(module.EmitToArray()).GetReference(); var code = @" class Test { public void M(in int p) { // This should trigger generating another EmbeddedAttribute } }"; CreateCompilation(code, references: new[] { moduleRef }).VerifyEmitDiagnostics( // error CS8004: Type 'EmbeddedAttribute' exported from module 'testModule.netmodule' conflicts with type declared in primary module of this assembly. Diagnostic(ErrorCode.ERR_ExportedTypeConflictsWithDeclaration).WithArguments("Microsoft.CodeAnalysis.EmbeddedAttribute", "testModule.netmodule").WithLocation(1, 1)); } [Fact] public void EmbeddedAttributeForwardedToAnotherAssemblyShouldTriggerAnError() { var reference = CreateCompilation(@" namespace Microsoft.CodeAnalysis { public class EmbeddedAttribute : System.Attribute { } }", assemblyName: "reference").ToMetadataReference(); var code = @" [assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(Microsoft.CodeAnalysis.EmbeddedAttribute))] class Test { public void M(in int p) { // This should trigger generating another EmbeddedAttribute } }"; CreateCompilation(code, references: new[] { reference }).VerifyEmitDiagnostics( // error CS8006: Forwarded type 'EmbeddedAttribute' conflicts with type declared in primary module of this assembly. Diagnostic(ErrorCode.ERR_ForwardedTypeConflictsWithDeclaration).WithArguments("Microsoft.CodeAnalysis.EmbeddedAttribute").WithLocation(1, 1)); } [Fact] public void CompilerShouldIgnorePublicEmbeddedAttributesInReferencedAssemblies() { var reference = CreateCompilation(assemblyName: "testRef", source: @" namespace Microsoft.CodeAnalysis { public class EmbeddedAttribute : System.Attribute { } } namespace OtherNamespace { public class TestReference { } }").ToMetadataReference(); var code = @" class Test { // This should trigger generating another EmbeddedAttribute public void M(in int p) { var obj = new OtherNamespace.TestReference(); // This should be fine } }"; CompileAndVerify(code, verify: Verification.Passes, references: new[] { reference }, symbolValidator: module => { var attributeName = AttributeDescription.CodeAnalysisEmbeddedAttribute.FullName; var referenceAttribute = module.GetReferencedAssemblySymbols().Single(assembly => assembly.Name == "testRef").GetTypeByMetadataName(attributeName); Assert.NotNull(referenceAttribute); var generatedAttribute = module.ContainingAssembly.GetTypeByMetadataName(attributeName); Assert.NotNull(generatedAttribute); Assert.False(referenceAttribute.Equals(generatedAttribute)); }); } [Fact] public void SynthesizingAttributeRequiresSystemAttribute_NonExisting() { var code = @" namespace System { public class Object {} public class Void {} } public class Test { public void M(in object x) { } // should trigger synthesizing IsReadOnly }"; CreateEmptyCompilation(code).VerifyEmitDiagnostics(CodeAnalysis.Emit.EmitOptions.Default.WithRuntimeMetadataVersion("v4.0.30319"), // error CS0518: Predefined type 'System.Attribute' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1), // error CS0518: Predefined type 'System.Attribute' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1)); } [Fact] public void SynthesizingAttributeRequiresSystemAttribute_NoSystemObject() { var code = @" namespace System { public class Attribute {} public class Void {} } public class Test { public object M(in object x) { return x; } // should trigger synthesizing IsReadOnly }"; CreateEmptyCompilation(code).VerifyEmitDiagnostics(CodeAnalysis.Emit.EmitOptions.Default.WithRuntimeMetadataVersion("v4.0.30319"), // (5,18): error CS0518: Predefined type 'System.Object' is not defined or imported // public class Void {} Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "Void").WithArguments("System.Object").WithLocation(5, 18), // (7,14): error CS0518: Predefined type 'System.Object' is not defined or imported // public class Test Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "Test").WithArguments("System.Object").WithLocation(7, 14), // (4,18): error CS0518: Predefined type 'System.Object' is not defined or imported // public class Attribute {} Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "Attribute").WithArguments("System.Object").WithLocation(4, 18), // (9,24): error CS0518: Predefined type 'System.Object' is not defined or imported // public object M(in object x) { return x; } // should trigger synthesizing IsReadOnly Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "object").WithArguments("System.Object").WithLocation(9, 24), // (9,12): error CS0518: Predefined type 'System.Object' is not defined or imported // public object M(in object x) { return x; } // should trigger synthesizing IsReadOnly Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "object").WithArguments("System.Object").WithLocation(9, 12), // (4,18): error CS1729: 'object' does not contain a constructor that takes 0 arguments // public class Attribute {} Diagnostic(ErrorCode.ERR_BadCtorArgCount, "Attribute").WithArguments("object", "0").WithLocation(4, 18), // (5,18): error CS1729: 'object' does not contain a constructor that takes 0 arguments // public class Void {} Diagnostic(ErrorCode.ERR_BadCtorArgCount, "Void").WithArguments("object", "0").WithLocation(5, 18), // (7,14): error CS1729: 'object' does not contain a constructor that takes 0 arguments // public class Test Diagnostic(ErrorCode.ERR_BadCtorArgCount, "Test").WithArguments("object", "0").WithLocation(7, 14)); } [Fact] public void SynthesizingAttributeRequiresSystemAttribute_NoSystemVoid() { var code = @" namespace System { public class Attribute {} public class Object {} } public class Test { public object M(in object x) { return x; } // should trigger synthesizing IsReadOnly }"; CreateEmptyCompilation(code).VerifyEmitDiagnostics(CodeAnalysis.Emit.EmitOptions.Default.WithRuntimeMetadataVersion("v4.0.30319"), // (4,18): error CS0518: Predefined type 'System.Void' is not defined or imported // public class Attribute {} Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "Attribute").WithArguments("System.Void").WithLocation(4, 18), // (7,14): error CS0518: Predefined type 'System.Void' is not defined or imported // public class Test Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "Test").WithArguments("System.Void").WithLocation(7, 14), // error CS0518: Predefined type 'System.Void' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Void").WithLocation(1, 1), // error CS0518: Predefined type 'System.Void' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Void").WithLocation(1, 1)); } [Fact] public void SynthesizingAttributeRequiresSystemAttribute_NoDefaultConstructor() { var code = @" namespace System { public class Object {} public class Void {} public class Attribute { public Attribute(object p) { } } } public class Test { public void M(in object x) { } // should trigger synthesizing IsReadOnly }"; CreateEmptyCompilation(code).VerifyEmitDiagnostics(CodeAnalysis.Emit.EmitOptions.Default.WithRuntimeMetadataVersion("v4.0.30319"), // error CS1729: 'Attribute' does not contain a constructor that takes 0 arguments Diagnostic(ErrorCode.ERR_BadCtorArgCount).WithArguments("System.Attribute", "0").WithLocation(1, 1), // error CS1729: 'Attribute' does not contain a constructor that takes 0 arguments Diagnostic(ErrorCode.ERR_BadCtorArgCount).WithArguments("System.Attribute", "0").WithLocation(1, 1)); } [Fact] public void EmbeddedTypesInAnAssemblyAreNotExposedExternally() { var compilation1 = CreateCompilation(@" namespace Microsoft.CodeAnalysis { public class EmbeddedAttribute : System.Attribute { } } [Microsoft.CodeAnalysis.Embedded] public class TestReference1 { } public class TestReference2 { } "); Assert.NotNull(compilation1.GetTypeByMetadataName("TestReference1")); Assert.NotNull(compilation1.GetTypeByMetadataName("TestReference2")); var compilation2 = CreateCompilation("", references: new[] { compilation1.EmitToImageReference() }); Assert.Null(compilation2.GetTypeByMetadataName("TestReference1")); Assert.NotNull(compilation2.GetTypeByMetadataName("TestReference2")); } } }
-1
dotnet/roslyn
56,015
Remove obsolete APIs
Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
tmat
"2021-08-30T20:53:26Z"
"2021-09-02T16:56:01Z"
bdf1025480ad91f8db054959553257746f58f527
e782ce78f087060a3bc51737d3f07a6d102fb7b1
Remove obsolete APIs. Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
./src/Tools/ExternalAccess/OmniSharp.CSharp/Completion/OmniSharpCompletionProviderNames.cs
// 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. using Microsoft.CodeAnalysis.CSharp.Completion.Providers; namespace Microsoft.CodeAnalysis.ExternalAccess.OmniSharp.CSharp.Completion { internal static class OmniSharpCompletionProviderNames { internal static string ObjectCreationCompletionProvider = typeof(ObjectCreationCompletionProvider).FullName; internal static string OverrideCompletionProvider = typeof(OverrideCompletionProvider).FullName; internal static string PartialMethodCompletionProvider = typeof(PartialMethodCompletionProvider).FullName; internal static string InternalsVisibleToCompletionProvider = typeof(InternalsVisibleToCompletionProvider).FullName; internal static string TypeImportCompletionProvider = typeof(TypeImportCompletionProvider).FullName; internal static string ExtensionMethodImportCompletionProvider = typeof(ExtensionMethodImportCompletionProvider).FullName; } }
// 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. using Microsoft.CodeAnalysis.CSharp.Completion.Providers; namespace Microsoft.CodeAnalysis.ExternalAccess.OmniSharp.CSharp.Completion { internal static class OmniSharpCompletionProviderNames { internal static string ObjectCreationCompletionProvider = typeof(ObjectCreationCompletionProvider).FullName; internal static string OverrideCompletionProvider = typeof(OverrideCompletionProvider).FullName; internal static string PartialMethodCompletionProvider = typeof(PartialMethodCompletionProvider).FullName; internal static string InternalsVisibleToCompletionProvider = typeof(InternalsVisibleToCompletionProvider).FullName; internal static string TypeImportCompletionProvider = typeof(TypeImportCompletionProvider).FullName; internal static string ExtensionMethodImportCompletionProvider = typeof(ExtensionMethodImportCompletionProvider).FullName; } }
-1
dotnet/roslyn
56,015
Remove obsolete APIs
Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
tmat
"2021-08-30T20:53:26Z"
"2021-09-02T16:56:01Z"
bdf1025480ad91f8db054959553257746f58f527
e782ce78f087060a3bc51737d3f07a6d102fb7b1
Remove obsolete APIs. Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
./src/Features/LanguageServer/ProtocolUnitTests/Ordering/RequestOrderingTests.cs
// 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. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.LanguageServer.Protocol; using Roslyn.Test.Utilities; using Xunit; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.RequestOrdering { public partial class RequestOrderingTests : AbstractLanguageServerProtocolTests { protected override TestComposition Composition => base.Composition .AddParts(typeof(MutatingRequestHandlerProvider)) .AddParts(typeof(NonMutatingRequestHandlerProvider)) .AddParts(typeof(FailingRequestHandlerProvider)) .AddParts(typeof(FailingMutatingRequestHandlerProvider)) .AddParts(typeof(NonLSPSolutionRequestHandlerProvider)) .AddParts(typeof(LongRunningNonMutatingRequestHandlerProvider)); [Fact] public async Task MutatingRequestsDontOverlap() { var requests = new[] { new TestRequest(MutatingRequestHandler.MethodName), new TestRequest(MutatingRequestHandler.MethodName), new TestRequest(MutatingRequestHandler.MethodName), }; using var testLspServer = CreateTestLspServer("class C { }", out _); var responses = await TestAsync(testLspServer, requests); // Every request should have started at or after the one before it Assert.True(responses[1].StartTime >= responses[0].EndTime); Assert.True(responses[2].StartTime >= responses[1].EndTime); } [Fact] public async Task NonMutatingRequestsOverlap() { var requests = new[] { new TestRequest(NonMutatingRequestHandler.MethodName), new TestRequest(NonMutatingRequestHandler.MethodName), new TestRequest(NonMutatingRequestHandler.MethodName), }; using var testLspServer = CreateTestLspServer("class C { }", out _); var responses = await TestAsync(testLspServer, requests); // Every request should have started immediately, without waiting Assert.True(responses[1].StartTime < responses[0].EndTime); Assert.True(responses[2].StartTime < responses[1].EndTime); } [Fact] public async Task NonMutatingWaitsForMutating() { var requests = new[] { new TestRequest(MutatingRequestHandler.MethodName), new TestRequest(NonMutatingRequestHandler.MethodName), new TestRequest(NonMutatingRequestHandler.MethodName), }; using var testLspServer = CreateTestLspServer("class C { }", out _); var responses = await TestAsync(testLspServer, requests); // The non mutating tasks should have waited for the first task to finish Assert.True(responses[1].StartTime >= responses[0].EndTime); Assert.True(responses[2].StartTime >= responses[0].EndTime); // The non mutating requests shouldn't have waited for each other Assert.True(responses[1].StartTime < responses[2].EndTime); Assert.True(responses[2].StartTime < responses[1].EndTime); } [Fact] public async Task MutatingDoesntWaitForNonMutating() { var requests = new[] { new TestRequest(NonMutatingRequestHandler.MethodName), new TestRequest(NonMutatingRequestHandler.MethodName), new TestRequest(MutatingRequestHandler.MethodName), }; using var testLspServer = CreateTestLspServer("class C { }", out _); var responses = await TestAsync(testLspServer, requests); // All tasks should start without waiting for any to finish Assert.True(responses[1].StartTime < responses[0].EndTime); Assert.True(responses[2].StartTime < responses[0].EndTime); Assert.True(responses[1].StartTime < responses[2].EndTime); Assert.True(responses[2].StartTime < responses[1].EndTime); } [Fact] public async Task ThrowingTaskDoesntBringDownQueue() { var requests = new[] { new TestRequest(FailingRequestHandler.MethodName), new TestRequest(NonMutatingRequestHandler.MethodName), new TestRequest(MutatingRequestHandler.MethodName), new TestRequest(NonMutatingRequestHandler.MethodName), }; using var testLspServer = CreateTestLspServer("class C { }", out _); var waitables = StartTestRun(testLspServer, requests); // first task should fail await Assert.ThrowsAsync<InvalidOperationException>(() => waitables[0]); // remaining tasks should have executed normally var responses = await Task.WhenAll(waitables.Skip(1)); Assert.Empty(responses.Where(r => r.StartTime == default)); Assert.All(responses, r => Assert.True(r.EndTime > r.StartTime)); } [Fact] public async Task LongRunningSynchronousNonMutatingTaskDoesNotBlockQueue() { var requests = new[] { new TestRequest(LongRunningNonMutatingRequestHandler.MethodName), new TestRequest(MutatingRequestHandler.MethodName), new TestRequest(NonMutatingRequestHandler.MethodName), }; using var testLspServer = CreateTestLspServer("class C { }", out _); // Cancel all requests if the request queue is blocked for 1 minute. This will result in a failed test run. using var cts = new CancellationTokenSource(TimeSpan.FromMinutes(1)); var waitables = StartTestRun(testLspServer, requests, cts.Token); // Non-long running tasks should run and complete. If there's a test-failure for a "cancellation" // at this point it means our long running task blocked the queue and prevented completion. var responses = await Task.WhenAll(waitables.Skip(1)); Assert.Empty(responses.Where(r => r.StartTime == default)); Assert.All(responses, r => Assert.True(r.EndTime > r.StartTime)); // Our long-running waitable should still be running until cancelled. var longRunningWaitable = waitables[0]; Assert.False(longRunningWaitable.IsCompleted); } [Fact] public async Task FailingMutableTaskShutsDownQueue() { // NOTE: A failing task shuts down the queue not due to an exception escaping out of the handler // but because the solution state would be invalid. This doesn't test the queues exception // resiliancy. var requests = new[] { new TestRequest(FailingMutatingRequestHandler.MethodName), new TestRequest(NonMutatingRequestHandler.MethodName), new TestRequest(MutatingRequestHandler.MethodName), new TestRequest(NonMutatingRequestHandler.MethodName), }; using var testLspServer = CreateTestLspServer("class C { }", out _); var waitables = StartTestRun(testLspServer, requests); // first task should fail await Assert.ThrowsAsync<InvalidOperationException>(() => waitables[0]); // remaining tasks should be canceled await Assert.ThrowsAsync<TaskCanceledException>(() => Task.WhenAll(waitables.Skip(1))); Assert.All(waitables.Skip(1), w => Assert.True(w.IsCanceled)); } [Fact] public async Task NonMutatingRequestsOperateOnTheSameSolutionAfterMutation() { using var testLspServer = CreateTestLspServer("class C { {|caret:|} }", out var locations); var expectedSolution = testLspServer.GetCurrentSolution(); // solution should be the same because no mutations have happened var solution = await GetLSPSolution(testLspServer, NonMutatingRequestHandler.MethodName); Assert.Equal(expectedSolution, solution); // Open a document, to get a forked solution await ExecuteDidOpen(testLspServer, locations["caret"].First().Uri); // solution should be different because there has been a mutation solution = await GetLSPSolution(testLspServer, NonMutatingRequestHandler.MethodName); Assert.NotEqual(expectedSolution, solution); expectedSolution = solution; // solution should be the same because no mutations have happened solution = await GetLSPSolution(testLspServer, NonMutatingRequestHandler.MethodName); Assert.Equal(expectedSolution, solution); // Apply some random change to the workspace that the LSP server doesn't "see" testLspServer.TestWorkspace.SetCurrentSolution(s => s.WithProjectName(s.Projects.First().Id, "NewName"), WorkspaceChangeKind.ProjectChanged); expectedSolution = testLspServer.GetCurrentSolution(); // solution should be different because there has been a workspace change solution = await GetLSPSolution(testLspServer, NonMutatingRequestHandler.MethodName); Assert.NotEqual(expectedSolution, solution); expectedSolution = solution; // solution should be the same because no mutations have happened solution = await GetLSPSolution(testLspServer, NonMutatingRequestHandler.MethodName); Assert.Equal(expectedSolution, solution); } [Fact] public async Task HandlerThatSkipsBuildingLSPSolutionGetsWorkspaceSolution() { using var testLspServer = CreateTestLspServer("class C { {|caret:|} }", out var locations); var solution = await GetLSPSolution(testLspServer, NonLSPSolutionRequestHandler.MethodName); Assert.Null(solution); // Open a document, to create a change that LSP handlers wouldn normally see await ExecuteDidOpen(testLspServer, locations["caret"].First().Uri); // solution shouldn't have changed solution = await GetLSPSolution(testLspServer, NonLSPSolutionRequestHandler.MethodName); Assert.Null(solution); } private static async Task ExecuteDidOpen(TestLspServer testLspServer, Uri documentUri) { var didOpenParams = new LSP.DidOpenTextDocumentParams { TextDocument = new LSP.TextDocumentItem { Uri = documentUri, Text = "// hi there" } }; await testLspServer.ExecuteRequestAsync<LSP.DidOpenTextDocumentParams, object>(Methods.TextDocumentDidOpenName, didOpenParams, new LSP.ClientCapabilities(), null, CancellationToken.None); } private static async Task<Solution> GetLSPSolution(TestLspServer testLspServer, string methodName) { var request = new TestRequest(methodName); var response = await testLspServer.ExecuteRequestAsync<TestRequest, TestResponse>(request.MethodName, request, new LSP.ClientCapabilities(), null, CancellationToken.None); return response.Solution; } private static async Task<TestResponse[]> TestAsync(TestLspServer testLspServer, TestRequest[] requests) { var waitables = StartTestRun(testLspServer, requests); var responses = await Task.WhenAll(waitables); // Sanity checks to ensure test handlers aren't doing something wacky, making future checks invalid Assert.Empty(responses.Where(r => r.StartTime == default)); Assert.All(responses, r => Assert.True(r.EndTime > r.StartTime)); return responses; } private static List<Task<TestResponse>> StartTestRun(TestLspServer testLspServer, TestRequest[] requests, CancellationToken cancellationToken = default) { var clientCapabilities = new LSP.ClientCapabilities(); var waitables = new List<Task<TestResponse>>(); foreach (var request in requests) { waitables.Add(testLspServer.ExecuteRequestAsync<TestRequest, TestResponse>(request.MethodName, request, clientCapabilities, null, cancellationToken)); } return waitables; } } }
// 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. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.LanguageServer.Protocol; using Roslyn.Test.Utilities; using Xunit; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.RequestOrdering { public partial class RequestOrderingTests : AbstractLanguageServerProtocolTests { protected override TestComposition Composition => base.Composition .AddParts(typeof(MutatingRequestHandlerProvider)) .AddParts(typeof(NonMutatingRequestHandlerProvider)) .AddParts(typeof(FailingRequestHandlerProvider)) .AddParts(typeof(FailingMutatingRequestHandlerProvider)) .AddParts(typeof(NonLSPSolutionRequestHandlerProvider)) .AddParts(typeof(LongRunningNonMutatingRequestHandlerProvider)); [Fact] public async Task MutatingRequestsDontOverlap() { var requests = new[] { new TestRequest(MutatingRequestHandler.MethodName), new TestRequest(MutatingRequestHandler.MethodName), new TestRequest(MutatingRequestHandler.MethodName), }; using var testLspServer = CreateTestLspServer("class C { }", out _); var responses = await TestAsync(testLspServer, requests); // Every request should have started at or after the one before it Assert.True(responses[1].StartTime >= responses[0].EndTime); Assert.True(responses[2].StartTime >= responses[1].EndTime); } [Fact] public async Task NonMutatingRequestsOverlap() { var requests = new[] { new TestRequest(NonMutatingRequestHandler.MethodName), new TestRequest(NonMutatingRequestHandler.MethodName), new TestRequest(NonMutatingRequestHandler.MethodName), }; using var testLspServer = CreateTestLspServer("class C { }", out _); var responses = await TestAsync(testLspServer, requests); // Every request should have started immediately, without waiting Assert.True(responses[1].StartTime < responses[0].EndTime); Assert.True(responses[2].StartTime < responses[1].EndTime); } [Fact] public async Task NonMutatingWaitsForMutating() { var requests = new[] { new TestRequest(MutatingRequestHandler.MethodName), new TestRequest(NonMutatingRequestHandler.MethodName), new TestRequest(NonMutatingRequestHandler.MethodName), }; using var testLspServer = CreateTestLspServer("class C { }", out _); var responses = await TestAsync(testLspServer, requests); // The non mutating tasks should have waited for the first task to finish Assert.True(responses[1].StartTime >= responses[0].EndTime); Assert.True(responses[2].StartTime >= responses[0].EndTime); // The non mutating requests shouldn't have waited for each other Assert.True(responses[1].StartTime < responses[2].EndTime); Assert.True(responses[2].StartTime < responses[1].EndTime); } [Fact] public async Task MutatingDoesntWaitForNonMutating() { var requests = new[] { new TestRequest(NonMutatingRequestHandler.MethodName), new TestRequest(NonMutatingRequestHandler.MethodName), new TestRequest(MutatingRequestHandler.MethodName), }; using var testLspServer = CreateTestLspServer("class C { }", out _); var responses = await TestAsync(testLspServer, requests); // All tasks should start without waiting for any to finish Assert.True(responses[1].StartTime < responses[0].EndTime); Assert.True(responses[2].StartTime < responses[0].EndTime); Assert.True(responses[1].StartTime < responses[2].EndTime); Assert.True(responses[2].StartTime < responses[1].EndTime); } [Fact] public async Task ThrowingTaskDoesntBringDownQueue() { var requests = new[] { new TestRequest(FailingRequestHandler.MethodName), new TestRequest(NonMutatingRequestHandler.MethodName), new TestRequest(MutatingRequestHandler.MethodName), new TestRequest(NonMutatingRequestHandler.MethodName), }; using var testLspServer = CreateTestLspServer("class C { }", out _); var waitables = StartTestRun(testLspServer, requests); // first task should fail await Assert.ThrowsAsync<InvalidOperationException>(() => waitables[0]); // remaining tasks should have executed normally var responses = await Task.WhenAll(waitables.Skip(1)); Assert.Empty(responses.Where(r => r.StartTime == default)); Assert.All(responses, r => Assert.True(r.EndTime > r.StartTime)); } [Fact] public async Task LongRunningSynchronousNonMutatingTaskDoesNotBlockQueue() { var requests = new[] { new TestRequest(LongRunningNonMutatingRequestHandler.MethodName), new TestRequest(MutatingRequestHandler.MethodName), new TestRequest(NonMutatingRequestHandler.MethodName), }; using var testLspServer = CreateTestLspServer("class C { }", out _); // Cancel all requests if the request queue is blocked for 1 minute. This will result in a failed test run. using var cts = new CancellationTokenSource(TimeSpan.FromMinutes(1)); var waitables = StartTestRun(testLspServer, requests, cts.Token); // Non-long running tasks should run and complete. If there's a test-failure for a "cancellation" // at this point it means our long running task blocked the queue and prevented completion. var responses = await Task.WhenAll(waitables.Skip(1)); Assert.Empty(responses.Where(r => r.StartTime == default)); Assert.All(responses, r => Assert.True(r.EndTime > r.StartTime)); // Our long-running waitable should still be running until cancelled. var longRunningWaitable = waitables[0]; Assert.False(longRunningWaitable.IsCompleted); } [Fact] public async Task FailingMutableTaskShutsDownQueue() { // NOTE: A failing task shuts down the queue not due to an exception escaping out of the handler // but because the solution state would be invalid. This doesn't test the queues exception // resiliancy. var requests = new[] { new TestRequest(FailingMutatingRequestHandler.MethodName), new TestRequest(NonMutatingRequestHandler.MethodName), new TestRequest(MutatingRequestHandler.MethodName), new TestRequest(NonMutatingRequestHandler.MethodName), }; using var testLspServer = CreateTestLspServer("class C { }", out _); var waitables = StartTestRun(testLspServer, requests); // first task should fail await Assert.ThrowsAsync<InvalidOperationException>(() => waitables[0]); // remaining tasks should be canceled await Assert.ThrowsAsync<TaskCanceledException>(() => Task.WhenAll(waitables.Skip(1))); Assert.All(waitables.Skip(1), w => Assert.True(w.IsCanceled)); } [Fact] public async Task NonMutatingRequestsOperateOnTheSameSolutionAfterMutation() { using var testLspServer = CreateTestLspServer("class C { {|caret:|} }", out var locations); var expectedSolution = testLspServer.GetCurrentSolution(); // solution should be the same because no mutations have happened var solution = await GetLSPSolution(testLspServer, NonMutatingRequestHandler.MethodName); Assert.Equal(expectedSolution, solution); // Open a document, to get a forked solution await ExecuteDidOpen(testLspServer, locations["caret"].First().Uri); // solution should be different because there has been a mutation solution = await GetLSPSolution(testLspServer, NonMutatingRequestHandler.MethodName); Assert.NotEqual(expectedSolution, solution); expectedSolution = solution; // solution should be the same because no mutations have happened solution = await GetLSPSolution(testLspServer, NonMutatingRequestHandler.MethodName); Assert.Equal(expectedSolution, solution); // Apply some random change to the workspace that the LSP server doesn't "see" testLspServer.TestWorkspace.SetCurrentSolution(s => s.WithProjectName(s.Projects.First().Id, "NewName"), WorkspaceChangeKind.ProjectChanged); expectedSolution = testLspServer.GetCurrentSolution(); // solution should be different because there has been a workspace change solution = await GetLSPSolution(testLspServer, NonMutatingRequestHandler.MethodName); Assert.NotEqual(expectedSolution, solution); expectedSolution = solution; // solution should be the same because no mutations have happened solution = await GetLSPSolution(testLspServer, NonMutatingRequestHandler.MethodName); Assert.Equal(expectedSolution, solution); } [Fact] public async Task HandlerThatSkipsBuildingLSPSolutionGetsWorkspaceSolution() { using var testLspServer = CreateTestLspServer("class C { {|caret:|} }", out var locations); var solution = await GetLSPSolution(testLspServer, NonLSPSolutionRequestHandler.MethodName); Assert.Null(solution); // Open a document, to create a change that LSP handlers wouldn normally see await ExecuteDidOpen(testLspServer, locations["caret"].First().Uri); // solution shouldn't have changed solution = await GetLSPSolution(testLspServer, NonLSPSolutionRequestHandler.MethodName); Assert.Null(solution); } private static async Task ExecuteDidOpen(TestLspServer testLspServer, Uri documentUri) { var didOpenParams = new LSP.DidOpenTextDocumentParams { TextDocument = new LSP.TextDocumentItem { Uri = documentUri, Text = "// hi there" } }; await testLspServer.ExecuteRequestAsync<LSP.DidOpenTextDocumentParams, object>(Methods.TextDocumentDidOpenName, didOpenParams, new LSP.ClientCapabilities(), null, CancellationToken.None); } private static async Task<Solution> GetLSPSolution(TestLspServer testLspServer, string methodName) { var request = new TestRequest(methodName); var response = await testLspServer.ExecuteRequestAsync<TestRequest, TestResponse>(request.MethodName, request, new LSP.ClientCapabilities(), null, CancellationToken.None); return response.Solution; } private static async Task<TestResponse[]> TestAsync(TestLspServer testLspServer, TestRequest[] requests) { var waitables = StartTestRun(testLspServer, requests); var responses = await Task.WhenAll(waitables); // Sanity checks to ensure test handlers aren't doing something wacky, making future checks invalid Assert.Empty(responses.Where(r => r.StartTime == default)); Assert.All(responses, r => Assert.True(r.EndTime > r.StartTime)); return responses; } private static List<Task<TestResponse>> StartTestRun(TestLspServer testLspServer, TestRequest[] requests, CancellationToken cancellationToken = default) { var clientCapabilities = new LSP.ClientCapabilities(); var waitables = new List<Task<TestResponse>>(); foreach (var request in requests) { waitables.Add(testLspServer.ExecuteRequestAsync<TestRequest, TestResponse>(request.MethodName, request, clientCapabilities, null, cancellationToken)); } return waitables; } } }
-1
dotnet/roslyn
56,015
Remove obsolete APIs
Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
tmat
"2021-08-30T20:53:26Z"
"2021-09-02T16:56:01Z"
bdf1025480ad91f8db054959553257746f58f527
e782ce78f087060a3bc51737d3f07a6d102fb7b1
Remove obsolete APIs. Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
./src/Workspaces/Core/Portable/SymbolKey/SymbolKey.ModuleSymbolKey.cs
// 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 { internal partial struct SymbolKey { private static class ModuleSymbolKey { public static void Create(IModuleSymbol symbol, SymbolKeyWriter visitor) => visitor.WriteSymbolKey(symbol.ContainingSymbol); public static SymbolKeyResolution Resolve(SymbolKeyReader reader, out string? failureReason) { var containingSymbolResolution = reader.ReadSymbolKey(out var containingSymbolFailureReason); if (containingSymbolFailureReason != null) { failureReason = $"({nameof(ModuleSymbolKey)} {nameof(containingSymbolResolution)} failed -> {containingSymbolFailureReason})"; return default; } using var result = PooledArrayBuilder<IModuleSymbol>.GetInstance(); foreach (var assembly in containingSymbolResolution.OfType<IAssemblySymbol>()) { // Don't check ModuleIds for equality because in practice, no-one uses them, // and there is no way to set netmodule name programmatically using Roslyn result.AddValuesIfNotNull(assembly.Modules); } return CreateResolution(result, $"({nameof(ModuleSymbolKey)} failed)", out failureReason); } } } }
// 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 { internal partial struct SymbolKey { private static class ModuleSymbolKey { public static void Create(IModuleSymbol symbol, SymbolKeyWriter visitor) => visitor.WriteSymbolKey(symbol.ContainingSymbol); public static SymbolKeyResolution Resolve(SymbolKeyReader reader, out string? failureReason) { var containingSymbolResolution = reader.ReadSymbolKey(out var containingSymbolFailureReason); if (containingSymbolFailureReason != null) { failureReason = $"({nameof(ModuleSymbolKey)} {nameof(containingSymbolResolution)} failed -> {containingSymbolFailureReason})"; return default; } using var result = PooledArrayBuilder<IModuleSymbol>.GetInstance(); foreach (var assembly in containingSymbolResolution.OfType<IAssemblySymbol>()) { // Don't check ModuleIds for equality because in practice, no-one uses them, // and there is no way to set netmodule name programmatically using Roslyn result.AddValuesIfNotNull(assembly.Modules); } return CreateResolution(result, $"({nameof(ModuleSymbolKey)} failed)", out failureReason); } } } }
-1
dotnet/roslyn
56,015
Remove obsolete APIs
Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
tmat
"2021-08-30T20:53:26Z"
"2021-09-02T16:56:01Z"
bdf1025480ad91f8db054959553257746f58f527
e782ce78f087060a3bc51737d3f07a6d102fb7b1
Remove obsolete APIs. Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
./src/Compilers/Core/Portable/Syntax/SyntaxListBuilder`1.cs
// 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.Syntax { internal struct SyntaxListBuilder<TNode> where TNode : SyntaxNode { private readonly SyntaxListBuilder? _builder; public SyntaxListBuilder(int size) : this(new SyntaxListBuilder(size)) { } public static SyntaxListBuilder<TNode> Create() { return new SyntaxListBuilder<TNode>(8); } internal SyntaxListBuilder(SyntaxListBuilder? builder) { _builder = builder; } public bool IsNull { get { return _builder == null; } } public int Count { get { return _builder!.Count; } } public void Clear() { _builder!.Clear(); } public SyntaxListBuilder<TNode> Add(TNode node) { _builder!.Add(node); return this; } public void AddRange(TNode[] items, int offset, int length) { _builder!.AddRange(items, offset, length); } public void AddRange(SyntaxList<TNode> nodes) { _builder!.AddRange(nodes); } public void AddRange(SyntaxList<TNode> nodes, int offset, int length) { _builder!.AddRange(nodes, offset, length); } public bool Any(int kind) { return _builder!.Any(kind); } public SyntaxList<TNode> ToList() { return _builder.ToList(); } public static implicit operator SyntaxListBuilder?(SyntaxListBuilder<TNode> builder) { return builder._builder; } public static implicit operator SyntaxList<TNode>(SyntaxListBuilder<TNode> builder) { if (builder._builder != null) { return builder.ToList(); } return default; } } }
// 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.Syntax { internal struct SyntaxListBuilder<TNode> where TNode : SyntaxNode { private readonly SyntaxListBuilder? _builder; public SyntaxListBuilder(int size) : this(new SyntaxListBuilder(size)) { } public static SyntaxListBuilder<TNode> Create() { return new SyntaxListBuilder<TNode>(8); } internal SyntaxListBuilder(SyntaxListBuilder? builder) { _builder = builder; } public bool IsNull { get { return _builder == null; } } public int Count { get { return _builder!.Count; } } public void Clear() { _builder!.Clear(); } public SyntaxListBuilder<TNode> Add(TNode node) { _builder!.Add(node); return this; } public void AddRange(TNode[] items, int offset, int length) { _builder!.AddRange(items, offset, length); } public void AddRange(SyntaxList<TNode> nodes) { _builder!.AddRange(nodes); } public void AddRange(SyntaxList<TNode> nodes, int offset, int length) { _builder!.AddRange(nodes, offset, length); } public bool Any(int kind) { return _builder!.Any(kind); } public SyntaxList<TNode> ToList() { return _builder.ToList(); } public static implicit operator SyntaxListBuilder?(SyntaxListBuilder<TNode> builder) { return builder._builder; } public static implicit operator SyntaxList<TNode>(SyntaxListBuilder<TNode> builder) { if (builder._builder != null) { return builder.ToList(); } return default; } } }
-1
dotnet/roslyn
56,015
Remove obsolete APIs
Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
tmat
"2021-08-30T20:53:26Z"
"2021-09-02T16:56:01Z"
bdf1025480ad91f8db054959553257746f58f527
e782ce78f087060a3bc51737d3f07a6d102fb7b1
Remove obsolete APIs. Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
./src/Compilers/Core/Portable/DocumentationComments/DocumentationProvider.NullDocumentationProvider.cs
// 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. using System.Globalization; using System.Runtime.CompilerServices; using System.Threading; namespace Microsoft.CodeAnalysis { public partial class DocumentationProvider { /// <summary> /// A trivial DocumentationProvider which never returns documentation. /// </summary> private class NullDocumentationProvider : DocumentationProvider { protected internal override string GetDocumentationForSymbol(string documentationMemberID, CultureInfo preferredCulture, CancellationToken cancellationToken = default(CancellationToken)) { return ""; } public override bool Equals(object? obj) { // Only one instance is expected to exist, so reference equality is fine. return (object)this == obj; } public override int GetHashCode() { return RuntimeHelpers.GetHashCode(this); } } } }
// 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. using System.Globalization; using System.Runtime.CompilerServices; using System.Threading; namespace Microsoft.CodeAnalysis { public partial class DocumentationProvider { /// <summary> /// A trivial DocumentationProvider which never returns documentation. /// </summary> private class NullDocumentationProvider : DocumentationProvider { protected internal override string GetDocumentationForSymbol(string documentationMemberID, CultureInfo preferredCulture, CancellationToken cancellationToken = default(CancellationToken)) { return ""; } public override bool Equals(object? obj) { // Only one instance is expected to exist, so reference equality is fine. return (object)this == obj; } public override int GetHashCode() { return RuntimeHelpers.GetHashCode(this); } } } }
-1
dotnet/roslyn
56,015
Remove obsolete APIs
Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
tmat
"2021-08-30T20:53:26Z"
"2021-09-02T16:56:01Z"
bdf1025480ad91f8db054959553257746f58f527
e782ce78f087060a3bc51737d3f07a6d102fb7b1
Remove obsolete APIs. Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
./src/VisualStudio/IntegrationTest/IntegrationTests/VisualBasic/BasicFindReferences.cs
// 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. using System; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities.Common; using Microsoft.VisualStudio.IntegrationTest.Utilities.Input; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; using ProjectUtils = Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils; namespace Roslyn.VisualStudio.IntegrationTests.VisualBasic { [Collection(nameof(SharedIntegrationHostFixture))] public class BasicFindReferences : AbstractEditorTest { protected override string LanguageName => LanguageNames.VisualBasic; public BasicFindReferences(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, nameof(BasicFindReferences)) { } [WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)] public void FindReferencesToLocals() { SetUpEditor(@" Class Program Sub Main() Dim local = 1 Console.WriteLine(loca$$l) End Sub End Class "); VisualStudio.SendKeys.Send(Shift(VirtualKey.F12)); const string localReferencesCaption = "'local' references"; var results = VisualStudio.FindReferencesWindow.GetContents(localReferencesCaption); var activeWindowCaption = VisualStudio.Shell.GetActiveWindowCaption(); Assert.Equal(expected: localReferencesCaption, actual: activeWindowCaption); Assert.Collection( results, new Action<Reference>[] { reference => { Assert.Equal(expected: "Dim local = 1", actual: reference.Code); Assert.Equal(expected: 3, actual: reference.Line); Assert.Equal(expected: 10, actual: reference.Column); }, reference => { Assert.Equal(expected: "Console.WriteLine(local)", actual: reference.Code); Assert.Equal(expected: 4, actual: reference.Line); Assert.Equal(expected: 24, actual: reference.Column); } }); } [WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)] public void FindReferencesToSharedField() { SetUpEditor(@" Class Program Public Shared Alpha As Int32 End Class$$ "); var project = new ProjectUtils.Project(ProjectName); VisualStudio.SolutionExplorer.AddFile(project, "File2.vb"); VisualStudio.SolutionExplorer.OpenFile(project, "File2.vb"); SetUpEditor(@" Class SomeOtherClass Sub M() Console.WriteLine(Program.$$Alpha) End Sub End Class "); VisualStudio.SendKeys.Send(Shift(VirtualKey.F12)); const string alphaReferencesCaption = "'Alpha' references"; var results = VisualStudio.FindReferencesWindow.GetContents(alphaReferencesCaption); var activeWindowCaption = VisualStudio.Shell.GetActiveWindowCaption(); Assert.Equal(expected: alphaReferencesCaption, actual: activeWindowCaption); Assert.Collection( results, new Action<Reference>[] { reference => { Assert.Equal(expected: "Public Shared Alpha As Int32", actual: reference.Code); Assert.Equal(expected: 2, actual: reference.Line); Assert.Equal(expected: 18, actual: reference.Column); }, reference => { Assert.Equal(expected: "Console.WriteLine(Program.Alpha)", actual: reference.Code); Assert.Equal(expected: 3, actual: reference.Line); Assert.Equal(expected: 34, actual: reference.Column); } }); } } }
// 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. using System; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities.Common; using Microsoft.VisualStudio.IntegrationTest.Utilities.Input; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; using ProjectUtils = Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils; namespace Roslyn.VisualStudio.IntegrationTests.VisualBasic { [Collection(nameof(SharedIntegrationHostFixture))] public class BasicFindReferences : AbstractEditorTest { protected override string LanguageName => LanguageNames.VisualBasic; public BasicFindReferences(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, nameof(BasicFindReferences)) { } [WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)] public void FindReferencesToLocals() { SetUpEditor(@" Class Program Sub Main() Dim local = 1 Console.WriteLine(loca$$l) End Sub End Class "); VisualStudio.SendKeys.Send(Shift(VirtualKey.F12)); const string localReferencesCaption = "'local' references"; var results = VisualStudio.FindReferencesWindow.GetContents(localReferencesCaption); var activeWindowCaption = VisualStudio.Shell.GetActiveWindowCaption(); Assert.Equal(expected: localReferencesCaption, actual: activeWindowCaption); Assert.Collection( results, new Action<Reference>[] { reference => { Assert.Equal(expected: "Dim local = 1", actual: reference.Code); Assert.Equal(expected: 3, actual: reference.Line); Assert.Equal(expected: 10, actual: reference.Column); }, reference => { Assert.Equal(expected: "Console.WriteLine(local)", actual: reference.Code); Assert.Equal(expected: 4, actual: reference.Line); Assert.Equal(expected: 24, actual: reference.Column); } }); } [WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)] public void FindReferencesToSharedField() { SetUpEditor(@" Class Program Public Shared Alpha As Int32 End Class$$ "); var project = new ProjectUtils.Project(ProjectName); VisualStudio.SolutionExplorer.AddFile(project, "File2.vb"); VisualStudio.SolutionExplorer.OpenFile(project, "File2.vb"); SetUpEditor(@" Class SomeOtherClass Sub M() Console.WriteLine(Program.$$Alpha) End Sub End Class "); VisualStudio.SendKeys.Send(Shift(VirtualKey.F12)); const string alphaReferencesCaption = "'Alpha' references"; var results = VisualStudio.FindReferencesWindow.GetContents(alphaReferencesCaption); var activeWindowCaption = VisualStudio.Shell.GetActiveWindowCaption(); Assert.Equal(expected: alphaReferencesCaption, actual: activeWindowCaption); Assert.Collection( results, new Action<Reference>[] { reference => { Assert.Equal(expected: "Public Shared Alpha As Int32", actual: reference.Code); Assert.Equal(expected: 2, actual: reference.Line); Assert.Equal(expected: 18, actual: reference.Column); }, reference => { Assert.Equal(expected: "Console.WriteLine(Program.Alpha)", actual: reference.Code); Assert.Equal(expected: 3, actual: reference.Line); Assert.Equal(expected: 34, actual: reference.Column); } }); } } }
-1
dotnet/roslyn
56,015
Remove obsolete APIs
Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
tmat
"2021-08-30T20:53:26Z"
"2021-09-02T16:56:01Z"
bdf1025480ad91f8db054959553257746f58f527
e782ce78f087060a3bc51737d3f07a6d102fb7b1
Remove obsolete APIs. Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
./src/Compilers/CSharp/Portable/Symbols/Metadata/PE/PENamespaceSymbol.cs
// 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. #nullable disable using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Reflection.Metadata; using System.Threading; namespace Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE { /// <summary> /// The base class to represent a namespace imported from a PE/module. Namespaces that differ /// only by casing in name are not merged. /// </summary> internal abstract class PENamespaceSymbol : NamespaceSymbol { /// <summary> /// A map of namespaces immediately contained within this namespace /// mapped by their name (case-sensitively). /// </summary> protected Dictionary<string, PENestedNamespaceSymbol> lazyNamespaces; /// <summary> /// A map of types immediately contained within this namespace /// grouped by their name (case-sensitively). /// </summary> protected Dictionary<string, ImmutableArray<PENamedTypeSymbol>> lazyTypes; /// <summary> /// A map of NoPia local types immediately contained in this assembly. /// Maps type name (non-qualified) to the row id. Note, for VB we should use /// full name. /// </summary> private Dictionary<string, TypeDefinitionHandle> _lazyNoPiaLocalTypes; /// <summary> /// All type members in a flat array /// </summary> private ImmutableArray<PENamedTypeSymbol> _lazyFlattenedTypes; internal sealed override NamespaceExtent Extent { get { return new NamespaceExtent(this.ContainingPEModule); } } [PerformanceSensitive( "https://github.com/dotnet/roslyn/issues/23582", Constraint = "Provide " + nameof(ArrayBuilder<Symbol>) + " capacity to reduce number of allocations.", AllowGenericEnumeration = false)] public sealed override ImmutableArray<Symbol> GetMembers() { EnsureAllMembersLoaded(); var memberTypes = GetMemberTypesPrivate(); var builder = ArrayBuilder<Symbol>.GetInstance(memberTypes.Length + lazyNamespaces.Count); builder.AddRange(memberTypes); foreach (var pair in lazyNamespaces) { builder.Add(pair.Value); } return builder.ToImmutableAndFree(); } private ImmutableArray<NamedTypeSymbol> GetMemberTypesPrivate() { //assume that EnsureAllMembersLoaded() has initialize lazyTypes if (_lazyFlattenedTypes.IsDefault) { var flattened = lazyTypes.Flatten(); ImmutableInterlocked.InterlockedExchange(ref _lazyFlattenedTypes, flattened); } return StaticCast<NamedTypeSymbol>.From(_lazyFlattenedTypes); } public sealed override ImmutableArray<Symbol> GetMembers(string name) { EnsureAllMembersLoaded(); PENestedNamespaceSymbol ns = null; ImmutableArray<PENamedTypeSymbol> t; if (lazyNamespaces.TryGetValue(name, out ns)) { if (lazyTypes.TryGetValue(name, out t)) { // TODO - Eliminate the copy by storing all members and type members instead of non-type and type members? return StaticCast<Symbol>.From(t).Add(ns); } else { return ImmutableArray.Create<Symbol>(ns); } } else if (lazyTypes.TryGetValue(name, out t)) { return StaticCast<Symbol>.From(t); } return ImmutableArray<Symbol>.Empty; } public sealed override ImmutableArray<NamedTypeSymbol> GetTypeMembers() { EnsureAllMembersLoaded(); return GetMemberTypesPrivate(); } public sealed override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name) { EnsureAllMembersLoaded(); ImmutableArray<PENamedTypeSymbol> t; return lazyTypes.TryGetValue(name, out t) ? StaticCast<NamedTypeSymbol>.From(t) : ImmutableArray<NamedTypeSymbol>.Empty; } public sealed override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name, int arity) { return GetTypeMembers(name).WhereAsArray((type, arity) => type.Arity == arity, arity); } public sealed override ImmutableArray<Location> Locations { get { return ContainingPEModule.MetadataLocation.Cast<MetadataLocation, Location>(); } } public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get { return ImmutableArray<SyntaxReference>.Empty; } } /// <summary> /// Returns PEModuleSymbol containing the namespace. /// </summary> /// <returns>PEModuleSymbol containing the namespace.</returns> internal abstract PEModuleSymbol ContainingPEModule { get; } protected abstract void EnsureAllMembersLoaded(); /// <summary> /// Initializes namespaces and types maps with information about /// namespaces and types immediately contained within this namespace. /// </summary> /// <param name="typesByNS"> /// The sequence of groups of TypeDef row ids for types contained within the namespace, /// recursively including those from nested namespaces. The row ids must be grouped by the /// fully-qualified namespace name case-sensitively. There could be multiple groups /// for each fully-qualified namespace name. The groups must be sorted by /// their key in case-sensitive manner. Empty string must be used as namespace name for types /// immediately contained within Global namespace. Therefore, all types in this namespace, if any, /// must be in several first IGroupings. /// </param> protected void LoadAllMembers(IEnumerable<IGrouping<string, TypeDefinitionHandle>> typesByNS) { Debug.Assert(typesByNS != null); // A sequence of groups of TypeDef row ids for types immediately contained within this namespace. IEnumerable<IGrouping<string, TypeDefinitionHandle>> nestedTypes = null; // A sequence with information about namespaces immediately contained within this namespace. // For each pair: // Key - contains simple name of a child namespace. // Value - contains a sequence similar to the one passed to this function, but // calculated for the child namespace. IEnumerable<KeyValuePair<string, IEnumerable<IGrouping<string, TypeDefinitionHandle>>>> nestedNamespaces = null; bool isGlobalNamespace = this.IsGlobalNamespace; MetadataHelpers.GetInfoForImmediateNamespaceMembers( isGlobalNamespace, isGlobalNamespace ? 0 : GetQualifiedNameLength(), typesByNS, StringComparer.Ordinal, out nestedTypes, out nestedNamespaces); LazyInitializeNamespaces(nestedNamespaces); LazyInitializeTypes(nestedTypes); } private int GetQualifiedNameLength() { int length = this.Name.Length; var parent = ContainingNamespace; while (parent?.IsGlobalNamespace == false) { // add name of the parent + "." length += parent.Name.Length + 1; parent = parent.ContainingNamespace; } return length; } /// <summary> /// Create symbols for nested namespaces and initialize namespaces map. /// </summary> private void LazyInitializeNamespaces( IEnumerable<KeyValuePair<string, IEnumerable<IGrouping<string, TypeDefinitionHandle>>>> childNamespaces) { if (this.lazyNamespaces == null) { var namespaces = new Dictionary<string, PENestedNamespaceSymbol>(StringOrdinalComparer.Instance); foreach (var child in childNamespaces) { var c = new PENestedNamespaceSymbol(child.Key, this, child.Value); namespaces.Add(c.Name, c); } Interlocked.CompareExchange(ref this.lazyNamespaces, namespaces, null); } } /// <summary> /// Create symbols for nested types and initialize types map. /// </summary> private void LazyInitializeTypes(IEnumerable<IGrouping<string, TypeDefinitionHandle>> typeGroups) { if (this.lazyTypes == null) { var moduleSymbol = ContainingPEModule; var children = ArrayBuilder<PENamedTypeSymbol>.GetInstance(); var skipCheckForPiaType = !moduleSymbol.Module.ContainsNoPiaLocalTypes(); Dictionary<string, TypeDefinitionHandle> noPiaLocalTypes = null; foreach (var g in typeGroups) { foreach (var t in g) { if (skipCheckForPiaType || !moduleSymbol.Module.IsNoPiaLocalType(t)) { children.Add(PENamedTypeSymbol.Create(moduleSymbol, this, t, g.Key)); } else { try { string typeDefName = moduleSymbol.Module.GetTypeDefNameOrThrow(t); if (noPiaLocalTypes == null) { noPiaLocalTypes = new Dictionary<string, TypeDefinitionHandle>(StringOrdinalComparer.Instance); } noPiaLocalTypes[typeDefName] = t; } catch (BadImageFormatException) { } } } } var typesDict = children.ToDictionary(c => c.Name, StringOrdinalComparer.Instance); children.Free(); if (noPiaLocalTypes != null) { Interlocked.CompareExchange(ref _lazyNoPiaLocalTypes, noPiaLocalTypes, null); } var original = Interlocked.CompareExchange(ref this.lazyTypes, typesDict, null); // Build cache of TypeDef Tokens // Potentially this can be done in the background. if (original == null) { moduleSymbol.OnNewTypeDeclarationsLoaded(typesDict); } } } internal NamedTypeSymbol LookupMetadataType(ref MetadataTypeName emittedTypeName, out bool isNoPiaLocalType) { NamedTypeSymbol result = LookupMetadataType(ref emittedTypeName); isNoPiaLocalType = false; if (result is MissingMetadataTypeSymbol) { EnsureAllMembersLoaded(); TypeDefinitionHandle typeDef; // See if this is a NoPia local type, which we should unify. // Note, VB should use FullName. if (_lazyNoPiaLocalTypes != null && _lazyNoPiaLocalTypes.TryGetValue(emittedTypeName.TypeName, out typeDef)) { result = (NamedTypeSymbol)new MetadataDecoder(ContainingPEModule).GetTypeOfToken(typeDef, out isNoPiaLocalType); Debug.Assert(isNoPiaLocalType); } } return result; } } }
// 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. #nullable disable using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Reflection.Metadata; using System.Threading; namespace Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE { /// <summary> /// The base class to represent a namespace imported from a PE/module. Namespaces that differ /// only by casing in name are not merged. /// </summary> internal abstract class PENamespaceSymbol : NamespaceSymbol { /// <summary> /// A map of namespaces immediately contained within this namespace /// mapped by their name (case-sensitively). /// </summary> protected Dictionary<string, PENestedNamespaceSymbol> lazyNamespaces; /// <summary> /// A map of types immediately contained within this namespace /// grouped by their name (case-sensitively). /// </summary> protected Dictionary<string, ImmutableArray<PENamedTypeSymbol>> lazyTypes; /// <summary> /// A map of NoPia local types immediately contained in this assembly. /// Maps type name (non-qualified) to the row id. Note, for VB we should use /// full name. /// </summary> private Dictionary<string, TypeDefinitionHandle> _lazyNoPiaLocalTypes; /// <summary> /// All type members in a flat array /// </summary> private ImmutableArray<PENamedTypeSymbol> _lazyFlattenedTypes; internal sealed override NamespaceExtent Extent { get { return new NamespaceExtent(this.ContainingPEModule); } } [PerformanceSensitive( "https://github.com/dotnet/roslyn/issues/23582", Constraint = "Provide " + nameof(ArrayBuilder<Symbol>) + " capacity to reduce number of allocations.", AllowGenericEnumeration = false)] public sealed override ImmutableArray<Symbol> GetMembers() { EnsureAllMembersLoaded(); var memberTypes = GetMemberTypesPrivate(); var builder = ArrayBuilder<Symbol>.GetInstance(memberTypes.Length + lazyNamespaces.Count); builder.AddRange(memberTypes); foreach (var pair in lazyNamespaces) { builder.Add(pair.Value); } return builder.ToImmutableAndFree(); } private ImmutableArray<NamedTypeSymbol> GetMemberTypesPrivate() { //assume that EnsureAllMembersLoaded() has initialize lazyTypes if (_lazyFlattenedTypes.IsDefault) { var flattened = lazyTypes.Flatten(); ImmutableInterlocked.InterlockedExchange(ref _lazyFlattenedTypes, flattened); } return StaticCast<NamedTypeSymbol>.From(_lazyFlattenedTypes); } public sealed override ImmutableArray<Symbol> GetMembers(string name) { EnsureAllMembersLoaded(); PENestedNamespaceSymbol ns = null; ImmutableArray<PENamedTypeSymbol> t; if (lazyNamespaces.TryGetValue(name, out ns)) { if (lazyTypes.TryGetValue(name, out t)) { // TODO - Eliminate the copy by storing all members and type members instead of non-type and type members? return StaticCast<Symbol>.From(t).Add(ns); } else { return ImmutableArray.Create<Symbol>(ns); } } else if (lazyTypes.TryGetValue(name, out t)) { return StaticCast<Symbol>.From(t); } return ImmutableArray<Symbol>.Empty; } public sealed override ImmutableArray<NamedTypeSymbol> GetTypeMembers() { EnsureAllMembersLoaded(); return GetMemberTypesPrivate(); } public sealed override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name) { EnsureAllMembersLoaded(); ImmutableArray<PENamedTypeSymbol> t; return lazyTypes.TryGetValue(name, out t) ? StaticCast<NamedTypeSymbol>.From(t) : ImmutableArray<NamedTypeSymbol>.Empty; } public sealed override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name, int arity) { return GetTypeMembers(name).WhereAsArray((type, arity) => type.Arity == arity, arity); } public sealed override ImmutableArray<Location> Locations { get { return ContainingPEModule.MetadataLocation.Cast<MetadataLocation, Location>(); } } public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get { return ImmutableArray<SyntaxReference>.Empty; } } /// <summary> /// Returns PEModuleSymbol containing the namespace. /// </summary> /// <returns>PEModuleSymbol containing the namespace.</returns> internal abstract PEModuleSymbol ContainingPEModule { get; } protected abstract void EnsureAllMembersLoaded(); /// <summary> /// Initializes namespaces and types maps with information about /// namespaces and types immediately contained within this namespace. /// </summary> /// <param name="typesByNS"> /// The sequence of groups of TypeDef row ids for types contained within the namespace, /// recursively including those from nested namespaces. The row ids must be grouped by the /// fully-qualified namespace name case-sensitively. There could be multiple groups /// for each fully-qualified namespace name. The groups must be sorted by /// their key in case-sensitive manner. Empty string must be used as namespace name for types /// immediately contained within Global namespace. Therefore, all types in this namespace, if any, /// must be in several first IGroupings. /// </param> protected void LoadAllMembers(IEnumerable<IGrouping<string, TypeDefinitionHandle>> typesByNS) { Debug.Assert(typesByNS != null); // A sequence of groups of TypeDef row ids for types immediately contained within this namespace. IEnumerable<IGrouping<string, TypeDefinitionHandle>> nestedTypes = null; // A sequence with information about namespaces immediately contained within this namespace. // For each pair: // Key - contains simple name of a child namespace. // Value - contains a sequence similar to the one passed to this function, but // calculated for the child namespace. IEnumerable<KeyValuePair<string, IEnumerable<IGrouping<string, TypeDefinitionHandle>>>> nestedNamespaces = null; bool isGlobalNamespace = this.IsGlobalNamespace; MetadataHelpers.GetInfoForImmediateNamespaceMembers( isGlobalNamespace, isGlobalNamespace ? 0 : GetQualifiedNameLength(), typesByNS, StringComparer.Ordinal, out nestedTypes, out nestedNamespaces); LazyInitializeNamespaces(nestedNamespaces); LazyInitializeTypes(nestedTypes); } private int GetQualifiedNameLength() { int length = this.Name.Length; var parent = ContainingNamespace; while (parent?.IsGlobalNamespace == false) { // add name of the parent + "." length += parent.Name.Length + 1; parent = parent.ContainingNamespace; } return length; } /// <summary> /// Create symbols for nested namespaces and initialize namespaces map. /// </summary> private void LazyInitializeNamespaces( IEnumerable<KeyValuePair<string, IEnumerable<IGrouping<string, TypeDefinitionHandle>>>> childNamespaces) { if (this.lazyNamespaces == null) { var namespaces = new Dictionary<string, PENestedNamespaceSymbol>(StringOrdinalComparer.Instance); foreach (var child in childNamespaces) { var c = new PENestedNamespaceSymbol(child.Key, this, child.Value); namespaces.Add(c.Name, c); } Interlocked.CompareExchange(ref this.lazyNamespaces, namespaces, null); } } /// <summary> /// Create symbols for nested types and initialize types map. /// </summary> private void LazyInitializeTypes(IEnumerable<IGrouping<string, TypeDefinitionHandle>> typeGroups) { if (this.lazyTypes == null) { var moduleSymbol = ContainingPEModule; var children = ArrayBuilder<PENamedTypeSymbol>.GetInstance(); var skipCheckForPiaType = !moduleSymbol.Module.ContainsNoPiaLocalTypes(); Dictionary<string, TypeDefinitionHandle> noPiaLocalTypes = null; foreach (var g in typeGroups) { foreach (var t in g) { if (skipCheckForPiaType || !moduleSymbol.Module.IsNoPiaLocalType(t)) { children.Add(PENamedTypeSymbol.Create(moduleSymbol, this, t, g.Key)); } else { try { string typeDefName = moduleSymbol.Module.GetTypeDefNameOrThrow(t); if (noPiaLocalTypes == null) { noPiaLocalTypes = new Dictionary<string, TypeDefinitionHandle>(StringOrdinalComparer.Instance); } noPiaLocalTypes[typeDefName] = t; } catch (BadImageFormatException) { } } } } var typesDict = children.ToDictionary(c => c.Name, StringOrdinalComparer.Instance); children.Free(); if (noPiaLocalTypes != null) { Interlocked.CompareExchange(ref _lazyNoPiaLocalTypes, noPiaLocalTypes, null); } var original = Interlocked.CompareExchange(ref this.lazyTypes, typesDict, null); // Build cache of TypeDef Tokens // Potentially this can be done in the background. if (original == null) { moduleSymbol.OnNewTypeDeclarationsLoaded(typesDict); } } } internal NamedTypeSymbol LookupMetadataType(ref MetadataTypeName emittedTypeName, out bool isNoPiaLocalType) { NamedTypeSymbol result = LookupMetadataType(ref emittedTypeName); isNoPiaLocalType = false; if (result is MissingMetadataTypeSymbol) { EnsureAllMembersLoaded(); TypeDefinitionHandle typeDef; // See if this is a NoPia local type, which we should unify. // Note, VB should use FullName. if (_lazyNoPiaLocalTypes != null && _lazyNoPiaLocalTypes.TryGetValue(emittedTypeName.TypeName, out typeDef)) { result = (NamedTypeSymbol)new MetadataDecoder(ContainingPEModule).GetTypeOfToken(typeDef, out isNoPiaLocalType); Debug.Assert(isNoPiaLocalType); } } return result; } } }
-1
dotnet/roslyn
56,015
Remove obsolete APIs
Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
tmat
"2021-08-30T20:53:26Z"
"2021-09-02T16:56:01Z"
bdf1025480ad91f8db054959553257746f58f527
e782ce78f087060a3bc51737d3f07a6d102fb7b1
Remove obsolete APIs. Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
./src/Features/Core/Portable/AddDebuggerDisplay/AbstractAddDebuggerDisplayCodeRefactoringProvider.cs
// 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. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; namespace Microsoft.CodeAnalysis.AddDebuggerDisplay { internal abstract class AbstractAddDebuggerDisplayCodeRefactoringProvider< TTypeDeclarationSyntax, TMethodDeclarationSyntax> : CodeRefactoringProvider where TTypeDeclarationSyntax : SyntaxNode where TMethodDeclarationSyntax : SyntaxNode { private const string DebuggerDisplayPrefix = "{"; private const string DebuggerDisplayMethodName = "GetDebuggerDisplay"; private const string DebuggerDisplaySuffix = "(),nq}"; protected abstract bool CanNameofAccessNonPublicMembersFromAttributeArgument { get; } protected abstract bool SupportsConstantInterpolatedStrings(Document document); public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var (document, _, cancellationToken) = context; var typeAndPriority = await GetRelevantTypeFromHeaderAsync(context).ConfigureAwait(false) ?? await GetRelevantTypeFromMethodAsync(context).ConfigureAwait(false); if (typeAndPriority == null) return; var (type, priority) = typeAndPriority.Value; var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var compilation = semanticModel.Compilation; var debuggerAttributeTypeSymbol = compilation.GetTypeByMetadataName("System.Diagnostics.DebuggerDisplayAttribute"); if (debuggerAttributeTypeSymbol is null) return; var typeSymbol = (INamedTypeSymbol)semanticModel.GetRequiredDeclaredSymbol(type, context.CancellationToken); if (typeSymbol.IsStatic || !IsClassOrStruct(typeSymbol)) return; if (HasDebuggerDisplayAttribute(typeSymbol, compilation)) return; context.RegisterRefactoring(new MyCodeAction( priority, c => ApplyAsync(document, type, debuggerAttributeTypeSymbol, c))); } private static async Task<(TTypeDeclarationSyntax type, CodeActionPriority priority)?> GetRelevantTypeFromHeaderAsync(CodeRefactoringContext context) { var type = await context.TryGetRelevantNodeAsync<TTypeDeclarationSyntax>().ConfigureAwait(false); if (type is null) return null; return (type, CodeActionPriority.Low); } private static async Task<(TTypeDeclarationSyntax type, CodeActionPriority priority)?> GetRelevantTypeFromMethodAsync(CodeRefactoringContext context) { var (document, _, cancellationToken) = context; var method = await context.TryGetRelevantNodeAsync<TMethodDeclarationSyntax>().ConfigureAwait(false); if (method == null) return null; var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var methodSymbol = (IMethodSymbol)semanticModel.GetRequiredDeclaredSymbol(method, cancellationToken); var isDebuggerDisplayMethod = IsDebuggerDisplayMethod(methodSymbol); if (!isDebuggerDisplayMethod && !IsToStringMethod(methodSymbol)) return null; // Show the feature if we're on a ToString or GetDebuggerDisplay method. For the former, // have this be low-pri so we don't override more important light-bulb options. var typeDecl = method.FirstAncestorOrSelf<TTypeDeclarationSyntax>(); if (typeDecl == null) return null; var priority = isDebuggerDisplayMethod ? CodeActionPriority.Medium : CodeActionPriority.Low; return (typeDecl, priority); } private static bool IsToStringMethod(IMethodSymbol methodSymbol) => methodSymbol is { Name: nameof(ToString), Arity: 0, Parameters: { IsEmpty: true } }; private static bool IsDebuggerDisplayMethod(IMethodSymbol methodSymbol) => methodSymbol is { Name: DebuggerDisplayMethodName, Arity: 0, Parameters: { IsEmpty: true } }; private static bool IsClassOrStruct(ITypeSymbol typeSymbol) => typeSymbol.TypeKind is TypeKind.Class or TypeKind.Struct; private static bool HasDebuggerDisplayAttribute(ITypeSymbol typeSymbol, Compilation compilation) => typeSymbol.GetAttributes() .Select(data => data.AttributeClass) .Contains(compilation.GetTypeByMetadataName("System.Diagnostics.DebuggerDisplayAttribute")); private async Task<Document> ApplyAsync(Document document, TTypeDeclarationSyntax type, INamedTypeSymbol debuggerAttributeTypeSymbol, CancellationToken cancellationToken) { var syntaxRoot = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var editor = new SyntaxEditor(syntaxRoot, document.Project.Solution.Workspace); var generator = editor.Generator; SyntaxNode attributeArgument; if (CanNameofAccessNonPublicMembersFromAttributeArgument) { if (SupportsConstantInterpolatedStrings(document)) { attributeArgument = generator.InterpolatedStringExpression( generator.CreateInterpolatedStringStartToken(isVerbatim: false), new SyntaxNode[] { generator.InterpolatedStringText(generator.InterpolatedStringTextToken("{{", "{{")), generator.Interpolation(generator.NameOfExpression(generator.IdentifierName(DebuggerDisplayMethodName))), generator.InterpolatedStringText(generator.InterpolatedStringTextToken("(),nq}}", "(),nq}}")), }, generator.CreateInterpolatedStringEndToken()); } else { attributeArgument = generator.AddExpression( generator.AddExpression( generator.LiteralExpression(DebuggerDisplayPrefix), generator.NameOfExpression(generator.IdentifierName(DebuggerDisplayMethodName))), generator.LiteralExpression(DebuggerDisplaySuffix)); } } else { attributeArgument = generator.LiteralExpression( DebuggerDisplayPrefix + DebuggerDisplayMethodName + DebuggerDisplaySuffix); } var newAttribute = generator .Attribute(generator.TypeExpression(debuggerAttributeTypeSymbol), new[] { attributeArgument }) .WithAdditionalAnnotations( Simplifier.Annotation, Simplifier.AddImportsAnnotation); editor.AddAttribute(type, newAttribute); var typeSymbol = (INamedTypeSymbol)semanticModel.GetRequiredDeclaredSymbol(type, cancellationToken); if (!typeSymbol.GetMembers().OfType<IMethodSymbol>().Any(IsDebuggerDisplayMethod)) { editor.AddMember(type, generator.MethodDeclaration( DebuggerDisplayMethodName, returnType: generator.TypeExpression(SpecialType.System_String), accessibility: Accessibility.Private, statements: new[] { generator.ReturnStatement(generator.InvocationExpression( generator.MemberAccessExpression( generator.ThisExpression(), generator.IdentifierName("ToString")))) })); } return document.WithSyntaxRoot(editor.GetChangedRoot()); } private sealed class MyCodeAction : CodeAction.DocumentChangeAction { internal override CodeActionPriority Priority { get; } public MyCodeAction(CodeActionPriority priority, Func<CancellationToken, Task<Document>> createChangedDocument) : base(FeaturesResources.Add_DebuggerDisplay_attribute, createChangedDocument, nameof(FeaturesResources.Add_DebuggerDisplay_attribute)) { Priority = priority; } } } }
// 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. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; namespace Microsoft.CodeAnalysis.AddDebuggerDisplay { internal abstract class AbstractAddDebuggerDisplayCodeRefactoringProvider< TTypeDeclarationSyntax, TMethodDeclarationSyntax> : CodeRefactoringProvider where TTypeDeclarationSyntax : SyntaxNode where TMethodDeclarationSyntax : SyntaxNode { private const string DebuggerDisplayPrefix = "{"; private const string DebuggerDisplayMethodName = "GetDebuggerDisplay"; private const string DebuggerDisplaySuffix = "(),nq}"; protected abstract bool CanNameofAccessNonPublicMembersFromAttributeArgument { get; } protected abstract bool SupportsConstantInterpolatedStrings(Document document); public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var (document, _, cancellationToken) = context; var typeAndPriority = await GetRelevantTypeFromHeaderAsync(context).ConfigureAwait(false) ?? await GetRelevantTypeFromMethodAsync(context).ConfigureAwait(false); if (typeAndPriority == null) return; var (type, priority) = typeAndPriority.Value; var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var compilation = semanticModel.Compilation; var debuggerAttributeTypeSymbol = compilation.GetTypeByMetadataName("System.Diagnostics.DebuggerDisplayAttribute"); if (debuggerAttributeTypeSymbol is null) return; var typeSymbol = (INamedTypeSymbol)semanticModel.GetRequiredDeclaredSymbol(type, context.CancellationToken); if (typeSymbol.IsStatic || !IsClassOrStruct(typeSymbol)) return; if (HasDebuggerDisplayAttribute(typeSymbol, compilation)) return; context.RegisterRefactoring(new MyCodeAction( priority, c => ApplyAsync(document, type, debuggerAttributeTypeSymbol, c))); } private static async Task<(TTypeDeclarationSyntax type, CodeActionPriority priority)?> GetRelevantTypeFromHeaderAsync(CodeRefactoringContext context) { var type = await context.TryGetRelevantNodeAsync<TTypeDeclarationSyntax>().ConfigureAwait(false); if (type is null) return null; return (type, CodeActionPriority.Low); } private static async Task<(TTypeDeclarationSyntax type, CodeActionPriority priority)?> GetRelevantTypeFromMethodAsync(CodeRefactoringContext context) { var (document, _, cancellationToken) = context; var method = await context.TryGetRelevantNodeAsync<TMethodDeclarationSyntax>().ConfigureAwait(false); if (method == null) return null; var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var methodSymbol = (IMethodSymbol)semanticModel.GetRequiredDeclaredSymbol(method, cancellationToken); var isDebuggerDisplayMethod = IsDebuggerDisplayMethod(methodSymbol); if (!isDebuggerDisplayMethod && !IsToStringMethod(methodSymbol)) return null; // Show the feature if we're on a ToString or GetDebuggerDisplay method. For the former, // have this be low-pri so we don't override more important light-bulb options. var typeDecl = method.FirstAncestorOrSelf<TTypeDeclarationSyntax>(); if (typeDecl == null) return null; var priority = isDebuggerDisplayMethod ? CodeActionPriority.Medium : CodeActionPriority.Low; return (typeDecl, priority); } private static bool IsToStringMethod(IMethodSymbol methodSymbol) => methodSymbol is { Name: nameof(ToString), Arity: 0, Parameters: { IsEmpty: true } }; private static bool IsDebuggerDisplayMethod(IMethodSymbol methodSymbol) => methodSymbol is { Name: DebuggerDisplayMethodName, Arity: 0, Parameters: { IsEmpty: true } }; private static bool IsClassOrStruct(ITypeSymbol typeSymbol) => typeSymbol.TypeKind is TypeKind.Class or TypeKind.Struct; private static bool HasDebuggerDisplayAttribute(ITypeSymbol typeSymbol, Compilation compilation) => typeSymbol.GetAttributes() .Select(data => data.AttributeClass) .Contains(compilation.GetTypeByMetadataName("System.Diagnostics.DebuggerDisplayAttribute")); private async Task<Document> ApplyAsync(Document document, TTypeDeclarationSyntax type, INamedTypeSymbol debuggerAttributeTypeSymbol, CancellationToken cancellationToken) { var syntaxRoot = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var editor = new SyntaxEditor(syntaxRoot, document.Project.Solution.Workspace); var generator = editor.Generator; SyntaxNode attributeArgument; if (CanNameofAccessNonPublicMembersFromAttributeArgument) { if (SupportsConstantInterpolatedStrings(document)) { attributeArgument = generator.InterpolatedStringExpression( generator.CreateInterpolatedStringStartToken(isVerbatim: false), new SyntaxNode[] { generator.InterpolatedStringText(generator.InterpolatedStringTextToken("{{", "{{")), generator.Interpolation(generator.NameOfExpression(generator.IdentifierName(DebuggerDisplayMethodName))), generator.InterpolatedStringText(generator.InterpolatedStringTextToken("(),nq}}", "(),nq}}")), }, generator.CreateInterpolatedStringEndToken()); } else { attributeArgument = generator.AddExpression( generator.AddExpression( generator.LiteralExpression(DebuggerDisplayPrefix), generator.NameOfExpression(generator.IdentifierName(DebuggerDisplayMethodName))), generator.LiteralExpression(DebuggerDisplaySuffix)); } } else { attributeArgument = generator.LiteralExpression( DebuggerDisplayPrefix + DebuggerDisplayMethodName + DebuggerDisplaySuffix); } var newAttribute = generator .Attribute(generator.TypeExpression(debuggerAttributeTypeSymbol), new[] { attributeArgument }) .WithAdditionalAnnotations( Simplifier.Annotation, Simplifier.AddImportsAnnotation); editor.AddAttribute(type, newAttribute); var typeSymbol = (INamedTypeSymbol)semanticModel.GetRequiredDeclaredSymbol(type, cancellationToken); if (!typeSymbol.GetMembers().OfType<IMethodSymbol>().Any(IsDebuggerDisplayMethod)) { editor.AddMember(type, generator.MethodDeclaration( DebuggerDisplayMethodName, returnType: generator.TypeExpression(SpecialType.System_String), accessibility: Accessibility.Private, statements: new[] { generator.ReturnStatement(generator.InvocationExpression( generator.MemberAccessExpression( generator.ThisExpression(), generator.IdentifierName("ToString")))) })); } return document.WithSyntaxRoot(editor.GetChangedRoot()); } private sealed class MyCodeAction : CodeAction.DocumentChangeAction { internal override CodeActionPriority Priority { get; } public MyCodeAction(CodeActionPriority priority, Func<CancellationToken, Task<Document>> createChangedDocument) : base(FeaturesResources.Add_DebuggerDisplay_attribute, createChangedDocument, nameof(FeaturesResources.Add_DebuggerDisplay_attribute)) { Priority = priority; } } } }
-1
dotnet/roslyn
56,015
Remove obsolete APIs
Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
tmat
"2021-08-30T20:53:26Z"
"2021-09-02T16:56:01Z"
bdf1025480ad91f8db054959553257746f58f527
e782ce78f087060a3bc51737d3f07a6d102fb7b1
Remove obsolete APIs. Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
./src/EditorFeatures/Core/Implementation/InlineRename/AbstractInlineRenameUndoManager.cs
// 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. #nullable disable using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Operations; namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename { /// <summary> /// This class contains the logic common to VS and ETA when implementing IInlineRenameUndoManager /// </summary> internal abstract class AbstractInlineRenameUndoManager<TBufferState> { protected class ActiveSpanState { public string ReplacementText; public int SelectionAnchorPoint; public int SelectionActivePoint; } protected readonly InlineRenameService InlineRenameService; protected readonly Dictionary<ITextBuffer, TBufferState> UndoManagers = new Dictionary<ITextBuffer, TBufferState>(); protected readonly Stack<ActiveSpanState> UndoStack = new Stack<ActiveSpanState>(); protected readonly Stack<ActiveSpanState> RedoStack = new Stack<ActiveSpanState>(); protected ActiveSpanState initialState; protected ActiveSpanState currentState; protected bool updatePending = false; public AbstractInlineRenameUndoManager(InlineRenameService inlineRenameService) => this.InlineRenameService = inlineRenameService; public void Disconnect() { this.UndoManagers.Clear(); this.UndoStack.Clear(); this.RedoStack.Clear(); this.initialState = null; this.currentState = null; } private void UpdateCurrentState(string replacementText, ITextSelection selection, SnapshotSpan activeSpan) { var snapshot = activeSpan.Snapshot; var selectionSpan = selection.GetSnapshotSpansOnBuffer(snapshot.TextBuffer).Single(); var start = selectionSpan.Start.TranslateTo(snapshot, PointTrackingMode.Positive).Position - activeSpan.Start.Position; var end = selectionSpan.End.TranslateTo(snapshot, PointTrackingMode.Positive).Position - activeSpan.Start.Position; this.currentState = new ActiveSpanState() { ReplacementText = replacementText, SelectionAnchorPoint = selection.IsReversed ? end : start, SelectionActivePoint = selection.IsReversed ? start : end }; } public void CreateInitialState(string replacementText, ITextSelection selection, SnapshotSpan startingSpan) { UpdateCurrentState(replacementText, selection, startingSpan); this.initialState = this.currentState; } public void OnTextChanged(ITextSelection selection, SnapshotSpan singleTrackingSpanTouched) { this.RedoStack.Clear(); if (!this.UndoStack.Any()) { this.UndoStack.Push(this.initialState); } // For now, we will only ever be one Undo away from the beginning of the rename session. We can // implement Undo merging in the future. var replacementText = singleTrackingSpanTouched.GetText(); UpdateCurrentState(replacementText, selection, singleTrackingSpanTouched); this.InlineRenameService.ActiveSession.ApplyReplacementText(replacementText, propagateEditImmediately: false); } public void UpdateSelection(ITextView textView, ITextBuffer subjectBuffer, ITrackingSpan activeRenameSpan) { var snapshot = subjectBuffer.CurrentSnapshot; var anchor = new VirtualSnapshotPoint(snapshot, this.currentState.SelectionAnchorPoint + activeRenameSpan.GetStartPoint(snapshot)); var active = new VirtualSnapshotPoint(snapshot, this.currentState.SelectionActivePoint + activeRenameSpan.GetStartPoint(snapshot)); textView.SetSelection(anchor, active); } public void Undo(ITextBuffer _) { if (this.UndoStack.Count > 0) { this.RedoStack.Push(this.currentState); this.currentState = this.UndoStack.Pop(); this.InlineRenameService.ActiveSession.ApplyReplacementText(this.currentState.ReplacementText, propagateEditImmediately: true); } else { this.InlineRenameService.ActiveSession.Cancel(); } } public void Redo(ITextBuffer _) { if (this.RedoStack.Count > 0) { this.UndoStack.Push(this.currentState); this.currentState = this.RedoStack.Pop(); this.InlineRenameService.ActiveSession.ApplyReplacementText(this.currentState.ReplacementText, propagateEditImmediately: true); } } protected abstract void UndoTemporaryEdits(ITextBuffer subjectBuffer, bool disconnect, bool undoConflictResolution); protected void ApplyReplacementText(ITextBuffer subjectBuffer, ITextUndoHistory undoHistory, object propagateSpansEditTag, IEnumerable<ITrackingSpan> spans, string replacementText) { // roll back to the initial state for the buffer after conflict resolution this.UndoTemporaryEdits(subjectBuffer, disconnect: false, undoConflictResolution: replacementText == string.Empty); using var transaction = undoHistory.CreateTransaction(GetUndoTransactionDescription(replacementText)); using var edit = subjectBuffer.CreateEdit(EditOptions.None, null, propagateSpansEditTag); foreach (var span in spans) { if (span.GetText(subjectBuffer.CurrentSnapshot) != replacementText) { edit.Replace(span.GetSpan(subjectBuffer.CurrentSnapshot), replacementText); } } edit.ApplyAndLogExceptions(); if (!edit.HasEffectiveChanges && !this.UndoStack.Any()) { transaction.Cancel(); } else { transaction.Complete(); } } protected static string GetUndoTransactionDescription(string replacementText) => replacementText == string.Empty ? "Delete Text" : replacementText; } }
// 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. #nullable disable using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Operations; namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename { /// <summary> /// This class contains the logic common to VS and ETA when implementing IInlineRenameUndoManager /// </summary> internal abstract class AbstractInlineRenameUndoManager<TBufferState> { protected class ActiveSpanState { public string ReplacementText; public int SelectionAnchorPoint; public int SelectionActivePoint; } protected readonly InlineRenameService InlineRenameService; protected readonly Dictionary<ITextBuffer, TBufferState> UndoManagers = new Dictionary<ITextBuffer, TBufferState>(); protected readonly Stack<ActiveSpanState> UndoStack = new Stack<ActiveSpanState>(); protected readonly Stack<ActiveSpanState> RedoStack = new Stack<ActiveSpanState>(); protected ActiveSpanState initialState; protected ActiveSpanState currentState; protected bool updatePending = false; public AbstractInlineRenameUndoManager(InlineRenameService inlineRenameService) => this.InlineRenameService = inlineRenameService; public void Disconnect() { this.UndoManagers.Clear(); this.UndoStack.Clear(); this.RedoStack.Clear(); this.initialState = null; this.currentState = null; } private void UpdateCurrentState(string replacementText, ITextSelection selection, SnapshotSpan activeSpan) { var snapshot = activeSpan.Snapshot; var selectionSpan = selection.GetSnapshotSpansOnBuffer(snapshot.TextBuffer).Single(); var start = selectionSpan.Start.TranslateTo(snapshot, PointTrackingMode.Positive).Position - activeSpan.Start.Position; var end = selectionSpan.End.TranslateTo(snapshot, PointTrackingMode.Positive).Position - activeSpan.Start.Position; this.currentState = new ActiveSpanState() { ReplacementText = replacementText, SelectionAnchorPoint = selection.IsReversed ? end : start, SelectionActivePoint = selection.IsReversed ? start : end }; } public void CreateInitialState(string replacementText, ITextSelection selection, SnapshotSpan startingSpan) { UpdateCurrentState(replacementText, selection, startingSpan); this.initialState = this.currentState; } public void OnTextChanged(ITextSelection selection, SnapshotSpan singleTrackingSpanTouched) { this.RedoStack.Clear(); if (!this.UndoStack.Any()) { this.UndoStack.Push(this.initialState); } // For now, we will only ever be one Undo away from the beginning of the rename session. We can // implement Undo merging in the future. var replacementText = singleTrackingSpanTouched.GetText(); UpdateCurrentState(replacementText, selection, singleTrackingSpanTouched); this.InlineRenameService.ActiveSession.ApplyReplacementText(replacementText, propagateEditImmediately: false); } public void UpdateSelection(ITextView textView, ITextBuffer subjectBuffer, ITrackingSpan activeRenameSpan) { var snapshot = subjectBuffer.CurrentSnapshot; var anchor = new VirtualSnapshotPoint(snapshot, this.currentState.SelectionAnchorPoint + activeRenameSpan.GetStartPoint(snapshot)); var active = new VirtualSnapshotPoint(snapshot, this.currentState.SelectionActivePoint + activeRenameSpan.GetStartPoint(snapshot)); textView.SetSelection(anchor, active); } public void Undo(ITextBuffer _) { if (this.UndoStack.Count > 0) { this.RedoStack.Push(this.currentState); this.currentState = this.UndoStack.Pop(); this.InlineRenameService.ActiveSession.ApplyReplacementText(this.currentState.ReplacementText, propagateEditImmediately: true); } else { this.InlineRenameService.ActiveSession.Cancel(); } } public void Redo(ITextBuffer _) { if (this.RedoStack.Count > 0) { this.UndoStack.Push(this.currentState); this.currentState = this.RedoStack.Pop(); this.InlineRenameService.ActiveSession.ApplyReplacementText(this.currentState.ReplacementText, propagateEditImmediately: true); } } protected abstract void UndoTemporaryEdits(ITextBuffer subjectBuffer, bool disconnect, bool undoConflictResolution); protected void ApplyReplacementText(ITextBuffer subjectBuffer, ITextUndoHistory undoHistory, object propagateSpansEditTag, IEnumerable<ITrackingSpan> spans, string replacementText) { // roll back to the initial state for the buffer after conflict resolution this.UndoTemporaryEdits(subjectBuffer, disconnect: false, undoConflictResolution: replacementText == string.Empty); using var transaction = undoHistory.CreateTransaction(GetUndoTransactionDescription(replacementText)); using var edit = subjectBuffer.CreateEdit(EditOptions.None, null, propagateSpansEditTag); foreach (var span in spans) { if (span.GetText(subjectBuffer.CurrentSnapshot) != replacementText) { edit.Replace(span.GetSpan(subjectBuffer.CurrentSnapshot), replacementText); } } edit.ApplyAndLogExceptions(); if (!edit.HasEffectiveChanges && !this.UndoStack.Any()) { transaction.Cancel(); } else { transaction.Complete(); } } protected static string GetUndoTransactionDescription(string replacementText) => replacementText == string.Empty ? "Delete Text" : replacementText; } }
-1
dotnet/roslyn
56,015
Remove obsolete APIs
Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
tmat
"2021-08-30T20:53:26Z"
"2021-09-02T16:56:01Z"
bdf1025480ad91f8db054959553257746f58f527
e782ce78f087060a3bc51737d3f07a6d102fb7b1
Remove obsolete APIs. Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
./src/EditorFeatures/CSharpTest/ConvertAutoPropertyToFullProperty/ConvertAutoPropertyToFullPropertyTests.cs
// 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. #nullable disable using System.Collections.Immutable; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.ConvertAutoPropertyToFullProperty; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ConvertAutoPropertyToFullProperty { public partial class ConvertAutoPropertyToFullPropertyTests : AbstractCSharpCodeActionTest { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new CSharpConvertAutoPropertyToFullPropertyCodeRefactoringProvider(); [Theory, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] [InlineData("set"), InlineData("init")] [WorkItem(48133, "https://github.com/dotnet/roslyn/issues/48133")] public async Task SimpleAutoPropertyTest(string setter) { var text = $@" class TestClass {{ public int G[||]oo {{ get; {setter}; }} }} "; var expected = $@" class TestClass {{ private int goo; public int Goo {{ get {{ return goo; }} {setter} {{ goo = value; }} }} }} "; await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors); } [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task ExtraLineAfterProperty() { var text = @" class TestClass { public int G[||]oo { get; set; } } "; var expected = @" class TestClass { private int goo; public int Goo { get { return goo; } set { goo = value; } } } "; await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors); } [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task WithInitialValue() { var text = @" class TestClass { public int G[||]oo { get; set; } = 2 } "; var expected = @" class TestClass { private int goo = 2; public int Goo { get { return goo; } set { goo = value; } } } "; await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors); } [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task WithCalculatedInitialValue() { var text = @" class TestClass { const int num = 345; public int G[||]oo { get; set; } = 2*num } "; var expected = @" class TestClass { const int num = 345; private int goo = 2 * num; public int Goo { get { return goo; } set { goo = value; } } } "; await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors); } [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task WithPrivateSetter() { var text = @" class TestClass { public int G[||]oo { get; private set; } } "; var expected = @" class TestClass { private int goo; public int Goo { get { return goo; } private set { goo = value; } } } "; await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors); } [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task WithFieldNameAlreadyUsed() { var text = @" class TestClass { private int goo; public int G[||]oo { get; private set; } } "; var expected = @" class TestClass { private int goo; private int goo1; public int Goo { get { return goo1; } private set { goo1 = value; } } } "; await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors); } [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task WithComments() { var text = @" class TestClass { // Comments before public int G[||]oo { get; private set; } //Comments during //Comments after } "; var expected = @" class TestClass { private int goo; // Comments before public int Goo { get { return goo; } private set { goo = value; } } //Comments during //Comments after } "; await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors); } [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task WithExpressionBody() { var text = @" class TestClass { public int G[||]oo { get; set; } } "; var expected = @" class TestClass { private int goo; public int Goo { get => goo; set => goo = value; } } "; await TestInRegularAndScriptAsync(text, expected, options: PreferExpressionBodiedAccessorsWhenPossible); } [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task WithExpressionBodyWhenOnSingleLine() { var text = @" class TestClass { public int G[||]oo { get; set; } } "; var expected = @" class TestClass { private int goo; public int Goo { get => goo; set => goo = value; } } "; await TestInRegularAndScriptAsync(text, expected, options: PreferExpressionBodiedAccessorsWhenOnSingleLine); } [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task WithExpressionBodyWhenOnSingleLine2() { var text = @" class TestClass { public int G[||]oo { get; set; } } "; var expected = @" class TestClass { private int goo; public int Goo { get => goo; set => goo = value; } } "; await TestInRegularAndScriptAsync(text, expected, options: PreferExpressionBodiedAccessorsWhenOnSingleLine); } [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task WithExpressionBodyWithTrivia() { var text = @" class TestClass { public int G[||]oo { get /* test */ ; set /* test2 */ ; } } "; var expected = @" class TestClass { private int goo; public int Goo { get /* test */ => goo; set /* test2 */ => goo = value; } } "; await TestInRegularAndScriptAsync(text, expected, options: PreferExpressionBodiedAccessorsWhenPossible); } [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task WithPropertyOpenBraceOnSameLine() { var text = @" class TestClass { public int G[||]oo { get; set; } } "; var expected = @" class TestClass { private int goo; public int Goo { get { return goo; } set { goo = value; } } } "; await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessorsAndPropertyOpenBraceOnSameLine); } [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task WithAccessorOpenBraceOnSameLine() { var text = @" class TestClass { public int G[||]oo { get; set; } } "; var expected = @" class TestClass { private int goo; public int Goo { get { return goo; } set { goo = value; } } } "; await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessorsAndAccessorOpenBraceOnSameLine); } [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task StaticProperty() { var text = @" class TestClass { public static int G[||]oo { get; set; } } "; var expected = @" class TestClass { private static int goo; public static int Goo { get { return goo; } set { goo = value; } } } "; await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors); } [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task ProtectedProperty() { var text = @" class TestClass { protected int G[||]oo { get; set; } } "; var expected = @" class TestClass { private int goo; protected int Goo { get { return goo; } set { goo = value; } } } "; await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors); } [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task InternalProperty() { var text = @" class TestClass { internal int G[||]oo { get; set; } } "; var expected = @" class TestClass { private int goo; internal int Goo { get { return goo; } set { goo = value; } } } "; await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors); } [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task WithAttributes() { var text = @" class TestClass { [A] public int G[||]oo { get; set; } } "; var expected = @" class TestClass { private int goo; [A] public int Goo { get { return goo; } set { goo = value; } } } "; await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors); } [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task CommentsInAccessors() { var text = @" class TestClass { /// <summary> /// test stuff here /// </summary> public int Testg[||]oo { /* test1 */ get /* test2 */; /* test3 */ set /* test4 */; /* test5 */ } /* test6 */ } "; var expected = @" class TestClass { private int testgoo; /// <summary> /// test stuff here /// </summary> public int Testgoo { /* test1 */ get /* test2 */ { return testgoo; } /* test3 */ set /* test4 */ { testgoo = value; } /* test5 */ } /* test6 */ } "; await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors); } [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task OverrideProperty() { var text = @" class MyBaseClass { public virtual string Name { get; set; } } class MyDerivedClass : MyBaseClass { public override string N[||]ame {get; set;} } "; var expected = @" class MyBaseClass { public virtual string Name { get; set; } } class MyDerivedClass : MyBaseClass { private string name; public override string Name { get { return name; } set { name = value; } } } "; await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors); } [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task SealedProperty() { var text = @" class MyClass { public sealed string N[||]ame {get; set;} } "; var expected = @" class MyClass { private string name; public sealed string Name { get { return name; } set { name = value; } } } "; await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors); } [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task VirtualProperty() { var text = @" class MyBaseClass { public virtual string N[||]ame { get; set; } } class MyDerivedClass : MyBaseClass { public override string Name {get; set;} } "; var expected = @" class MyBaseClass { private string name; public virtual string Name { get { return name; } set { name = value; } } } class MyDerivedClass : MyBaseClass { public override string Name {get; set;} } "; await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors); } [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task PrivateProperty() { var text = @" class MyClass { private string N[||]ame { get; set; } } "; var expected = @" class MyClass { private string name; private string Name { get { return name; } set { name = value; } } } "; await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors); } [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task AbstractProperty() { var text = @" class MyBaseClass { public abstract string N[||]ame { get; set; } } class MyDerivedClass : MyBaseClass { public override string Name {get; set;} } "; await TestMissingAsync(text); } [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task ExternProperty() { var text = @" class MyBaseClass { extern string N[||]ame { get; set; } } "; await TestMissingAsync(text); } [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task GetterOnly() { var text = @" class TestClass { public int G[||]oo { get;} } "; var expected = @" class TestClass { private readonly int goo; public int Goo { get { return goo; } } } "; await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors); } [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task GetterOnlyExpressionBodies() { var text = @" class TestClass { public int G[||]oo { get;} } "; var expected = @" class TestClass { private readonly int goo; public int Goo => goo; } "; await TestInRegularAndScriptAsync(text, expected, options: PreferExpressionBodiesOnAccessorsAndMethods); } [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task SetterOnly() { var text = @" class TestClass { public int G[||]oo { set {} } } "; await TestMissingAsync(text); } [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task ExpressionBodiedAccessors() { var text = @" class TestClass { private int testgoo; public int testg[||]oo {get => testgoo; set => testgoo = value; } } "; await TestMissingAsync(text); } [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task CursorAtBeginning() { var text = @" class TestClass { [||]public int Goo { get; set; } } "; var expected = @" class TestClass { private int goo; public int Goo { get { return goo; } set { goo = value; } } } "; await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors); } [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task CursorAtEnd() { var text = @" class TestClass { public int Goo[||] { get; set; } } "; var expected = @" class TestClass { private int goo; public int Goo { get { return goo; } set { goo = value; } } } "; await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors); } [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task CursorOnAccessors() { var text = @" class TestClass { public int Goo { g[||]et; set; } } "; await TestMissingAsync(text); } [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task CursorInType() { var text = @" class TestClass { public in[||]t Goo { get; set; } } "; var expected = @" class TestClass { private int goo; public int Goo { get { return goo; } set { goo = value; } } } "; await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors); } [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task SelectionWhole() { var text = @" class TestClass { [|public int Goo { get; set; }|] } "; var expected = @" class TestClass { private int goo; public int Goo { get { return goo; } set { goo = value; } } } "; await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors); } [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task SelectionName() { var text = @" class TestClass { public int [|Goo|] { get; set; } } "; var expected = @" class TestClass { private int goo; public int Goo { get { return goo; } set { goo = value; } } } "; await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors); } [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task MoreThanOneGetter() { var text = @" class TestClass { public int Goo { g[||]et; get; } } "; await TestMissingAsync(text); } [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task MoreThanOneSetter() { var text = @" class TestClass { public int Goo { get; s[||]et; set; } } "; await TestMissingAsync(text); } [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task CustomFieldName() { var text = @" class TestClass { public int G[||]oo { get; set; } } "; var expected = @" class TestClass { private int testingGoo; public int Goo { get { return testingGoo; } set { testingGoo = value; } } } "; await TestInRegularAndScriptAsync(text, expected, options: UseCustomFieldName); } [WorkItem(28013, "https://github.com/dotnet/roslyn/issues/26992")] [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task UnderscorePrefixedFieldName() { var text = @" class TestClass { public int G[||]oo { get; set; } } "; var expected = @" class TestClass { private int _goo; public int Goo { get { return _goo; } set { _goo = value; } } } "; await TestInRegularAndScriptAsync(text, expected, options: UseUnderscorePrefixedFieldName); } [WorkItem(28013, "https://github.com/dotnet/roslyn/issues/26992")] [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task PropertyNameEqualsToClassNameExceptFirstCharCasingWhichCausesFieldNameCollisionByDefault() { var text = @" class stranger { public int S[||]tranger { get; set; } } "; var expected = @" class stranger { private int stranger; public int Stranger { get => stranger; set => stranger = value; } } "; await TestInRegularAndScriptAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task NonStaticPropertyWithCustomStaticFieldName() { var text = @" class TestClass { public int G[||]oo { get; set; } } "; var expected = @" class TestClass { private int goo; public int Goo { get { return goo; } set { goo = value; } } } "; await TestInRegularAndScriptAsync(text, expected, options: UseCustomStaticFieldName); } [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task StaticPropertyWithCustomStaticFieldName() { var text = @" class TestClass { public static int G[||]oo { get; set; } } "; var expected = @" class TestClass { private static int staticfieldtestGoo; public static int Goo { get { return staticfieldtestGoo; } set { staticfieldtestGoo = value; } } } "; await TestInRegularAndScriptAsync(text, expected, options: UseCustomStaticFieldName); } [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task InInterface() { var text = @" interface IGoo { public int Goo { get; s[||]et; } } "; await TestMissingAsync(text); } [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task InStruct() { var text = @" struct goo { public int G[||]oo { get; set; } } "; var expected = @" struct goo { private int goo; public int Goo { get { return goo; } set { goo = value; } } } "; await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors); } [WorkItem(22146, "https://github.com/dotnet/roslyn/issues/22146")] [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task PartialClasses() { var text = @" partial class Program { int P { get; set; } } partial class Program { int [||]Q { get; set; } } "; var expected = @" partial class Program { int P { get; set; } } partial class Program { private int q; int Q { get => q; set => q = value; } } "; await TestInRegularAndScriptAsync(text, expected); } [WorkItem(22146, "https://github.com/dotnet/roslyn/issues/22146")] [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task PartialClassInSeparateFiles1() { var file1 = @" partial class Program { int [||]P { get; set; } }"; var file2 = @" partial class Program { int Q { get; set; } }"; var file1AfterRefactor = @" partial class Program { private int p; int P { get => p; set => p = value; } }"; var xmlString = string.Format(@" <Workspace> <Project Language=""{0}"" CommonReferences=""true""> <Document FilePath=""file1"">{1}</Document> <Document FilePath=""file2"">{2}</Document> </Project> </Workspace>", LanguageNames.CSharp, file1, file2); using var testWorkspace = TestWorkspace.Create(xmlString); // refactor file1 and check var (_, action) = await GetCodeActionsAsync(testWorkspace, parameters: default); await TestActionAsync( testWorkspace, file1AfterRefactor, action, conflictSpans: ImmutableArray<TextSpan>.Empty, renameSpans: ImmutableArray<TextSpan>.Empty, warningSpans: ImmutableArray<TextSpan>.Empty, navigationSpans: ImmutableArray<TextSpan>.Empty, parameters: default); } [WorkItem(22146, "https://github.com/dotnet/roslyn/issues/22146")] [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task PartialClassInSeparateFiles2() { var file1 = @" partial class Program { int P { get; set; } }"; var file2 = @" partial class Program { int Q[||] { get; set; } }"; var file2AfterRefactor = @" partial class Program { private int q; int Q { get => q; set => q = value; } }"; var xmlString = string.Format(@" <Workspace> <Project Language=""{0}"" CommonReferences=""true""> <Document FilePath=""file1"">{1}</Document> <Document FilePath=""file2"">{2}</Document> </Project> </Workspace>", LanguageNames.CSharp, file1, file2); using var testWorkspace = TestWorkspace.Create(xmlString); // refactor file2 and check var (_, action) = await GetCodeActionsAsync(testWorkspace, parameters: default); await TestActionAsync( testWorkspace, file2AfterRefactor, action, conflictSpans: ImmutableArray<TextSpan>.Empty, renameSpans: ImmutableArray<TextSpan>.Empty, warningSpans: ImmutableArray<TextSpan>.Empty, navigationSpans: ImmutableArray<TextSpan>.Empty, parameters: default); } [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task InvalidLocation() { await TestMissingAsync(@"namespace NS { public int G[||]oo { get; set; } }"); await TestMissingAsync("public int G[||]oo { get; set; }"); } [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task NullBackingField() { await TestInRegularAndScriptAsync( @" #nullable enable class Program { string? Name[||] { get; set; } }", @" #nullable enable class Program { private string? name; string? Name { get => name; set => name = value; } }"); } } }
// 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. #nullable disable using System.Collections.Immutable; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.ConvertAutoPropertyToFullProperty; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ConvertAutoPropertyToFullProperty { public partial class ConvertAutoPropertyToFullPropertyTests : AbstractCSharpCodeActionTest { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new CSharpConvertAutoPropertyToFullPropertyCodeRefactoringProvider(); [Theory, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] [InlineData("set"), InlineData("init")] [WorkItem(48133, "https://github.com/dotnet/roslyn/issues/48133")] public async Task SimpleAutoPropertyTest(string setter) { var text = $@" class TestClass {{ public int G[||]oo {{ get; {setter}; }} }} "; var expected = $@" class TestClass {{ private int goo; public int Goo {{ get {{ return goo; }} {setter} {{ goo = value; }} }} }} "; await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors); } [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task ExtraLineAfterProperty() { var text = @" class TestClass { public int G[||]oo { get; set; } } "; var expected = @" class TestClass { private int goo; public int Goo { get { return goo; } set { goo = value; } } } "; await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors); } [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task WithInitialValue() { var text = @" class TestClass { public int G[||]oo { get; set; } = 2 } "; var expected = @" class TestClass { private int goo = 2; public int Goo { get { return goo; } set { goo = value; } } } "; await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors); } [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task WithCalculatedInitialValue() { var text = @" class TestClass { const int num = 345; public int G[||]oo { get; set; } = 2*num } "; var expected = @" class TestClass { const int num = 345; private int goo = 2 * num; public int Goo { get { return goo; } set { goo = value; } } } "; await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors); } [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task WithPrivateSetter() { var text = @" class TestClass { public int G[||]oo { get; private set; } } "; var expected = @" class TestClass { private int goo; public int Goo { get { return goo; } private set { goo = value; } } } "; await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors); } [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task WithFieldNameAlreadyUsed() { var text = @" class TestClass { private int goo; public int G[||]oo { get; private set; } } "; var expected = @" class TestClass { private int goo; private int goo1; public int Goo { get { return goo1; } private set { goo1 = value; } } } "; await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors); } [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task WithComments() { var text = @" class TestClass { // Comments before public int G[||]oo { get; private set; } //Comments during //Comments after } "; var expected = @" class TestClass { private int goo; // Comments before public int Goo { get { return goo; } private set { goo = value; } } //Comments during //Comments after } "; await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors); } [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task WithExpressionBody() { var text = @" class TestClass { public int G[||]oo { get; set; } } "; var expected = @" class TestClass { private int goo; public int Goo { get => goo; set => goo = value; } } "; await TestInRegularAndScriptAsync(text, expected, options: PreferExpressionBodiedAccessorsWhenPossible); } [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task WithExpressionBodyWhenOnSingleLine() { var text = @" class TestClass { public int G[||]oo { get; set; } } "; var expected = @" class TestClass { private int goo; public int Goo { get => goo; set => goo = value; } } "; await TestInRegularAndScriptAsync(text, expected, options: PreferExpressionBodiedAccessorsWhenOnSingleLine); } [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task WithExpressionBodyWhenOnSingleLine2() { var text = @" class TestClass { public int G[||]oo { get; set; } } "; var expected = @" class TestClass { private int goo; public int Goo { get => goo; set => goo = value; } } "; await TestInRegularAndScriptAsync(text, expected, options: PreferExpressionBodiedAccessorsWhenOnSingleLine); } [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task WithExpressionBodyWithTrivia() { var text = @" class TestClass { public int G[||]oo { get /* test */ ; set /* test2 */ ; } } "; var expected = @" class TestClass { private int goo; public int Goo { get /* test */ => goo; set /* test2 */ => goo = value; } } "; await TestInRegularAndScriptAsync(text, expected, options: PreferExpressionBodiedAccessorsWhenPossible); } [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task WithPropertyOpenBraceOnSameLine() { var text = @" class TestClass { public int G[||]oo { get; set; } } "; var expected = @" class TestClass { private int goo; public int Goo { get { return goo; } set { goo = value; } } } "; await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessorsAndPropertyOpenBraceOnSameLine); } [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task WithAccessorOpenBraceOnSameLine() { var text = @" class TestClass { public int G[||]oo { get; set; } } "; var expected = @" class TestClass { private int goo; public int Goo { get { return goo; } set { goo = value; } } } "; await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessorsAndAccessorOpenBraceOnSameLine); } [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task StaticProperty() { var text = @" class TestClass { public static int G[||]oo { get; set; } } "; var expected = @" class TestClass { private static int goo; public static int Goo { get { return goo; } set { goo = value; } } } "; await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors); } [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task ProtectedProperty() { var text = @" class TestClass { protected int G[||]oo { get; set; } } "; var expected = @" class TestClass { private int goo; protected int Goo { get { return goo; } set { goo = value; } } } "; await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors); } [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task InternalProperty() { var text = @" class TestClass { internal int G[||]oo { get; set; } } "; var expected = @" class TestClass { private int goo; internal int Goo { get { return goo; } set { goo = value; } } } "; await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors); } [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task WithAttributes() { var text = @" class TestClass { [A] public int G[||]oo { get; set; } } "; var expected = @" class TestClass { private int goo; [A] public int Goo { get { return goo; } set { goo = value; } } } "; await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors); } [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task CommentsInAccessors() { var text = @" class TestClass { /// <summary> /// test stuff here /// </summary> public int Testg[||]oo { /* test1 */ get /* test2 */; /* test3 */ set /* test4 */; /* test5 */ } /* test6 */ } "; var expected = @" class TestClass { private int testgoo; /// <summary> /// test stuff here /// </summary> public int Testgoo { /* test1 */ get /* test2 */ { return testgoo; } /* test3 */ set /* test4 */ { testgoo = value; } /* test5 */ } /* test6 */ } "; await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors); } [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task OverrideProperty() { var text = @" class MyBaseClass { public virtual string Name { get; set; } } class MyDerivedClass : MyBaseClass { public override string N[||]ame {get; set;} } "; var expected = @" class MyBaseClass { public virtual string Name { get; set; } } class MyDerivedClass : MyBaseClass { private string name; public override string Name { get { return name; } set { name = value; } } } "; await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors); } [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task SealedProperty() { var text = @" class MyClass { public sealed string N[||]ame {get; set;} } "; var expected = @" class MyClass { private string name; public sealed string Name { get { return name; } set { name = value; } } } "; await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors); } [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task VirtualProperty() { var text = @" class MyBaseClass { public virtual string N[||]ame { get; set; } } class MyDerivedClass : MyBaseClass { public override string Name {get; set;} } "; var expected = @" class MyBaseClass { private string name; public virtual string Name { get { return name; } set { name = value; } } } class MyDerivedClass : MyBaseClass { public override string Name {get; set;} } "; await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors); } [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task PrivateProperty() { var text = @" class MyClass { private string N[||]ame { get; set; } } "; var expected = @" class MyClass { private string name; private string Name { get { return name; } set { name = value; } } } "; await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors); } [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task AbstractProperty() { var text = @" class MyBaseClass { public abstract string N[||]ame { get; set; } } class MyDerivedClass : MyBaseClass { public override string Name {get; set;} } "; await TestMissingAsync(text); } [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task ExternProperty() { var text = @" class MyBaseClass { extern string N[||]ame { get; set; } } "; await TestMissingAsync(text); } [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task GetterOnly() { var text = @" class TestClass { public int G[||]oo { get;} } "; var expected = @" class TestClass { private readonly int goo; public int Goo { get { return goo; } } } "; await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors); } [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task GetterOnlyExpressionBodies() { var text = @" class TestClass { public int G[||]oo { get;} } "; var expected = @" class TestClass { private readonly int goo; public int Goo => goo; } "; await TestInRegularAndScriptAsync(text, expected, options: PreferExpressionBodiesOnAccessorsAndMethods); } [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task SetterOnly() { var text = @" class TestClass { public int G[||]oo { set {} } } "; await TestMissingAsync(text); } [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task ExpressionBodiedAccessors() { var text = @" class TestClass { private int testgoo; public int testg[||]oo {get => testgoo; set => testgoo = value; } } "; await TestMissingAsync(text); } [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task CursorAtBeginning() { var text = @" class TestClass { [||]public int Goo { get; set; } } "; var expected = @" class TestClass { private int goo; public int Goo { get { return goo; } set { goo = value; } } } "; await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors); } [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task CursorAtEnd() { var text = @" class TestClass { public int Goo[||] { get; set; } } "; var expected = @" class TestClass { private int goo; public int Goo { get { return goo; } set { goo = value; } } } "; await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors); } [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task CursorOnAccessors() { var text = @" class TestClass { public int Goo { g[||]et; set; } } "; await TestMissingAsync(text); } [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task CursorInType() { var text = @" class TestClass { public in[||]t Goo { get; set; } } "; var expected = @" class TestClass { private int goo; public int Goo { get { return goo; } set { goo = value; } } } "; await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors); } [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task SelectionWhole() { var text = @" class TestClass { [|public int Goo { get; set; }|] } "; var expected = @" class TestClass { private int goo; public int Goo { get { return goo; } set { goo = value; } } } "; await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors); } [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task SelectionName() { var text = @" class TestClass { public int [|Goo|] { get; set; } } "; var expected = @" class TestClass { private int goo; public int Goo { get { return goo; } set { goo = value; } } } "; await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors); } [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task MoreThanOneGetter() { var text = @" class TestClass { public int Goo { g[||]et; get; } } "; await TestMissingAsync(text); } [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task MoreThanOneSetter() { var text = @" class TestClass { public int Goo { get; s[||]et; set; } } "; await TestMissingAsync(text); } [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task CustomFieldName() { var text = @" class TestClass { public int G[||]oo { get; set; } } "; var expected = @" class TestClass { private int testingGoo; public int Goo { get { return testingGoo; } set { testingGoo = value; } } } "; await TestInRegularAndScriptAsync(text, expected, options: UseCustomFieldName); } [WorkItem(28013, "https://github.com/dotnet/roslyn/issues/26992")] [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task UnderscorePrefixedFieldName() { var text = @" class TestClass { public int G[||]oo { get; set; } } "; var expected = @" class TestClass { private int _goo; public int Goo { get { return _goo; } set { _goo = value; } } } "; await TestInRegularAndScriptAsync(text, expected, options: UseUnderscorePrefixedFieldName); } [WorkItem(28013, "https://github.com/dotnet/roslyn/issues/26992")] [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task PropertyNameEqualsToClassNameExceptFirstCharCasingWhichCausesFieldNameCollisionByDefault() { var text = @" class stranger { public int S[||]tranger { get; set; } } "; var expected = @" class stranger { private int stranger; public int Stranger { get => stranger; set => stranger = value; } } "; await TestInRegularAndScriptAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task NonStaticPropertyWithCustomStaticFieldName() { var text = @" class TestClass { public int G[||]oo { get; set; } } "; var expected = @" class TestClass { private int goo; public int Goo { get { return goo; } set { goo = value; } } } "; await TestInRegularAndScriptAsync(text, expected, options: UseCustomStaticFieldName); } [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task StaticPropertyWithCustomStaticFieldName() { var text = @" class TestClass { public static int G[||]oo { get; set; } } "; var expected = @" class TestClass { private static int staticfieldtestGoo; public static int Goo { get { return staticfieldtestGoo; } set { staticfieldtestGoo = value; } } } "; await TestInRegularAndScriptAsync(text, expected, options: UseCustomStaticFieldName); } [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task InInterface() { var text = @" interface IGoo { public int Goo { get; s[||]et; } } "; await TestMissingAsync(text); } [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task InStruct() { var text = @" struct goo { public int G[||]oo { get; set; } } "; var expected = @" struct goo { private int goo; public int Goo { get { return goo; } set { goo = value; } } } "; await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors); } [WorkItem(22146, "https://github.com/dotnet/roslyn/issues/22146")] [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task PartialClasses() { var text = @" partial class Program { int P { get; set; } } partial class Program { int [||]Q { get; set; } } "; var expected = @" partial class Program { int P { get; set; } } partial class Program { private int q; int Q { get => q; set => q = value; } } "; await TestInRegularAndScriptAsync(text, expected); } [WorkItem(22146, "https://github.com/dotnet/roslyn/issues/22146")] [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task PartialClassInSeparateFiles1() { var file1 = @" partial class Program { int [||]P { get; set; } }"; var file2 = @" partial class Program { int Q { get; set; } }"; var file1AfterRefactor = @" partial class Program { private int p; int P { get => p; set => p = value; } }"; var xmlString = string.Format(@" <Workspace> <Project Language=""{0}"" CommonReferences=""true""> <Document FilePath=""file1"">{1}</Document> <Document FilePath=""file2"">{2}</Document> </Project> </Workspace>", LanguageNames.CSharp, file1, file2); using var testWorkspace = TestWorkspace.Create(xmlString); // refactor file1 and check var (_, action) = await GetCodeActionsAsync(testWorkspace, parameters: default); await TestActionAsync( testWorkspace, file1AfterRefactor, action, conflictSpans: ImmutableArray<TextSpan>.Empty, renameSpans: ImmutableArray<TextSpan>.Empty, warningSpans: ImmutableArray<TextSpan>.Empty, navigationSpans: ImmutableArray<TextSpan>.Empty, parameters: default); } [WorkItem(22146, "https://github.com/dotnet/roslyn/issues/22146")] [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task PartialClassInSeparateFiles2() { var file1 = @" partial class Program { int P { get; set; } }"; var file2 = @" partial class Program { int Q[||] { get; set; } }"; var file2AfterRefactor = @" partial class Program { private int q; int Q { get => q; set => q = value; } }"; var xmlString = string.Format(@" <Workspace> <Project Language=""{0}"" CommonReferences=""true""> <Document FilePath=""file1"">{1}</Document> <Document FilePath=""file2"">{2}</Document> </Project> </Workspace>", LanguageNames.CSharp, file1, file2); using var testWorkspace = TestWorkspace.Create(xmlString); // refactor file2 and check var (_, action) = await GetCodeActionsAsync(testWorkspace, parameters: default); await TestActionAsync( testWorkspace, file2AfterRefactor, action, conflictSpans: ImmutableArray<TextSpan>.Empty, renameSpans: ImmutableArray<TextSpan>.Empty, warningSpans: ImmutableArray<TextSpan>.Empty, navigationSpans: ImmutableArray<TextSpan>.Empty, parameters: default); } [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task InvalidLocation() { await TestMissingAsync(@"namespace NS { public int G[||]oo { get; set; } }"); await TestMissingAsync("public int G[||]oo { get; set; }"); } [Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)] public async Task NullBackingField() { await TestInRegularAndScriptAsync( @" #nullable enable class Program { string? Name[||] { get; set; } }", @" #nullable enable class Program { private string? name; string? Name { get => name; set => name = value; } }"); } } }
-1
dotnet/roslyn
56,015
Remove obsolete APIs
Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
tmat
"2021-08-30T20:53:26Z"
"2021-09-02T16:56:01Z"
bdf1025480ad91f8db054959553257746f58f527
e782ce78f087060a3bc51737d3f07a6d102fb7b1
Remove obsolete APIs. Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
./src/Compilers/CSharp/Portable/Syntax/SyntaxTreeDiagnosticEnumerator.cs
// 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. using System; using System.Diagnostics; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// An enumerator for diagnostic lists. /// </summary> internal struct SyntaxTreeDiagnosticEnumerator { private readonly SyntaxTree? _syntaxTree; private NodeIterationStack _stack; private Diagnostic? _current; private int _position; private const int DefaultStackCapacity = 8; internal SyntaxTreeDiagnosticEnumerator(SyntaxTree syntaxTree, GreenNode? node, int position) { _syntaxTree = null; _current = null; _position = position; if (node != null && node.ContainsDiagnostics) { _syntaxTree = syntaxTree; _stack = new NodeIterationStack(DefaultStackCapacity); _stack.PushNodeOrToken(node); } else { _stack = new NodeIterationStack(); } } /// <summary> /// Moves the enumerator to the next diagnostic instance in the diagnostic list. /// </summary> /// <returns>Returns true if enumerator moved to the next diagnostic, false if the /// enumerator was at the end of the diagnostic list.</returns> public bool MoveNext() { while (_stack.Any()) { var diagIndex = _stack.Top.DiagnosticIndex; var node = _stack.Top.Node; var diags = node.GetDiagnostics(); if (diagIndex < diags.Length - 1) { diagIndex++; var sdi = (SyntaxDiagnosticInfo)diags[diagIndex]; //for tokens, we've already seen leading trivia on the stack, so we have to roll back //for nodes, we have yet to see the leading trivia int leadingWidthAlreadyCounted = node.IsToken ? node.GetLeadingTriviaWidth() : 0; // don't produce locations outside of tree span Debug.Assert(_syntaxTree is object); var length = _syntaxTree.GetRoot().FullSpan.Length; var spanStart = Math.Min(_position - leadingWidthAlreadyCounted + sdi.Offset, length); var spanWidth = Math.Min(spanStart + sdi.Width, length) - spanStart; _current = new CSDiagnostic(sdi, new SourceLocation(_syntaxTree, new TextSpan(spanStart, spanWidth))); _stack.UpdateDiagnosticIndexForStackTop(diagIndex); return true; } var slotIndex = _stack.Top.SlotIndex; tryAgain: if (slotIndex < node.SlotCount - 1) { slotIndex++; var child = node.GetSlot(slotIndex); if (child == null) { goto tryAgain; } if (!child.ContainsDiagnostics) { _position += child.FullWidth; goto tryAgain; } _stack.UpdateSlotIndexForStackTop(slotIndex); _stack.PushNodeOrToken(child); } else { if (node.SlotCount == 0) { _position += node.Width; } _stack.Pop(); } } return false; } /// <summary> /// The current diagnostic that the enumerator is pointing at. /// </summary> public Diagnostic Current { get { Debug.Assert(_current is object); return _current; } } private struct NodeIteration { internal readonly GreenNode Node; internal int DiagnosticIndex; internal int SlotIndex; internal NodeIteration(GreenNode node) { this.Node = node; this.SlotIndex = -1; this.DiagnosticIndex = -1; } } private struct NodeIterationStack { private NodeIteration[] _stack; private int _count; internal NodeIterationStack(int capacity) { Debug.Assert(capacity > 0); _stack = new NodeIteration[capacity]; _count = 0; } internal void PushNodeOrToken(GreenNode node) { var token = node as Syntax.InternalSyntax.SyntaxToken; if (token != null) { PushToken(token); } else { Push(node); } } private void PushToken(Syntax.InternalSyntax.SyntaxToken token) { var trailing = token.GetTrailingTrivia(); if (trailing != null) { this.Push(trailing); } this.Push(token); var leading = token.GetLeadingTrivia(); if (leading != null) { this.Push(leading); } } private void Push(GreenNode node) { if (_count >= _stack.Length) { var tmp = new NodeIteration[_stack.Length * 2]; Array.Copy(_stack, tmp, _stack.Length); _stack = tmp; } _stack[_count] = new NodeIteration(node); _count++; } internal void Pop() { _count--; } internal bool Any() { return _count > 0; } internal NodeIteration Top { get { return this[_count - 1]; } } internal NodeIteration this[int index] { get { Debug.Assert(_stack != null); Debug.Assert(index >= 0 && index < _count); return _stack[index]; } } internal void UpdateSlotIndexForStackTop(int slotIndex) { Debug.Assert(_stack != null); Debug.Assert(_count > 0); _stack[_count - 1].SlotIndex = slotIndex; } internal void UpdateDiagnosticIndexForStackTop(int diagnosticIndex) { Debug.Assert(_stack != null); Debug.Assert(_count > 0); _stack[_count - 1].DiagnosticIndex = diagnosticIndex; } } } }
// 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. using System; using System.Diagnostics; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// An enumerator for diagnostic lists. /// </summary> internal struct SyntaxTreeDiagnosticEnumerator { private readonly SyntaxTree? _syntaxTree; private NodeIterationStack _stack; private Diagnostic? _current; private int _position; private const int DefaultStackCapacity = 8; internal SyntaxTreeDiagnosticEnumerator(SyntaxTree syntaxTree, GreenNode? node, int position) { _syntaxTree = null; _current = null; _position = position; if (node != null && node.ContainsDiagnostics) { _syntaxTree = syntaxTree; _stack = new NodeIterationStack(DefaultStackCapacity); _stack.PushNodeOrToken(node); } else { _stack = new NodeIterationStack(); } } /// <summary> /// Moves the enumerator to the next diagnostic instance in the diagnostic list. /// </summary> /// <returns>Returns true if enumerator moved to the next diagnostic, false if the /// enumerator was at the end of the diagnostic list.</returns> public bool MoveNext() { while (_stack.Any()) { var diagIndex = _stack.Top.DiagnosticIndex; var node = _stack.Top.Node; var diags = node.GetDiagnostics(); if (diagIndex < diags.Length - 1) { diagIndex++; var sdi = (SyntaxDiagnosticInfo)diags[diagIndex]; //for tokens, we've already seen leading trivia on the stack, so we have to roll back //for nodes, we have yet to see the leading trivia int leadingWidthAlreadyCounted = node.IsToken ? node.GetLeadingTriviaWidth() : 0; // don't produce locations outside of tree span Debug.Assert(_syntaxTree is object); var length = _syntaxTree.GetRoot().FullSpan.Length; var spanStart = Math.Min(_position - leadingWidthAlreadyCounted + sdi.Offset, length); var spanWidth = Math.Min(spanStart + sdi.Width, length) - spanStart; _current = new CSDiagnostic(sdi, new SourceLocation(_syntaxTree, new TextSpan(spanStart, spanWidth))); _stack.UpdateDiagnosticIndexForStackTop(diagIndex); return true; } var slotIndex = _stack.Top.SlotIndex; tryAgain: if (slotIndex < node.SlotCount - 1) { slotIndex++; var child = node.GetSlot(slotIndex); if (child == null) { goto tryAgain; } if (!child.ContainsDiagnostics) { _position += child.FullWidth; goto tryAgain; } _stack.UpdateSlotIndexForStackTop(slotIndex); _stack.PushNodeOrToken(child); } else { if (node.SlotCount == 0) { _position += node.Width; } _stack.Pop(); } } return false; } /// <summary> /// The current diagnostic that the enumerator is pointing at. /// </summary> public Diagnostic Current { get { Debug.Assert(_current is object); return _current; } } private struct NodeIteration { internal readonly GreenNode Node; internal int DiagnosticIndex; internal int SlotIndex; internal NodeIteration(GreenNode node) { this.Node = node; this.SlotIndex = -1; this.DiagnosticIndex = -1; } } private struct NodeIterationStack { private NodeIteration[] _stack; private int _count; internal NodeIterationStack(int capacity) { Debug.Assert(capacity > 0); _stack = new NodeIteration[capacity]; _count = 0; } internal void PushNodeOrToken(GreenNode node) { var token = node as Syntax.InternalSyntax.SyntaxToken; if (token != null) { PushToken(token); } else { Push(node); } } private void PushToken(Syntax.InternalSyntax.SyntaxToken token) { var trailing = token.GetTrailingTrivia(); if (trailing != null) { this.Push(trailing); } this.Push(token); var leading = token.GetLeadingTrivia(); if (leading != null) { this.Push(leading); } } private void Push(GreenNode node) { if (_count >= _stack.Length) { var tmp = new NodeIteration[_stack.Length * 2]; Array.Copy(_stack, tmp, _stack.Length); _stack = tmp; } _stack[_count] = new NodeIteration(node); _count++; } internal void Pop() { _count--; } internal bool Any() { return _count > 0; } internal NodeIteration Top { get { return this[_count - 1]; } } internal NodeIteration this[int index] { get { Debug.Assert(_stack != null); Debug.Assert(index >= 0 && index < _count); return _stack[index]; } } internal void UpdateSlotIndexForStackTop(int slotIndex) { Debug.Assert(_stack != null); Debug.Assert(_count > 0); _stack[_count - 1].SlotIndex = slotIndex; } internal void UpdateDiagnosticIndexForStackTop(int diagnosticIndex) { Debug.Assert(_stack != null); Debug.Assert(_count > 0); _stack[_count - 1].DiagnosticIndex = diagnosticIndex; } } } }
-1
dotnet/roslyn
56,015
Remove obsolete APIs
Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
tmat
"2021-08-30T20:53:26Z"
"2021-09-02T16:56:01Z"
bdf1025480ad91f8db054959553257746f58f527
e782ce78f087060a3bc51737d3f07a6d102fb7b1
Remove obsolete APIs. Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/ICacheEntry.cs
// 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 Roslyn.Utilities { internal interface ICacheEntry<out TKey, out TValue> { TKey Key { get; } TValue Value { get; } } }
// 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 Roslyn.Utilities { internal interface ICacheEntry<out TKey, out TValue> { TKey Key { get; } TValue Value { get; } } }
-1
dotnet/roslyn
56,015
Remove obsolete APIs
Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
tmat
"2021-08-30T20:53:26Z"
"2021-09-02T16:56:01Z"
bdf1025480ad91f8db054959553257746f58f527
e782ce78f087060a3bc51737d3f07a6d102fb7b1
Remove obsolete APIs. Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
./src/Compilers/CSharp/Portable/Symbols/SynthesizedNamespaceSymbol.cs
// 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. #nullable disable using System.Collections.Immutable; using Roslyn.Utilities; using System.Diagnostics; using System; using Microsoft.CodeAnalysis.Emit; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Synthesized namespace that contains synthesized types or subnamespaces. /// All its members are stored in a table on <see cref="CommonPEModuleBuilder"/>. /// </summary> internal sealed class SynthesizedNamespaceSymbol : NamespaceSymbol { private readonly string _name; private readonly NamespaceSymbol _containingSymbol; public SynthesizedNamespaceSymbol(NamespaceSymbol containingNamespace, string name) { Debug.Assert(containingNamespace is object); Debug.Assert(name is object); _containingSymbol = containingNamespace; _name = name; } public override int GetHashCode() => Hash.Combine(_containingSymbol.GetHashCode(), _name.GetHashCode()); public override bool Equals(Symbol obj, TypeCompareKind compareKind) => obj is SynthesizedNamespaceSymbol other && Equals(other, compareKind); public bool Equals(SynthesizedNamespaceSymbol other, TypeCompareKind compareKind) { if (ReferenceEquals(this, other)) { return true; } return other is object && _name.Equals(other._name) && _containingSymbol.Equals(other._containingSymbol); } internal override NamespaceExtent Extent => _containingSymbol.Extent; public override string Name => _name; public override Symbol ContainingSymbol => _containingSymbol; public override AssemblySymbol ContainingAssembly => _containingSymbol.ContainingAssembly; public override ImmutableArray<Location> Locations => ImmutableArray<Location>.Empty; public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences => ImmutableArray<SyntaxReference>.Empty; public override ImmutableArray<NamedTypeSymbol> GetTypeMembers() => ImmutableArray<NamedTypeSymbol>.Empty; public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name) => ImmutableArray<NamedTypeSymbol>.Empty; public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name, int arity) => ImmutableArray<NamedTypeSymbol>.Empty; public override ImmutableArray<Symbol> GetMembers() => ImmutableArray<Symbol>.Empty; public override ImmutableArray<Symbol> GetMembers(string name) => ImmutableArray<Symbol>.Empty; } }
// 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. #nullable disable using System.Collections.Immutable; using Roslyn.Utilities; using System.Diagnostics; using System; using Microsoft.CodeAnalysis.Emit; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Synthesized namespace that contains synthesized types or subnamespaces. /// All its members are stored in a table on <see cref="CommonPEModuleBuilder"/>. /// </summary> internal sealed class SynthesizedNamespaceSymbol : NamespaceSymbol { private readonly string _name; private readonly NamespaceSymbol _containingSymbol; public SynthesizedNamespaceSymbol(NamespaceSymbol containingNamespace, string name) { Debug.Assert(containingNamespace is object); Debug.Assert(name is object); _containingSymbol = containingNamespace; _name = name; } public override int GetHashCode() => Hash.Combine(_containingSymbol.GetHashCode(), _name.GetHashCode()); public override bool Equals(Symbol obj, TypeCompareKind compareKind) => obj is SynthesizedNamespaceSymbol other && Equals(other, compareKind); public bool Equals(SynthesizedNamespaceSymbol other, TypeCompareKind compareKind) { if (ReferenceEquals(this, other)) { return true; } return other is object && _name.Equals(other._name) && _containingSymbol.Equals(other._containingSymbol); } internal override NamespaceExtent Extent => _containingSymbol.Extent; public override string Name => _name; public override Symbol ContainingSymbol => _containingSymbol; public override AssemblySymbol ContainingAssembly => _containingSymbol.ContainingAssembly; public override ImmutableArray<Location> Locations => ImmutableArray<Location>.Empty; public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences => ImmutableArray<SyntaxReference>.Empty; public override ImmutableArray<NamedTypeSymbol> GetTypeMembers() => ImmutableArray<NamedTypeSymbol>.Empty; public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name) => ImmutableArray<NamedTypeSymbol>.Empty; public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name, int arity) => ImmutableArray<NamedTypeSymbol>.Empty; public override ImmutableArray<Symbol> GetMembers() => ImmutableArray<Symbol>.Empty; public override ImmutableArray<Symbol> GetMembers(string name) => ImmutableArray<Symbol>.Empty; } }
-1
dotnet/roslyn
56,015
Remove obsolete APIs
Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
tmat
"2021-08-30T20:53:26Z"
"2021-09-02T16:56:01Z"
bdf1025480ad91f8db054959553257746f58f527
e782ce78f087060a3bc51737d3f07a6d102fb7b1
Remove obsolete APIs. Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
./src/Features/CSharp/Portable/Structure/Providers/ParenthesizedLambdaExpressionStructureProvider.cs
// 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. using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Structure; namespace Microsoft.CodeAnalysis.CSharp.Structure { internal class ParenthesizedLambdaExpressionStructureProvider : AbstractSyntaxNodeStructureProvider<ParenthesizedLambdaExpressionSyntax> { protected override void CollectBlockSpans( SyntaxToken previousToken, ParenthesizedLambdaExpressionSyntax lambdaExpression, ref TemporaryArray<BlockSpan> spans, BlockStructureOptionProvider optionProvider, CancellationToken cancellationToken) { // fault tolerance if (lambdaExpression.Body.IsMissing) { return; } if (!(lambdaExpression.Body is BlockSyntax lambdaBlock) || lambdaBlock.OpenBraceToken.IsMissing || lambdaBlock.CloseBraceToken.IsMissing) { return; } var lastToken = CSharpStructureHelpers.GetLastInlineMethodBlockToken(lambdaExpression); if (lastToken.Kind() == SyntaxKind.None) { return; } spans.AddIfNotNull(CSharpStructureHelpers.CreateBlockSpan( lambdaExpression, lambdaExpression.ArrowToken, lastToken, compressEmptyLines: false, autoCollapse: false, type: BlockTypes.Expression, isCollapsible: true)); } } }
// 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. using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Structure; namespace Microsoft.CodeAnalysis.CSharp.Structure { internal class ParenthesizedLambdaExpressionStructureProvider : AbstractSyntaxNodeStructureProvider<ParenthesizedLambdaExpressionSyntax> { protected override void CollectBlockSpans( SyntaxToken previousToken, ParenthesizedLambdaExpressionSyntax lambdaExpression, ref TemporaryArray<BlockSpan> spans, BlockStructureOptionProvider optionProvider, CancellationToken cancellationToken) { // fault tolerance if (lambdaExpression.Body.IsMissing) { return; } if (!(lambdaExpression.Body is BlockSyntax lambdaBlock) || lambdaBlock.OpenBraceToken.IsMissing || lambdaBlock.CloseBraceToken.IsMissing) { return; } var lastToken = CSharpStructureHelpers.GetLastInlineMethodBlockToken(lambdaExpression); if (lastToken.Kind() == SyntaxKind.None) { return; } spans.AddIfNotNull(CSharpStructureHelpers.CreateBlockSpan( lambdaExpression, lambdaExpression.ArrowToken, lastToken, compressEmptyLines: false, autoCollapse: false, type: BlockTypes.Expression, isCollapsible: true)); } } }
-1
dotnet/roslyn
56,015
Remove obsolete APIs
Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
tmat
"2021-08-30T20:53:26Z"
"2021-09-02T16:56:01Z"
bdf1025480ad91f8db054959553257746f58f527
e782ce78f087060a3bc51737d3f07a6d102fb7b1
Remove obsolete APIs. Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
./src/Workspaces/Core/Portable/Workspace/Host/PersistentStorage/IPersistentStorage.cs
// 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. using System; using System.IO; using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.Host { /// <remarks> /// Instances of <see cref="IPersistentStorage"/> support both synchronous and asynchronous disposal. Asynchronous /// disposal should always be preferred as the implementation of synchronous disposal may end up blocking the caller /// on async work. /// </remarks> public interface IPersistentStorage : IDisposable, IAsyncDisposable { Task<Stream?> ReadStreamAsync(string name, CancellationToken cancellationToken = default); Task<Stream?> ReadStreamAsync(Project project, string name, CancellationToken cancellationToken = default); Task<Stream?> ReadStreamAsync(Document document, string name, CancellationToken cancellationToken = default); /// <summary> /// Returns <see langword="true"/> if the data was successfully persisted to the storage subsystem. Subsequent /// calls to read the same keys should succeed if called within the same session. /// </summary> Task<bool> WriteStreamAsync(string name, Stream stream, CancellationToken cancellationToken = default); /// <summary> /// Returns <see langword="true"/> if the data was successfully persisted to the storage subsystem. Subsequent /// calls to read the same keys should succeed if called within the same session. /// </summary> Task<bool> WriteStreamAsync(Project project, string name, Stream stream, CancellationToken cancellationToken = default); /// <summary> /// Returns <see langword="true"/> if the data was successfully persisted to the storage subsystem. Subsequent /// calls to read the same keys should succeed if called within the same session. /// </summary> Task<bool> WriteStreamAsync(Document document, string name, Stream stream, CancellationToken cancellationToken = default); } }
// 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. using System; using System.IO; using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.Host { /// <remarks> /// Instances of <see cref="IPersistentStorage"/> support both synchronous and asynchronous disposal. Asynchronous /// disposal should always be preferred as the implementation of synchronous disposal may end up blocking the caller /// on async work. /// </remarks> public interface IPersistentStorage : IDisposable, IAsyncDisposable { Task<Stream?> ReadStreamAsync(string name, CancellationToken cancellationToken = default); Task<Stream?> ReadStreamAsync(Project project, string name, CancellationToken cancellationToken = default); Task<Stream?> ReadStreamAsync(Document document, string name, CancellationToken cancellationToken = default); /// <summary> /// Returns <see langword="true"/> if the data was successfully persisted to the storage subsystem. Subsequent /// calls to read the same keys should succeed if called within the same session. /// </summary> Task<bool> WriteStreamAsync(string name, Stream stream, CancellationToken cancellationToken = default); /// <summary> /// Returns <see langword="true"/> if the data was successfully persisted to the storage subsystem. Subsequent /// calls to read the same keys should succeed if called within the same session. /// </summary> Task<bool> WriteStreamAsync(Project project, string name, Stream stream, CancellationToken cancellationToken = default); /// <summary> /// Returns <see langword="true"/> if the data was successfully persisted to the storage subsystem. Subsequent /// calls to read the same keys should succeed if called within the same session. /// </summary> Task<bool> WriteStreamAsync(Document document, string name, Stream stream, CancellationToken cancellationToken = default); } }
-1
dotnet/roslyn
56,015
Remove obsolete APIs
Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
tmat
"2021-08-30T20:53:26Z"
"2021-09-02T16:56:01Z"
bdf1025480ad91f8db054959553257746f58f527
e782ce78f087060a3bc51737d3f07a6d102fb7b1
Remove obsolete APIs. Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
./src/EditorFeatures/VisualBasicTest/EndConstructGeneration/XmlLiteralTests.vb
' 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.EndConstructGeneration <[UseExportProvider]> Public Class XmlLiteralTests <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlStartElement() VerifyXmlElementEndConstructApplied( before:="Class C1 Sub M1() Dim x = <xml> End Sub End Class", beforeCaret:={2, -1}, after:="Class C1 Sub M1() Dim x = <xml></xml> End Sub End Class", afterCaret:={2, 21}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlStartElementSplitAcrossLines() VerifyXmlElementEndConstructApplied( before:="Class C1 Sub M1() Dim x = <xml > End Sub End Class", beforeCaret:={3, -1}, after:="Class C1 Sub M1() Dim x = <xml ></xml> End Sub End Class", afterCaret:={3, 21}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlStartElementWithNamespace() VerifyXmlElementEndConstructApplied( before:="Class C1 Sub M1() Dim x = <a:b> End Sub End Class", beforeCaret:={2, -1}, after:="Class C1 Sub M1() Dim x = <a:b></a:b> End Sub End Class", afterCaret:={2, 21}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub DontApplyInParameterDeclaration1() VerifyXmlElementEndConstructNotApplied( text:="Class C1 Sub M1(<xml>) End Sub End Class", caret:={1, 16}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub DontApplyInParameterDeclaration2() VerifyXmlElementEndConstructNotApplied( text:="Class C1 Sub M1(i As Integer, <xml>) End Sub End Class", caret:={2, 16}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub DontApplyAfterXmlStartElementWithEndElement() VerifyXmlElementEndConstructNotApplied( text:="Class C1 Sub M1() Dim x = <xml></xml> End Sub End Class", caret:={2, 23}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub DontApplyAfterXmlEndElement() VerifyXmlElementEndConstructNotApplied( text:="Class C1 Sub M1() Dim x = </xml> End Sub End Class", caret:={2, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub DontApplyAfterSingleXmlTag() VerifyXmlElementEndConstructNotApplied( text:="Class C1 Sub M1() Dim x = <xml/> End Sub End Class", caret:={2, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub DontApplyAfterProcessingInstruction() VerifyXmlElementEndConstructNotApplied( text:="Class C1 Sub M1() Dim x = <?xml version=""1.0""?> End Sub End Class", caret:={2, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlStartElementWhenPassedAsParameter1() VerifyXmlElementEndConstructApplied( before:="Class C1 Sub M1() M2(<xml> End Sub End Class", beforeCaret:={2, -1}, after:="Class C1 Sub M1() M2(<xml></xml> End Sub End Class", afterCaret:={2, 16}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlStartElementWhenPassedAsParameter2() VerifyXmlElementEndConstructApplied( before:="Class C1 Sub M1() M2(<xml>) End Sub End Class", beforeCaret:={2, 16}, after:="Class C1 Sub M1() M2(<xml></xml>) End Sub End Class", afterCaret:={2, 16}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlComment() VerifyXmlCommentEndConstructApplied( before:="Class C1 Sub M1() Dim x = <!-- End Sub End Class", beforeCaret:={2, -1}, after:="Class C1 Sub M1() Dim x = <!----> End Sub End Class", afterCaret:={2, 20}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlCommentWhenPassedAsParameter1() VerifyXmlCommentEndConstructApplied( before:="Class C1 Sub M1() M2(<!-- End Sub End Class", beforeCaret:={2, -1}, after:="Class C1 Sub M1() M2(<!----> End Sub End Class", afterCaret:={2, 15}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlCommentWhenPassedAsParameter2() VerifyXmlCommentEndConstructApplied( before:="Class C1 Sub M1() M2(<!--) End Sub End Class", beforeCaret:={2, 15}, after:="Class C1 Sub M1() M2(<!---->) End Sub End Class", afterCaret:={2, 15}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlCData() VerifyXmlCDataEndConstructApplied( before:="Class C1 Sub M1() Dim x = <![CDATA[ End Sub End Class", beforeCaret:={2, -1}, after:="Class C1 Sub M1() Dim x = <![CDATA[]]> End Sub End Class", afterCaret:={2, 25}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlCData2() VerifyXmlCDataEndConstructApplied( before:="Class C1 Sub M1() Dim x = <Code><![CDATA[</Code> End Sub End Class", beforeCaret:={2, 31}, after:="Class C1 Sub M1() Dim x = <Code><![CDATA[]]></Code> End Sub End Class", afterCaret:={2, 31}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlEmbeddedExpression1() VerifyXmlEmbeddedExpressionEndConstructApplied( before:="Class C1 Sub M1() Dim x = <%= End Sub End Class", beforeCaret:={2, -1}, after:="Class C1 Sub M1() Dim x = <%= %> End Sub End Class", afterCaret:={2, 20}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlEmbeddedExpression2() VerifyXmlEmbeddedExpressionEndConstructApplied( before:="Class C1 Sub M1() Dim x = <a><%= End Sub End Class", beforeCaret:={2, -1}, after:="Class C1 Sub M1() Dim x = <a><%= %> End Sub End Class", afterCaret:={2, 23}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlEmbeddedExpression3() VerifyXmlEmbeddedExpressionEndConstructApplied( before:="Class C1 Sub M1() Dim x = <a><%=</a> End Sub End Class", beforeCaret:={2, 22}, after:="Class C1 Sub M1() Dim x = <a><%= %></a> End Sub End Class", afterCaret:={2, 23}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlProcessingInstruction() VerifyXmlProcessingInstructionEndConstructApplied( before:="Class C1 Sub M1() Dim x = <? End Sub End Class", beforeCaret:={2, -1}, after:="Class C1 Sub M1() Dim x = <??> End Sub End Class", afterCaret:={2, 18}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlProcessingInstructionWhenPassedAsParameter1() VerifyXmlProcessingInstructionEndConstructApplied( before:="Class C1 Sub M1() M2(<? End Sub End Class", beforeCaret:={2, -1}, after:="Class C1 Sub M1() M2(<??> End Sub End Class", afterCaret:={2, 13}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlProcessingInstructionWhenPassedAsParameter2() VerifyXmlProcessingInstructionEndConstructApplied( before:="Class C1 Sub M1() M2(<?) End Sub End Class", beforeCaret:={2, 13}, after:="Class C1 Sub M1() M2(<??>) End Sub End Class", afterCaret:={2, 13}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestInsertBlankLineWhenPressingEnterInEmptyXmlTag() VerifyStatementEndConstructApplied( before:="Class C1 Sub M1() Dim x = <goo></goo> End Sub End Class", beforeCaret:={2, 21}, after:="Class C1 Sub M1() Dim x = <goo> </goo> End Sub End Class", afterCaret:={3, -1}) End Sub End Class End Namespace
' 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.EndConstructGeneration <[UseExportProvider]> Public Class XmlLiteralTests <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlStartElement() VerifyXmlElementEndConstructApplied( before:="Class C1 Sub M1() Dim x = <xml> End Sub End Class", beforeCaret:={2, -1}, after:="Class C1 Sub M1() Dim x = <xml></xml> End Sub End Class", afterCaret:={2, 21}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlStartElementSplitAcrossLines() VerifyXmlElementEndConstructApplied( before:="Class C1 Sub M1() Dim x = <xml > End Sub End Class", beforeCaret:={3, -1}, after:="Class C1 Sub M1() Dim x = <xml ></xml> End Sub End Class", afterCaret:={3, 21}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlStartElementWithNamespace() VerifyXmlElementEndConstructApplied( before:="Class C1 Sub M1() Dim x = <a:b> End Sub End Class", beforeCaret:={2, -1}, after:="Class C1 Sub M1() Dim x = <a:b></a:b> End Sub End Class", afterCaret:={2, 21}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub DontApplyInParameterDeclaration1() VerifyXmlElementEndConstructNotApplied( text:="Class C1 Sub M1(<xml>) End Sub End Class", caret:={1, 16}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub DontApplyInParameterDeclaration2() VerifyXmlElementEndConstructNotApplied( text:="Class C1 Sub M1(i As Integer, <xml>) End Sub End Class", caret:={2, 16}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub DontApplyAfterXmlStartElementWithEndElement() VerifyXmlElementEndConstructNotApplied( text:="Class C1 Sub M1() Dim x = <xml></xml> End Sub End Class", caret:={2, 23}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub DontApplyAfterXmlEndElement() VerifyXmlElementEndConstructNotApplied( text:="Class C1 Sub M1() Dim x = </xml> End Sub End Class", caret:={2, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub DontApplyAfterSingleXmlTag() VerifyXmlElementEndConstructNotApplied( text:="Class C1 Sub M1() Dim x = <xml/> End Sub End Class", caret:={2, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub DontApplyAfterProcessingInstruction() VerifyXmlElementEndConstructNotApplied( text:="Class C1 Sub M1() Dim x = <?xml version=""1.0""?> End Sub End Class", caret:={2, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlStartElementWhenPassedAsParameter1() VerifyXmlElementEndConstructApplied( before:="Class C1 Sub M1() M2(<xml> End Sub End Class", beforeCaret:={2, -1}, after:="Class C1 Sub M1() M2(<xml></xml> End Sub End Class", afterCaret:={2, 16}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlStartElementWhenPassedAsParameter2() VerifyXmlElementEndConstructApplied( before:="Class C1 Sub M1() M2(<xml>) End Sub End Class", beforeCaret:={2, 16}, after:="Class C1 Sub M1() M2(<xml></xml>) End Sub End Class", afterCaret:={2, 16}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlComment() VerifyXmlCommentEndConstructApplied( before:="Class C1 Sub M1() Dim x = <!-- End Sub End Class", beforeCaret:={2, -1}, after:="Class C1 Sub M1() Dim x = <!----> End Sub End Class", afterCaret:={2, 20}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlCommentWhenPassedAsParameter1() VerifyXmlCommentEndConstructApplied( before:="Class C1 Sub M1() M2(<!-- End Sub End Class", beforeCaret:={2, -1}, after:="Class C1 Sub M1() M2(<!----> End Sub End Class", afterCaret:={2, 15}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlCommentWhenPassedAsParameter2() VerifyXmlCommentEndConstructApplied( before:="Class C1 Sub M1() M2(<!--) End Sub End Class", beforeCaret:={2, 15}, after:="Class C1 Sub M1() M2(<!---->) End Sub End Class", afterCaret:={2, 15}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlCData() VerifyXmlCDataEndConstructApplied( before:="Class C1 Sub M1() Dim x = <![CDATA[ End Sub End Class", beforeCaret:={2, -1}, after:="Class C1 Sub M1() Dim x = <![CDATA[]]> End Sub End Class", afterCaret:={2, 25}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlCData2() VerifyXmlCDataEndConstructApplied( before:="Class C1 Sub M1() Dim x = <Code><![CDATA[</Code> End Sub End Class", beforeCaret:={2, 31}, after:="Class C1 Sub M1() Dim x = <Code><![CDATA[]]></Code> End Sub End Class", afterCaret:={2, 31}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlEmbeddedExpression1() VerifyXmlEmbeddedExpressionEndConstructApplied( before:="Class C1 Sub M1() Dim x = <%= End Sub End Class", beforeCaret:={2, -1}, after:="Class C1 Sub M1() Dim x = <%= %> End Sub End Class", afterCaret:={2, 20}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlEmbeddedExpression2() VerifyXmlEmbeddedExpressionEndConstructApplied( before:="Class C1 Sub M1() Dim x = <a><%= End Sub End Class", beforeCaret:={2, -1}, after:="Class C1 Sub M1() Dim x = <a><%= %> End Sub End Class", afterCaret:={2, 23}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlEmbeddedExpression3() VerifyXmlEmbeddedExpressionEndConstructApplied( before:="Class C1 Sub M1() Dim x = <a><%=</a> End Sub End Class", beforeCaret:={2, 22}, after:="Class C1 Sub M1() Dim x = <a><%= %></a> End Sub End Class", afterCaret:={2, 23}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlProcessingInstruction() VerifyXmlProcessingInstructionEndConstructApplied( before:="Class C1 Sub M1() Dim x = <? End Sub End Class", beforeCaret:={2, -1}, after:="Class C1 Sub M1() Dim x = <??> End Sub End Class", afterCaret:={2, 18}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlProcessingInstructionWhenPassedAsParameter1() VerifyXmlProcessingInstructionEndConstructApplied( before:="Class C1 Sub M1() M2(<? End Sub End Class", beforeCaret:={2, -1}, after:="Class C1 Sub M1() M2(<??> End Sub End Class", afterCaret:={2, 13}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlProcessingInstructionWhenPassedAsParameter2() VerifyXmlProcessingInstructionEndConstructApplied( before:="Class C1 Sub M1() M2(<?) End Sub End Class", beforeCaret:={2, 13}, after:="Class C1 Sub M1() M2(<??>) End Sub End Class", afterCaret:={2, 13}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestInsertBlankLineWhenPressingEnterInEmptyXmlTag() VerifyStatementEndConstructApplied( before:="Class C1 Sub M1() Dim x = <goo></goo> End Sub End Class", beforeCaret:={2, 21}, after:="Class C1 Sub M1() Dim x = <goo> </goo> End Sub End Class", afterCaret:={3, -1}) End Sub End Class End Namespace
-1
dotnet/roslyn
56,015
Remove obsolete APIs
Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
tmat
"2021-08-30T20:53:26Z"
"2021-09-02T16:56:01Z"
bdf1025480ad91f8db054959553257746f58f527
e782ce78f087060a3bc51737d3f07a6d102fb7b1
Remove obsolete APIs. Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
./src/VisualStudio/Core/Def/Implementation/TableDataSource/DiagnosticTableControlEventProcessorProvider.cs
// 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. #nullable disable using System; using System.ComponentModel.Composition; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Shell.TableControl; using Microsoft.VisualStudio.Shell.TableManager; using Microsoft.VisualStudio.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.TableDataSource { [Export(typeof(ITableControlEventProcessorProvider))] [DataSourceType(StandardTableDataSources.ErrorTableDataSource)] [DataSource(VisualStudioDiagnosticListTableWorkspaceEventListener.IdentifierString)] [Name(Name)] [Order(Before = "default")] internal partial class DiagnosticTableControlEventProcessorProvider : AbstractTableControlEventProcessorProvider<DiagnosticTableItem> { internal const string Name = "C#/VB Diagnostic Table Event Processor"; private readonly VisualStudioDiagnosticListSuppressionStateService _suppressionStateService; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public DiagnosticTableControlEventProcessorProvider( IVisualStudioDiagnosticListSuppressionStateService suppressionStateService) { _suppressionStateService = (VisualStudioDiagnosticListSuppressionStateService)suppressionStateService; } protected override EventProcessor CreateEventProcessor() { var suppressionStateEventProcessor = new SuppressionStateEventProcessor(_suppressionStateService); return new AggregateDiagnosticTableControlEventProcessor(additionalEventProcessors: suppressionStateEventProcessor); } } }
// 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. #nullable disable using System; using System.ComponentModel.Composition; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Shell.TableControl; using Microsoft.VisualStudio.Shell.TableManager; using Microsoft.VisualStudio.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.TableDataSource { [Export(typeof(ITableControlEventProcessorProvider))] [DataSourceType(StandardTableDataSources.ErrorTableDataSource)] [DataSource(VisualStudioDiagnosticListTableWorkspaceEventListener.IdentifierString)] [Name(Name)] [Order(Before = "default")] internal partial class DiagnosticTableControlEventProcessorProvider : AbstractTableControlEventProcessorProvider<DiagnosticTableItem> { internal const string Name = "C#/VB Diagnostic Table Event Processor"; private readonly VisualStudioDiagnosticListSuppressionStateService _suppressionStateService; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public DiagnosticTableControlEventProcessorProvider( IVisualStudioDiagnosticListSuppressionStateService suppressionStateService) { _suppressionStateService = (VisualStudioDiagnosticListSuppressionStateService)suppressionStateService; } protected override EventProcessor CreateEventProcessor() { var suppressionStateEventProcessor = new SuppressionStateEventProcessor(_suppressionStateService); return new AggregateDiagnosticTableControlEventProcessor(additionalEventProcessors: suppressionStateEventProcessor); } } }
-1
dotnet/roslyn
56,015
Remove obsolete APIs
Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
tmat
"2021-08-30T20:53:26Z"
"2021-09-02T16:56:01Z"
bdf1025480ad91f8db054959553257746f58f527
e782ce78f087060a3bc51737d3f07a6d102fb7b1
Remove obsolete APIs. Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
./src/Compilers/VisualBasic/Test/Syntax/Scanner/ScanErrorTests.vb
' 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.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests ' this place is dedicated to scan related error tests Public Class ScanErrorTests #Region "Targeted Error Tests - please arrange tests in the order of error code" <WorkItem(897923, "DevDiv/Personal")> <Fact> Public Sub BC31170ERR_IllegalXmlNameChar() Dim nameText = "Nc#" & ChrW(7) & "Name" Dim fullText = "<" & nameText & "/>" Dim t = DirectCast(SyntaxFactory.ParseExpression(fullText), XmlEmptyElementSyntax) Assert.Equal(fullText, t.ToFullString()) Assert.Equal(True, t.ContainsDiagnostics) Assert.Equal(3, t.GetSyntaxErrorsNoTree.Count) Assert.Equal(31170, t.GetSyntaxErrorsNoTree(2).Code) End Sub #End Region #Region "Mixed Error Tests" <WorkItem(881821, "DevDiv/Personal")> <Fact> Public Sub BC30004ERR_IllegalCharConstant_ScanTwoCharLiteralFollowedByQuote1() ParseAndVerify(<![CDATA[ " "C " ]]>, <errors> <error id="30648"/> <error id="30004"/> </errors>) End Sub #End Region End Class End Namespace
' 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.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests ' this place is dedicated to scan related error tests Public Class ScanErrorTests #Region "Targeted Error Tests - please arrange tests in the order of error code" <WorkItem(897923, "DevDiv/Personal")> <Fact> Public Sub BC31170ERR_IllegalXmlNameChar() Dim nameText = "Nc#" & ChrW(7) & "Name" Dim fullText = "<" & nameText & "/>" Dim t = DirectCast(SyntaxFactory.ParseExpression(fullText), XmlEmptyElementSyntax) Assert.Equal(fullText, t.ToFullString()) Assert.Equal(True, t.ContainsDiagnostics) Assert.Equal(3, t.GetSyntaxErrorsNoTree.Count) Assert.Equal(31170, t.GetSyntaxErrorsNoTree(2).Code) End Sub #End Region #Region "Mixed Error Tests" <WorkItem(881821, "DevDiv/Personal")> <Fact> Public Sub BC30004ERR_IllegalCharConstant_ScanTwoCharLiteralFollowedByQuote1() ParseAndVerify(<![CDATA[ " "C " ]]>, <errors> <error id="30648"/> <error id="30004"/> </errors>) End Sub #End Region End Class End Namespace
-1
dotnet/roslyn
56,015
Remove obsolete APIs
Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
tmat
"2021-08-30T20:53:26Z"
"2021-09-02T16:56:01Z"
bdf1025480ad91f8db054959553257746f58f527
e782ce78f087060a3bc51737d3f07a6d102fb7b1
Remove obsolete APIs. Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
./src/VisualStudio/Core/Test/CodeModel/AbstractFileCodeModelTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel Public MustInherit Class AbstractFileCodeModelTests Inherits AbstractCodeModelObjectTests(Of EnvDTE80.FileCodeModel2) Protected Async Function TestOperation(code As XElement, expectedCode As XElement, operation As Action(Of EnvDTE80.FileCodeModel2)) As Task WpfTestRunner.RequireWpfFact($"Test calls {NameOf(Me.TestOperation)} which means we're creating new {NameOf(EnvDTE.CodeModel)} elements.") Using state = CreateCodeModelTestState(GetWorkspaceDefinition(code)) Dim fileCodeModel = state.FileCodeModel Assert.NotNull(fileCodeModel) operation(fileCodeModel) Dim text = (Await state.GetDocumentAtCursor().GetTextAsync()).ToString() Assert.Equal(expectedCode.NormalizedValue.Trim(), text.Trim()) End Using Using state = CreateCodeModelTestState(GetWorkspaceDefinition(code)) Dim fileCodeModel = state.FileCodeModel Assert.NotNull(fileCodeModel) fileCodeModel.BeginBatch() operation(fileCodeModel) fileCodeModel.EndBatch() Dim text = (Await state.GetDocumentAtCursor().GetTextAsync()).ToString() Assert.Equal(expectedCode.NormalizedValue.Trim(), text.Trim()) End Using End Function Protected Sub TestOperation(code As XElement, operation As Action(Of EnvDTE80.FileCodeModel2)) Using state = CreateCodeModelTestState(GetWorkspaceDefinition(code)) Dim fileCodeModel = state.FileCodeModel Assert.NotNull(fileCodeModel) operation(fileCodeModel) End Using Using state = CreateCodeModelTestState(GetWorkspaceDefinition(code)) Dim fileCodeModel = state.FileCodeModel Assert.NotNull(fileCodeModel) fileCodeModel.BeginBatch() operation(fileCodeModel) fileCodeModel.EndBatch() End Using End Sub Protected Overrides Sub TestChildren(code As XElement, ParamArray expectedChildren() As Action(Of Object)) TestOperation(code, Sub(fileCodeModel) Dim children = fileCodeModel.CodeElements Assert.Equal(expectedChildren.Length, children.Count) For i = 1 To children.Count expectedChildren(i - 1)(children.Item(i)) Next End Sub) End Sub Protected Overrides Async Function TestAddAttribute(code As XElement, expectedCode As XElement, data As AttributeData) As Task Await TestOperation(code, expectedCode, Sub(fileCodeModel) Dim newAttribute = fileCodeModel.AddAttribute(data.Name, data.Value, data.Position) Assert.NotNull(newAttribute) Assert.Equal(data.Name, newAttribute.Name) End Sub) End Function Protected Overrides Async Function TestAddClass(code As XElement, expectedCode As XElement, data As ClassData) As Task Await TestOperation(code, expectedCode, Sub(fileCodeModel) Dim newClass = fileCodeModel.AddClass(data.Name, data.Position, data.Bases, data.ImplementedInterfaces, data.Access) Assert.NotNull(newClass) Assert.Equal(data.Name, newClass.Name) End Sub) End Function Protected Overrides Async Function TestAddDelegate(code As XElement, expectedCode As XElement, data As DelegateData) As Task Await TestOperation(code, expectedCode, Sub(fileCodeModel) Dim newDelegate = fileCodeModel.AddDelegate(data.Name, data.Type, data.Position, data.Access) Assert.NotNull(newDelegate) Assert.Equal(data.Name, newDelegate.Name) End Sub) End Function Protected Overrides Async Function TestAddEnum(code As XElement, expectedCode As XElement, data As EnumData) As Task Await TestOperation(code, expectedCode, Sub(fileCodeModel) Dim newEnum = fileCodeModel.AddEnum(data.Name, data.Position, data.Base, data.Access) Assert.NotNull(newEnum) Assert.Equal(data.Name, newEnum.Name) End Sub) End Function Protected Overrides Async Function TestAddFunction(code As XElement, expectedCode As XElement, data As FunctionData) As Task Await TestOperation(code, expectedCode, Sub(fileCodeModel) Assert.Throws(Of System.Runtime.InteropServices.COMException)( Sub() fileCodeModel.AddFunction(data.Name, data.Kind, data.Type, data.Position, data.Access) End Sub) End Sub) End Function Protected Overrides Async Function TestAddImport(code As XElement, expectedCode As XElement, data As ImportData) As Task Await TestOperation(code, expectedCode, Sub(fileCodeModel) Dim newImport = fileCodeModel.AddImport(data.Namespace, data.Position, data.Alias) Assert.NotNull(newImport) Assert.Equal(data.Namespace, newImport.Namespace) If data.Alias IsNot Nothing Then Assert.Equal(data.Alias, newImport.Alias) End If End Sub) End Function Protected Overrides Async Function TestAddInterface(code As XElement, expectedCode As XElement, data As InterfaceData) As Task Await TestOperation(code, expectedCode, Sub(fileCodeModel) Dim newInterface = fileCodeModel.AddInterface(data.Name, data.Position, data.Bases, data.Access) Assert.NotNull(newInterface) Assert.Equal(data.Name, newInterface.Name) End Sub) End Function Protected Overrides Async Function TestAddNamespace(code As XElement, expectedCode As XElement, data As NamespaceData) As Task Await TestOperation(code, expectedCode, Sub(fileCodeModel) Dim newNamespace = fileCodeModel.AddNamespace(data.Name, data.Position) Assert.NotNull(newNamespace) Assert.Equal(data.Name, newNamespace.Name) End Sub) End Function Protected Overrides Async Function TestAddStruct(code As XElement, expectedCode As XElement, data As StructData) As Task Await TestOperation(code, expectedCode, Sub(fileCodeModel) Dim newStruct = fileCodeModel.AddStruct(data.Name, data.Position, data.Bases, data.ImplementedInterfaces, data.Access) Assert.NotNull(newStruct) Assert.Equal(data.Name, newStruct.Name) End Sub) End Function Protected Overrides Async Function TestAddVariable(code As XElement, expectedCode As XElement, data As VariableData) As Task Await TestOperation(code, expectedCode, Sub(fileCodeModel) Assert.Throws(Of System.Runtime.InteropServices.COMException)( Sub() fileCodeModel.AddVariable(data.Name, data.Type, data.Position, data.Access) End Sub) End Sub) End Function Protected Overrides Async Function TestRemoveChild(code As XElement, expectedCode As XElement, element As Object) As Task Await TestOperation(code, expectedCode, Sub(fileCodeModel) fileCodeModel.Remove(element) End Sub) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel Public MustInherit Class AbstractFileCodeModelTests Inherits AbstractCodeModelObjectTests(Of EnvDTE80.FileCodeModel2) Protected Async Function TestOperation(code As XElement, expectedCode As XElement, operation As Action(Of EnvDTE80.FileCodeModel2)) As Task WpfTestRunner.RequireWpfFact($"Test calls {NameOf(Me.TestOperation)} which means we're creating new {NameOf(EnvDTE.CodeModel)} elements.") Using state = CreateCodeModelTestState(GetWorkspaceDefinition(code)) Dim fileCodeModel = state.FileCodeModel Assert.NotNull(fileCodeModel) operation(fileCodeModel) Dim text = (Await state.GetDocumentAtCursor().GetTextAsync()).ToString() Assert.Equal(expectedCode.NormalizedValue.Trim(), text.Trim()) End Using Using state = CreateCodeModelTestState(GetWorkspaceDefinition(code)) Dim fileCodeModel = state.FileCodeModel Assert.NotNull(fileCodeModel) fileCodeModel.BeginBatch() operation(fileCodeModel) fileCodeModel.EndBatch() Dim text = (Await state.GetDocumentAtCursor().GetTextAsync()).ToString() Assert.Equal(expectedCode.NormalizedValue.Trim(), text.Trim()) End Using End Function Protected Sub TestOperation(code As XElement, operation As Action(Of EnvDTE80.FileCodeModel2)) Using state = CreateCodeModelTestState(GetWorkspaceDefinition(code)) Dim fileCodeModel = state.FileCodeModel Assert.NotNull(fileCodeModel) operation(fileCodeModel) End Using Using state = CreateCodeModelTestState(GetWorkspaceDefinition(code)) Dim fileCodeModel = state.FileCodeModel Assert.NotNull(fileCodeModel) fileCodeModel.BeginBatch() operation(fileCodeModel) fileCodeModel.EndBatch() End Using End Sub Protected Overrides Sub TestChildren(code As XElement, ParamArray expectedChildren() As Action(Of Object)) TestOperation(code, Sub(fileCodeModel) Dim children = fileCodeModel.CodeElements Assert.Equal(expectedChildren.Length, children.Count) For i = 1 To children.Count expectedChildren(i - 1)(children.Item(i)) Next End Sub) End Sub Protected Overrides Async Function TestAddAttribute(code As XElement, expectedCode As XElement, data As AttributeData) As Task Await TestOperation(code, expectedCode, Sub(fileCodeModel) Dim newAttribute = fileCodeModel.AddAttribute(data.Name, data.Value, data.Position) Assert.NotNull(newAttribute) Assert.Equal(data.Name, newAttribute.Name) End Sub) End Function Protected Overrides Async Function TestAddClass(code As XElement, expectedCode As XElement, data As ClassData) As Task Await TestOperation(code, expectedCode, Sub(fileCodeModel) Dim newClass = fileCodeModel.AddClass(data.Name, data.Position, data.Bases, data.ImplementedInterfaces, data.Access) Assert.NotNull(newClass) Assert.Equal(data.Name, newClass.Name) End Sub) End Function Protected Overrides Async Function TestAddDelegate(code As XElement, expectedCode As XElement, data As DelegateData) As Task Await TestOperation(code, expectedCode, Sub(fileCodeModel) Dim newDelegate = fileCodeModel.AddDelegate(data.Name, data.Type, data.Position, data.Access) Assert.NotNull(newDelegate) Assert.Equal(data.Name, newDelegate.Name) End Sub) End Function Protected Overrides Async Function TestAddEnum(code As XElement, expectedCode As XElement, data As EnumData) As Task Await TestOperation(code, expectedCode, Sub(fileCodeModel) Dim newEnum = fileCodeModel.AddEnum(data.Name, data.Position, data.Base, data.Access) Assert.NotNull(newEnum) Assert.Equal(data.Name, newEnum.Name) End Sub) End Function Protected Overrides Async Function TestAddFunction(code As XElement, expectedCode As XElement, data As FunctionData) As Task Await TestOperation(code, expectedCode, Sub(fileCodeModel) Assert.Throws(Of System.Runtime.InteropServices.COMException)( Sub() fileCodeModel.AddFunction(data.Name, data.Kind, data.Type, data.Position, data.Access) End Sub) End Sub) End Function Protected Overrides Async Function TestAddImport(code As XElement, expectedCode As XElement, data As ImportData) As Task Await TestOperation(code, expectedCode, Sub(fileCodeModel) Dim newImport = fileCodeModel.AddImport(data.Namespace, data.Position, data.Alias) Assert.NotNull(newImport) Assert.Equal(data.Namespace, newImport.Namespace) If data.Alias IsNot Nothing Then Assert.Equal(data.Alias, newImport.Alias) End If End Sub) End Function Protected Overrides Async Function TestAddInterface(code As XElement, expectedCode As XElement, data As InterfaceData) As Task Await TestOperation(code, expectedCode, Sub(fileCodeModel) Dim newInterface = fileCodeModel.AddInterface(data.Name, data.Position, data.Bases, data.Access) Assert.NotNull(newInterface) Assert.Equal(data.Name, newInterface.Name) End Sub) End Function Protected Overrides Async Function TestAddNamespace(code As XElement, expectedCode As XElement, data As NamespaceData) As Task Await TestOperation(code, expectedCode, Sub(fileCodeModel) Dim newNamespace = fileCodeModel.AddNamespace(data.Name, data.Position) Assert.NotNull(newNamespace) Assert.Equal(data.Name, newNamespace.Name) End Sub) End Function Protected Overrides Async Function TestAddStruct(code As XElement, expectedCode As XElement, data As StructData) As Task Await TestOperation(code, expectedCode, Sub(fileCodeModel) Dim newStruct = fileCodeModel.AddStruct(data.Name, data.Position, data.Bases, data.ImplementedInterfaces, data.Access) Assert.NotNull(newStruct) Assert.Equal(data.Name, newStruct.Name) End Sub) End Function Protected Overrides Async Function TestAddVariable(code As XElement, expectedCode As XElement, data As VariableData) As Task Await TestOperation(code, expectedCode, Sub(fileCodeModel) Assert.Throws(Of System.Runtime.InteropServices.COMException)( Sub() fileCodeModel.AddVariable(data.Name, data.Type, data.Position, data.Access) End Sub) End Sub) End Function Protected Overrides Async Function TestRemoveChild(code As XElement, expectedCode As XElement, element As Object) As Task Await TestOperation(code, expectedCode, Sub(fileCodeModel) fileCodeModel.Remove(element) End Sub) End Function End Class End Namespace
-1
dotnet/roslyn
56,015
Remove obsolete APIs
Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
tmat
"2021-08-30T20:53:26Z"
"2021-09-02T16:56:01Z"
bdf1025480ad91f8db054959553257746f58f527
e782ce78f087060a3bc51737d3f07a6d102fb7b1
Remove obsolete APIs. Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
./src/Compilers/Core/Portable/Diagnostic/FileLinePositionSpan.cs
// 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. using System; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents a span of text in a source code file in terms of file name, line number, and offset within line. /// However, the file is actually whatever was passed in when asked to parse; there may not really be a file. /// </summary> public readonly struct FileLinePositionSpan : IEquatable<FileLinePositionSpan> { /// <summary> /// Path, or null if the span represents an invalid value. /// </summary> /// <remarks> /// Path may be <see cref="string.Empty"/> if not available. /// </remarks> public string Path { get; } /// <summary> /// True if the <see cref="Path"/> is a mapped path. /// </summary> /// <remarks> /// A mapped path is a path specified in source via <c>#line</c> (C#) or <c>#ExternalSource</c> (VB) directives. /// </remarks> public bool HasMappedPath { get; } /// <summary> /// Gets the span. /// </summary> public LinePositionSpan Span { get; } /// <summary> /// Initializes the <see cref="FileLinePositionSpan"/> instance. /// </summary> /// <param name="path">The file identifier - typically a relative or absolute path.</param> /// <param name="start">The start line position.</param> /// <param name="end">The end line position.</param> /// <exception cref="ArgumentNullException"><paramref name="path"/> is null.</exception> public FileLinePositionSpan(string path, LinePosition start, LinePosition end) : this(path, new LinePositionSpan(start, end)) { } /// <summary> /// Initializes the <see cref="FileLinePositionSpan"/> instance. /// </summary> /// <param name="path">The file identifier - typically a relative or absolute path.</param> /// <param name="span">The span.</param> /// <exception cref="ArgumentNullException"><paramref name="path"/> is null.</exception> public FileLinePositionSpan(string path, LinePositionSpan span) { Path = path ?? throw new ArgumentNullException(nameof(path)); Span = span; HasMappedPath = false; } internal FileLinePositionSpan(string path, LinePositionSpan span, bool hasMappedPath) { Path = path; Span = span; HasMappedPath = hasMappedPath; } /// <summary> /// Gets the <see cref="LinePosition"/> of the start of the span. /// </summary> /// <returns></returns> public LinePosition StartLinePosition => Span.Start; /// <summary> /// Gets the <see cref="LinePosition"/> of the end of the span. /// </summary> /// <returns></returns> public LinePosition EndLinePosition => Span.End; /// <summary> /// Returns true if the span represents a valid location. /// </summary> public bool IsValid => Path != null; // invalid span can be constructed by new FileLinePositionSpan() /// <summary> /// Determines if two FileLinePositionSpan objects are equal. /// </summary> /// <remarks> /// The path is treated as an opaque string, i.e. a case-sensitive comparison is used. /// </remarks> public bool Equals(FileLinePositionSpan other) => Span.Equals(other.Span) && HasMappedPath == other.HasMappedPath && string.Equals(Path, other.Path, StringComparison.Ordinal); /// <summary> /// Determines if two FileLinePositionSpan objects are equal. /// </summary> public override bool Equals(object? other) => other is FileLinePositionSpan span && Equals(span); /// <summary> /// Serves as a hash function for FileLinePositionSpan. /// </summary> /// <returns>The hash code.</returns> /// <remarks> /// The path is treated as an opaque string, i.e. a case-sensitive hash is calculated. /// </remarks> public override int GetHashCode() => Hash.Combine(Path, Hash.Combine(HasMappedPath, Span.GetHashCode())); /// <summary> /// Returns a <see cref="string"/> that represents <see cref="FileLinePositionSpan"/>. /// </summary> /// <returns>The string representation of <see cref="FileLinePositionSpan"/>.</returns> /// <example>Path: (0,0)-(5,6)</example> public override string ToString() => Path + ": " + Span; public static bool operator ==(FileLinePositionSpan left, FileLinePositionSpan right) => left.Equals(right); public static bool operator !=(FileLinePositionSpan left, FileLinePositionSpan right) => !(left == right); } }
// 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. using System; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents a span of text in a source code file in terms of file name, line number, and offset within line. /// However, the file is actually whatever was passed in when asked to parse; there may not really be a file. /// </summary> public readonly struct FileLinePositionSpan : IEquatable<FileLinePositionSpan> { /// <summary> /// Path, or null if the span represents an invalid value. /// </summary> /// <remarks> /// Path may be <see cref="string.Empty"/> if not available. /// </remarks> public string Path { get; } /// <summary> /// True if the <see cref="Path"/> is a mapped path. /// </summary> /// <remarks> /// A mapped path is a path specified in source via <c>#line</c> (C#) or <c>#ExternalSource</c> (VB) directives. /// </remarks> public bool HasMappedPath { get; } /// <summary> /// Gets the span. /// </summary> public LinePositionSpan Span { get; } /// <summary> /// Initializes the <see cref="FileLinePositionSpan"/> instance. /// </summary> /// <param name="path">The file identifier - typically a relative or absolute path.</param> /// <param name="start">The start line position.</param> /// <param name="end">The end line position.</param> /// <exception cref="ArgumentNullException"><paramref name="path"/> is null.</exception> public FileLinePositionSpan(string path, LinePosition start, LinePosition end) : this(path, new LinePositionSpan(start, end)) { } /// <summary> /// Initializes the <see cref="FileLinePositionSpan"/> instance. /// </summary> /// <param name="path">The file identifier - typically a relative or absolute path.</param> /// <param name="span">The span.</param> /// <exception cref="ArgumentNullException"><paramref name="path"/> is null.</exception> public FileLinePositionSpan(string path, LinePositionSpan span) { Path = path ?? throw new ArgumentNullException(nameof(path)); Span = span; HasMappedPath = false; } internal FileLinePositionSpan(string path, LinePositionSpan span, bool hasMappedPath) { Path = path; Span = span; HasMappedPath = hasMappedPath; } /// <summary> /// Gets the <see cref="LinePosition"/> of the start of the span. /// </summary> /// <returns></returns> public LinePosition StartLinePosition => Span.Start; /// <summary> /// Gets the <see cref="LinePosition"/> of the end of the span. /// </summary> /// <returns></returns> public LinePosition EndLinePosition => Span.End; /// <summary> /// Returns true if the span represents a valid location. /// </summary> public bool IsValid => Path != null; // invalid span can be constructed by new FileLinePositionSpan() /// <summary> /// Determines if two FileLinePositionSpan objects are equal. /// </summary> /// <remarks> /// The path is treated as an opaque string, i.e. a case-sensitive comparison is used. /// </remarks> public bool Equals(FileLinePositionSpan other) => Span.Equals(other.Span) && HasMappedPath == other.HasMappedPath && string.Equals(Path, other.Path, StringComparison.Ordinal); /// <summary> /// Determines if two FileLinePositionSpan objects are equal. /// </summary> public override bool Equals(object? other) => other is FileLinePositionSpan span && Equals(span); /// <summary> /// Serves as a hash function for FileLinePositionSpan. /// </summary> /// <returns>The hash code.</returns> /// <remarks> /// The path is treated as an opaque string, i.e. a case-sensitive hash is calculated. /// </remarks> public override int GetHashCode() => Hash.Combine(Path, Hash.Combine(HasMappedPath, Span.GetHashCode())); /// <summary> /// Returns a <see cref="string"/> that represents <see cref="FileLinePositionSpan"/>. /// </summary> /// <returns>The string representation of <see cref="FileLinePositionSpan"/>.</returns> /// <example>Path: (0,0)-(5,6)</example> public override string ToString() => Path + ": " + Span; public static bool operator ==(FileLinePositionSpan left, FileLinePositionSpan right) => left.Equals(right); public static bool operator !=(FileLinePositionSpan left, FileLinePositionSpan right) => !(left == right); } }
-1
dotnet/roslyn
56,015
Remove obsolete APIs
Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
tmat
"2021-08-30T20:53:26Z"
"2021-09-02T16:56:01Z"
bdf1025480ad91f8db054959553257746f58f527
e782ce78f087060a3bc51737d3f07a6d102fb7b1
Remove obsolete APIs. Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
./src/EditorFeatures/TestUtilities/Workspaces/NoCompilationDocumentDiagnosticAnalyzer.cs
// 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. #nullable disable using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.UnitTests; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces { [DiagnosticAnalyzer(NoCompilationConstants.LanguageName)] internal class NoCompilationDocumentDiagnosticAnalyzer : DocumentDiagnosticAnalyzer { public static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor( "NC0000", "No Compilation Syntax Error", "No Compilation Syntax Error", "Error", DiagnosticSeverity.Error, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override Task<ImmutableArray<Diagnostic>> AnalyzeSemanticsAsync(Document document, CancellationToken cancellationToken) => SpecializedTasks.EmptyImmutableArray<Diagnostic>(); public override Task<ImmutableArray<Diagnostic>> AnalyzeSyntaxAsync(Document document, CancellationToken cancellationToken) { return Task.FromResult(ImmutableArray.Create( Diagnostic.Create(Descriptor, Location.Create(document.FilePath, default, default)))); } } }
// 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. #nullable disable using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.UnitTests; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces { [DiagnosticAnalyzer(NoCompilationConstants.LanguageName)] internal class NoCompilationDocumentDiagnosticAnalyzer : DocumentDiagnosticAnalyzer { public static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor( "NC0000", "No Compilation Syntax Error", "No Compilation Syntax Error", "Error", DiagnosticSeverity.Error, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override Task<ImmutableArray<Diagnostic>> AnalyzeSemanticsAsync(Document document, CancellationToken cancellationToken) => SpecializedTasks.EmptyImmutableArray<Diagnostic>(); public override Task<ImmutableArray<Diagnostic>> AnalyzeSyntaxAsync(Document document, CancellationToken cancellationToken) { return Task.FromResult(ImmutableArray.Create( Diagnostic.Create(Descriptor, Location.Create(document.FilePath, default, default)))); } } }
-1
dotnet/roslyn
56,015
Remove obsolete APIs
Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
tmat
"2021-08-30T20:53:26Z"
"2021-09-02T16:56:01Z"
bdf1025480ad91f8db054959553257746f58f527
e782ce78f087060a3bc51737d3f07a6d102fb7b1
Remove obsolete APIs. Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
./src/Features/Core/Portable/CodeLens/CodeLensReferencesService.cs
// 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. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Globalization; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CodeLens { internal sealed class CodeLensReferencesService : ICodeLensReferencesService { private static readonly SymbolDisplayFormat MethodDisplayFormat = new(typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, memberOptions: SymbolDisplayMemberOptions.IncludeContainingType); /// <summary> /// Set ourselves as an implicit invocation of FindReferences. This will cause the finding operation to operate /// in serial, not parallel. We're running ephemerally in the BG and do not want to saturate the system with /// work that then slows the user down. Also, only process the inheritance hierarchy unidirectionally. We want /// to find references that could actually call into a particular, not references to other members that could /// never actually call into this member. /// </summary> private static readonly FindReferencesSearchOptions s_nonParallelSearch = FindReferencesSearchOptions.Default.With( @explicit: false, unidirectionalHierarchyCascade: true); private static async Task<T?> FindAsync<T>(Solution solution, DocumentId documentId, SyntaxNode syntaxNode, Func<CodeLensFindReferencesProgress, Task<T>> onResults, Func<CodeLensFindReferencesProgress, Task<T>> onCapped, int searchCap, CancellationToken cancellationToken) where T : struct { var document = solution.GetDocument(documentId); if (document == null) { return null; } var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); var symbol = semanticModel.GetDeclaredSymbol(syntaxNode, cancellationToken); if (symbol == null) { return null; } using var progress = new CodeLensFindReferencesProgress(symbol, syntaxNode, searchCap, cancellationToken); try { await SymbolFinder.FindReferencesAsync( symbol, solution, progress, documents: null, s_nonParallelSearch, progress.CancellationToken).ConfigureAwait(false); return await onResults(progress).ConfigureAwait(false); } catch (OperationCanceledException) { if (onCapped != null && progress.SearchCapReached) { // search was cancelled, and it was cancelled by us because a cap was reached. return await onCapped(progress).ConfigureAwait(false); } // search was cancelled, but not because of cap. // this always throws. throw; } } public async ValueTask<VersionStamp> GetProjectCodeLensVersionAsync(Solution solution, ProjectId projectId, CancellationToken cancellationToken) { return await solution.GetRequiredProject(projectId).GetDependentVersionAsync(cancellationToken).ConfigureAwait(false); } public async Task<ReferenceCount?> GetReferenceCountAsync(Solution solution, DocumentId documentId, SyntaxNode syntaxNode, int maxSearchResults, CancellationToken cancellationToken) { var projectVersion = await GetProjectCodeLensVersionAsync(solution, documentId.ProjectId, cancellationToken).ConfigureAwait(false); return await FindAsync(solution, documentId, syntaxNode, progress => Task.FromResult(new ReferenceCount( progress.SearchCap > 0 ? Math.Min(progress.ReferencesCount, progress.SearchCap) : progress.ReferencesCount, progress.SearchCapReached, projectVersion.ToString())), progress => Task.FromResult(new ReferenceCount(progress.SearchCap, isCapped: true, projectVersion.ToString())), maxSearchResults, cancellationToken).ConfigureAwait(false); } private static async Task<ReferenceLocationDescriptor> GetDescriptorOfEnclosingSymbolAsync(Solution solution, Location location, CancellationToken cancellationToken) { var document = solution.GetDocument(location.SourceTree); if (document == null) { return null; } var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var langServices = document.GetLanguageService<ICodeLensDisplayInfoService>(); if (langServices == null) { throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Unsupported language '{0}'", semanticModel.Language), nameof(semanticModel)); } var position = location.SourceSpan.Start; var token = (await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false)).FindToken(position, true); var node = GetEnclosingCodeElementNode(document, token, langServices, cancellationToken); var longName = langServices.GetDisplayName(semanticModel, node); // get the full line of source text on the line that contains this position var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); // get the actual span of text for the line containing reference var textLine = text.Lines.GetLineFromPosition(position); // turn the span from document relative to line relative var spanStart = token.Span.Start - textLine.Span.Start; var line = textLine.ToString(); var beforeLine1 = textLine.LineNumber > 0 ? text.Lines[textLine.LineNumber - 1].ToString() : string.Empty; var beforeLine2 = textLine.LineNumber - 1 > 0 ? text.Lines[textLine.LineNumber - 2].ToString() : string.Empty; var afterLine1 = textLine.LineNumber < text.Lines.Count - 1 ? text.Lines[textLine.LineNumber + 1].ToString() : string.Empty; var afterLine2 = textLine.LineNumber + 1 < text.Lines.Count - 1 ? text.Lines[textLine.LineNumber + 2].ToString() : string.Empty; var referenceSpan = new TextSpan(spanStart, token.Span.Length); var symbol = semanticModel.GetDeclaredSymbol(node, cancellationToken); var glyph = symbol?.GetGlyph(); var startLinePosition = location.GetLineSpan().StartLinePosition; var documentId = solution.GetDocument(location.SourceTree)?.Id; return new ReferenceLocationDescriptor( longName, semanticModel.Language, glyph, token.Span.Start, token.Span.Length, startLinePosition.Line, startLinePosition.Character, documentId.ProjectId.Id, documentId.Id, document.FilePath, line.TrimEnd(), referenceSpan.Start, referenceSpan.Length, beforeLine1.TrimEnd(), beforeLine2.TrimEnd(), afterLine1.TrimEnd(), afterLine2.TrimEnd()); } private static SyntaxNode GetEnclosingCodeElementNode(Document document, SyntaxToken token, ICodeLensDisplayInfoService langServices, CancellationToken cancellationToken) { var syntaxFactsService = document.GetLanguageService<ISyntaxFactsService>(); var node = token.Parent; while (node != null) { cancellationToken.ThrowIfCancellationRequested(); if (syntaxFactsService.IsDocumentationComment(node)) { var structuredTriviaSyntax = (IStructuredTriviaSyntax)node; var parentTrivia = structuredTriviaSyntax.ParentTrivia; node = parentTrivia.Token.Parent; } else if (syntaxFactsService.IsDeclaration(node) || syntaxFactsService.IsUsingOrExternOrImport(node) || syntaxFactsService.IsGlobalAssemblyAttribute(node)) { break; } else { node = node.Parent; } } if (node == null) { node = token.Parent; } return langServices.GetDisplayNode(node); } public async Task<ImmutableArray<ReferenceLocationDescriptor>?> FindReferenceLocationsAsync(Solution solution, DocumentId documentId, SyntaxNode syntaxNode, CancellationToken cancellationToken) { return await FindAsync(solution, documentId, syntaxNode, async progress => { var referenceTasks = progress.Locations .Select(location => GetDescriptorOfEnclosingSymbolAsync(solution, location, cancellationToken)) .ToArray(); var result = await Task.WhenAll(referenceTasks).ConfigureAwait(false); return result.ToImmutableArray(); }, onCapped: null, searchCap: 0, cancellationToken: cancellationToken).ConfigureAwait(false); } private static ISymbol GetEnclosingMethod(SemanticModel semanticModel, Location location, CancellationToken cancellationToken) { var enclosingSymbol = semanticModel.GetEnclosingSymbol(location.SourceSpan.Start, cancellationToken); for (var current = enclosingSymbol; current != null; current = current.ContainingSymbol) { cancellationToken.ThrowIfCancellationRequested(); if (current.Kind != SymbolKind.Method) { continue; } var method = (IMethodSymbol)current; if (method.IsAccessor()) { return method.AssociatedSymbol; } if (method.MethodKind != MethodKind.AnonymousFunction) { return method; } } return null; } private static async Task<ReferenceMethodDescriptor> TryGetMethodDescriptorAsync(Location commonLocation, Solution solution, CancellationToken cancellationToken) { var document = solution.GetDocument(commonLocation.SourceTree); if (document == null) { return null; } var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var fullName = GetEnclosingMethod(semanticModel, commonLocation, cancellationToken)?.ToDisplayString(MethodDisplayFormat); return !string.IsNullOrEmpty(fullName) ? new ReferenceMethodDescriptor(fullName, document.FilePath, document.Project.OutputFilePath) : null; } public Task<ImmutableArray<ReferenceMethodDescriptor>?> FindReferenceMethodsAsync(Solution solution, DocumentId documentId, SyntaxNode syntaxNode, CancellationToken cancellationToken) { return FindAsync(solution, documentId, syntaxNode, async progress => { var descriptorTasks = progress.Locations .Select(location => TryGetMethodDescriptorAsync(location, solution, cancellationToken)) .ToArray(); var result = await Task.WhenAll(descriptorTasks).ConfigureAwait(false); return result.OfType<ReferenceMethodDescriptor>().ToImmutableArray(); }, onCapped: null, searchCap: 0, cancellationToken: cancellationToken); } public async Task<string> GetFullyQualifiedNameAsync(Solution solution, DocumentId documentId, SyntaxNode syntaxNode, CancellationToken cancellationToken) { var document = solution.GetDocument(syntaxNode.GetLocation().SourceTree); using (solution.Services.CacheService?.EnableCaching(document.Project.Id)) { var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var declaredSymbol = semanticModel.GetDeclaredSymbol(syntaxNode, cancellationToken); if (declaredSymbol == null) { return string.Empty; } var parts = declaredSymbol.ToDisplayParts(MethodDisplayFormat); var pool = PooledStringBuilder.GetInstance(); try { var actualBuilder = pool.Builder; var previousWasClass = false; for (var index = 0; index < parts.Length; index++) { var part = parts[index]; if (previousWasClass && part.Kind == SymbolDisplayPartKind.Punctuation && index < parts.Length - 1) { switch (parts[index + 1].Kind) { case SymbolDisplayPartKind.ClassName: case SymbolDisplayPartKind.RecordClassName: case SymbolDisplayPartKind.DelegateName: case SymbolDisplayPartKind.EnumName: case SymbolDisplayPartKind.ErrorTypeName: case SymbolDisplayPartKind.InterfaceName: case SymbolDisplayPartKind.StructName: case SymbolDisplayPartKind.RecordStructName: actualBuilder.Append('+'); break; default: actualBuilder.Append(part); break; } } else { actualBuilder.Append(part); } previousWasClass = part.Kind is SymbolDisplayPartKind.ClassName or SymbolDisplayPartKind.RecordClassName or SymbolDisplayPartKind.InterfaceName or SymbolDisplayPartKind.StructName or SymbolDisplayPartKind.RecordStructName; } return actualBuilder.ToString(); } finally { pool.Free(); } } } } }
// 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. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Globalization; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CodeLens { internal sealed class CodeLensReferencesService : ICodeLensReferencesService { private static readonly SymbolDisplayFormat MethodDisplayFormat = new(typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, memberOptions: SymbolDisplayMemberOptions.IncludeContainingType); /// <summary> /// Set ourselves as an implicit invocation of FindReferences. This will cause the finding operation to operate /// in serial, not parallel. We're running ephemerally in the BG and do not want to saturate the system with /// work that then slows the user down. Also, only process the inheritance hierarchy unidirectionally. We want /// to find references that could actually call into a particular, not references to other members that could /// never actually call into this member. /// </summary> private static readonly FindReferencesSearchOptions s_nonParallelSearch = FindReferencesSearchOptions.Default.With( @explicit: false, unidirectionalHierarchyCascade: true); private static async Task<T?> FindAsync<T>(Solution solution, DocumentId documentId, SyntaxNode syntaxNode, Func<CodeLensFindReferencesProgress, Task<T>> onResults, Func<CodeLensFindReferencesProgress, Task<T>> onCapped, int searchCap, CancellationToken cancellationToken) where T : struct { var document = solution.GetDocument(documentId); if (document == null) { return null; } var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); var symbol = semanticModel.GetDeclaredSymbol(syntaxNode, cancellationToken); if (symbol == null) { return null; } using var progress = new CodeLensFindReferencesProgress(symbol, syntaxNode, searchCap, cancellationToken); try { await SymbolFinder.FindReferencesAsync( symbol, solution, progress, documents: null, s_nonParallelSearch, progress.CancellationToken).ConfigureAwait(false); return await onResults(progress).ConfigureAwait(false); } catch (OperationCanceledException) { if (onCapped != null && progress.SearchCapReached) { // search was cancelled, and it was cancelled by us because a cap was reached. return await onCapped(progress).ConfigureAwait(false); } // search was cancelled, but not because of cap. // this always throws. throw; } } public async ValueTask<VersionStamp> GetProjectCodeLensVersionAsync(Solution solution, ProjectId projectId, CancellationToken cancellationToken) { return await solution.GetRequiredProject(projectId).GetDependentVersionAsync(cancellationToken).ConfigureAwait(false); } public async Task<ReferenceCount?> GetReferenceCountAsync(Solution solution, DocumentId documentId, SyntaxNode syntaxNode, int maxSearchResults, CancellationToken cancellationToken) { var projectVersion = await GetProjectCodeLensVersionAsync(solution, documentId.ProjectId, cancellationToken).ConfigureAwait(false); return await FindAsync(solution, documentId, syntaxNode, progress => Task.FromResult(new ReferenceCount( progress.SearchCap > 0 ? Math.Min(progress.ReferencesCount, progress.SearchCap) : progress.ReferencesCount, progress.SearchCapReached, projectVersion.ToString())), progress => Task.FromResult(new ReferenceCount(progress.SearchCap, isCapped: true, projectVersion.ToString())), maxSearchResults, cancellationToken).ConfigureAwait(false); } private static async Task<ReferenceLocationDescriptor> GetDescriptorOfEnclosingSymbolAsync(Solution solution, Location location, CancellationToken cancellationToken) { var document = solution.GetDocument(location.SourceTree); if (document == null) { return null; } var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var langServices = document.GetLanguageService<ICodeLensDisplayInfoService>(); if (langServices == null) { throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Unsupported language '{0}'", semanticModel.Language), nameof(semanticModel)); } var position = location.SourceSpan.Start; var token = (await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false)).FindToken(position, true); var node = GetEnclosingCodeElementNode(document, token, langServices, cancellationToken); var longName = langServices.GetDisplayName(semanticModel, node); // get the full line of source text on the line that contains this position var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); // get the actual span of text for the line containing reference var textLine = text.Lines.GetLineFromPosition(position); // turn the span from document relative to line relative var spanStart = token.Span.Start - textLine.Span.Start; var line = textLine.ToString(); var beforeLine1 = textLine.LineNumber > 0 ? text.Lines[textLine.LineNumber - 1].ToString() : string.Empty; var beforeLine2 = textLine.LineNumber - 1 > 0 ? text.Lines[textLine.LineNumber - 2].ToString() : string.Empty; var afterLine1 = textLine.LineNumber < text.Lines.Count - 1 ? text.Lines[textLine.LineNumber + 1].ToString() : string.Empty; var afterLine2 = textLine.LineNumber + 1 < text.Lines.Count - 1 ? text.Lines[textLine.LineNumber + 2].ToString() : string.Empty; var referenceSpan = new TextSpan(spanStart, token.Span.Length); var symbol = semanticModel.GetDeclaredSymbol(node, cancellationToken); var glyph = symbol?.GetGlyph(); var startLinePosition = location.GetLineSpan().StartLinePosition; var documentId = solution.GetDocument(location.SourceTree)?.Id; return new ReferenceLocationDescriptor( longName, semanticModel.Language, glyph, token.Span.Start, token.Span.Length, startLinePosition.Line, startLinePosition.Character, documentId.ProjectId.Id, documentId.Id, document.FilePath, line.TrimEnd(), referenceSpan.Start, referenceSpan.Length, beforeLine1.TrimEnd(), beforeLine2.TrimEnd(), afterLine1.TrimEnd(), afterLine2.TrimEnd()); } private static SyntaxNode GetEnclosingCodeElementNode(Document document, SyntaxToken token, ICodeLensDisplayInfoService langServices, CancellationToken cancellationToken) { var syntaxFactsService = document.GetLanguageService<ISyntaxFactsService>(); var node = token.Parent; while (node != null) { cancellationToken.ThrowIfCancellationRequested(); if (syntaxFactsService.IsDocumentationComment(node)) { var structuredTriviaSyntax = (IStructuredTriviaSyntax)node; var parentTrivia = structuredTriviaSyntax.ParentTrivia; node = parentTrivia.Token.Parent; } else if (syntaxFactsService.IsDeclaration(node) || syntaxFactsService.IsUsingOrExternOrImport(node) || syntaxFactsService.IsGlobalAssemblyAttribute(node)) { break; } else { node = node.Parent; } } if (node == null) { node = token.Parent; } return langServices.GetDisplayNode(node); } public async Task<ImmutableArray<ReferenceLocationDescriptor>?> FindReferenceLocationsAsync(Solution solution, DocumentId documentId, SyntaxNode syntaxNode, CancellationToken cancellationToken) { return await FindAsync(solution, documentId, syntaxNode, async progress => { var referenceTasks = progress.Locations .Select(location => GetDescriptorOfEnclosingSymbolAsync(solution, location, cancellationToken)) .ToArray(); var result = await Task.WhenAll(referenceTasks).ConfigureAwait(false); return result.ToImmutableArray(); }, onCapped: null, searchCap: 0, cancellationToken: cancellationToken).ConfigureAwait(false); } private static ISymbol GetEnclosingMethod(SemanticModel semanticModel, Location location, CancellationToken cancellationToken) { var enclosingSymbol = semanticModel.GetEnclosingSymbol(location.SourceSpan.Start, cancellationToken); for (var current = enclosingSymbol; current != null; current = current.ContainingSymbol) { cancellationToken.ThrowIfCancellationRequested(); if (current.Kind != SymbolKind.Method) { continue; } var method = (IMethodSymbol)current; if (method.IsAccessor()) { return method.AssociatedSymbol; } if (method.MethodKind != MethodKind.AnonymousFunction) { return method; } } return null; } private static async Task<ReferenceMethodDescriptor> TryGetMethodDescriptorAsync(Location commonLocation, Solution solution, CancellationToken cancellationToken) { var document = solution.GetDocument(commonLocation.SourceTree); if (document == null) { return null; } var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var fullName = GetEnclosingMethod(semanticModel, commonLocation, cancellationToken)?.ToDisplayString(MethodDisplayFormat); return !string.IsNullOrEmpty(fullName) ? new ReferenceMethodDescriptor(fullName, document.FilePath, document.Project.OutputFilePath) : null; } public Task<ImmutableArray<ReferenceMethodDescriptor>?> FindReferenceMethodsAsync(Solution solution, DocumentId documentId, SyntaxNode syntaxNode, CancellationToken cancellationToken) { return FindAsync(solution, documentId, syntaxNode, async progress => { var descriptorTasks = progress.Locations .Select(location => TryGetMethodDescriptorAsync(location, solution, cancellationToken)) .ToArray(); var result = await Task.WhenAll(descriptorTasks).ConfigureAwait(false); return result.OfType<ReferenceMethodDescriptor>().ToImmutableArray(); }, onCapped: null, searchCap: 0, cancellationToken: cancellationToken); } public async Task<string> GetFullyQualifiedNameAsync(Solution solution, DocumentId documentId, SyntaxNode syntaxNode, CancellationToken cancellationToken) { var document = solution.GetDocument(syntaxNode.GetLocation().SourceTree); using (solution.Services.CacheService?.EnableCaching(document.Project.Id)) { var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var declaredSymbol = semanticModel.GetDeclaredSymbol(syntaxNode, cancellationToken); if (declaredSymbol == null) { return string.Empty; } var parts = declaredSymbol.ToDisplayParts(MethodDisplayFormat); var pool = PooledStringBuilder.GetInstance(); try { var actualBuilder = pool.Builder; var previousWasClass = false; for (var index = 0; index < parts.Length; index++) { var part = parts[index]; if (previousWasClass && part.Kind == SymbolDisplayPartKind.Punctuation && index < parts.Length - 1) { switch (parts[index + 1].Kind) { case SymbolDisplayPartKind.ClassName: case SymbolDisplayPartKind.RecordClassName: case SymbolDisplayPartKind.DelegateName: case SymbolDisplayPartKind.EnumName: case SymbolDisplayPartKind.ErrorTypeName: case SymbolDisplayPartKind.InterfaceName: case SymbolDisplayPartKind.StructName: case SymbolDisplayPartKind.RecordStructName: actualBuilder.Append('+'); break; default: actualBuilder.Append(part); break; } } else { actualBuilder.Append(part); } previousWasClass = part.Kind is SymbolDisplayPartKind.ClassName or SymbolDisplayPartKind.RecordClassName or SymbolDisplayPartKind.InterfaceName or SymbolDisplayPartKind.StructName or SymbolDisplayPartKind.RecordStructName; } return actualBuilder.ToString(); } finally { pool.Free(); } } } } }
-1
dotnet/roslyn
56,015
Remove obsolete APIs
Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
tmat
"2021-08-30T20:53:26Z"
"2021-09-02T16:56:01Z"
bdf1025480ad91f8db054959553257746f58f527
e782ce78f087060a3bc51737d3f07a6d102fb7b1
Remove obsolete APIs. Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
./src/EditorFeatures/VisualBasicTest/Recommendations/Declarations/AsyncKeywordRecommenderTests.vb
' 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.Declarations Public Class AsyncKeywordRecommenderTests Inherits RecommenderTests <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub KeywordsAfterAsyncTest() VerifyRecommendationsAreExactly(<ClassDeclaration>Async |</ClassDeclaration>, "Friend", "Function", "Private", "Protected", "Protected Friend", "Public", "Sub") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotInMethodStatementTest() VerifyRecommendationsMissing(<MethodBody>|</MethodBody>, "Async") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub InMethodExpressionTest() VerifyRecommendationsContain(<MethodBody>Dim z = |</MethodBody>, "Async") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub FunctionDeclarationTest() VerifyRecommendationsContain(<ClassDeclaration>|</ClassDeclaration>, "Async") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AlreadyAsyncFunctionDeclarationTest() VerifyRecommendationsContain(<ClassDeclaration>| Async</ClassDeclaration>, "Async") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub SubDeclarationTest() VerifyRecommendationsContain(<ClassDeclaration>| Sub bar()</ClassDeclaration>, "Async") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub FunctionDeclarationInInterfaceTest() VerifyRecommendationsContain(<InterfaceDeclaration>|</InterfaceDeclaration>, "Async") End Sub <WorkItem(547254, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547254")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotAfterAsyncTest() VerifyRecommendationsMissing(<ClassDeclaration>Async |</ClassDeclaration>, "Async") End Sub <WorkItem(645060, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/645060")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotAfterConstInClassTest() VerifyRecommendationsMissing(<ClassDeclaration>Const |</ClassDeclaration>, "Async") End Sub <WorkItem(645060, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/645060")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotAfterConstInModuleTest() VerifyRecommendationsMissing(<ModuleDeclaration>Const |</ModuleDeclaration>, "Async") End Sub <WorkItem(645060, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/645060")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotAfterWithEventsInClassTest() VerifyRecommendationsMissing(<ClassDeclaration>WithEvents |</ClassDeclaration>, "Async") End Sub <WorkItem(645060, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/645060")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotAfterWithEventsInModuleTest() VerifyRecommendationsMissing(<ModuleDeclaration>WithEvents |</ModuleDeclaration>, "Async") End Sub <WorkItem(674791, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/674791")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotAfterHashTest() VerifyRecommendationsMissing(<File> Imports System #| Module Module1 End Module </File>, "Async") End Sub End Class End Namespace
' 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.Declarations Public Class AsyncKeywordRecommenderTests Inherits RecommenderTests <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub KeywordsAfterAsyncTest() VerifyRecommendationsAreExactly(<ClassDeclaration>Async |</ClassDeclaration>, "Friend", "Function", "Private", "Protected", "Protected Friend", "Public", "Sub") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotInMethodStatementTest() VerifyRecommendationsMissing(<MethodBody>|</MethodBody>, "Async") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub InMethodExpressionTest() VerifyRecommendationsContain(<MethodBody>Dim z = |</MethodBody>, "Async") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub FunctionDeclarationTest() VerifyRecommendationsContain(<ClassDeclaration>|</ClassDeclaration>, "Async") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AlreadyAsyncFunctionDeclarationTest() VerifyRecommendationsContain(<ClassDeclaration>| Async</ClassDeclaration>, "Async") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub SubDeclarationTest() VerifyRecommendationsContain(<ClassDeclaration>| Sub bar()</ClassDeclaration>, "Async") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub FunctionDeclarationInInterfaceTest() VerifyRecommendationsContain(<InterfaceDeclaration>|</InterfaceDeclaration>, "Async") End Sub <WorkItem(547254, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547254")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotAfterAsyncTest() VerifyRecommendationsMissing(<ClassDeclaration>Async |</ClassDeclaration>, "Async") End Sub <WorkItem(645060, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/645060")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotAfterConstInClassTest() VerifyRecommendationsMissing(<ClassDeclaration>Const |</ClassDeclaration>, "Async") End Sub <WorkItem(645060, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/645060")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotAfterConstInModuleTest() VerifyRecommendationsMissing(<ModuleDeclaration>Const |</ModuleDeclaration>, "Async") End Sub <WorkItem(645060, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/645060")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotAfterWithEventsInClassTest() VerifyRecommendationsMissing(<ClassDeclaration>WithEvents |</ClassDeclaration>, "Async") End Sub <WorkItem(645060, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/645060")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotAfterWithEventsInModuleTest() VerifyRecommendationsMissing(<ModuleDeclaration>WithEvents |</ModuleDeclaration>, "Async") End Sub <WorkItem(674791, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/674791")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotAfterHashTest() VerifyRecommendationsMissing(<File> Imports System #| Module Module1 End Module </File>, "Async") End Sub End Class End Namespace
-1
dotnet/roslyn
56,015
Remove obsolete APIs
Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
tmat
"2021-08-30T20:53:26Z"
"2021-09-02T16:56:01Z"
bdf1025480ad91f8db054959553257746f58f527
e782ce78f087060a3bc51737d3f07a6d102fb7b1
Remove obsolete APIs. Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Engine/AbstractTriviaDataFactory.cs
// 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. using System.Threading; using Microsoft.CodeAnalysis.Diagnostics; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Formatting { internal abstract partial class AbstractTriviaDataFactory { private const int SpaceCacheSize = 10; private const int LineBreakCacheSize = 5; private const int IndentationLevelCacheSize = 20; protected readonly TreeData TreeInfo; protected readonly AnalyzerConfigOptions Options; protected readonly bool UseTabs; protected readonly int TabSize; protected readonly int IndentationSize; private readonly Whitespace[] _spaces; private readonly Whitespace?[,] _whitespaces = new Whitespace[LineBreakCacheSize, IndentationLevelCacheSize]; protected AbstractTriviaDataFactory(TreeData treeInfo, AnalyzerConfigOptions options) { Contract.ThrowIfNull(treeInfo); Contract.ThrowIfNull(options); this.TreeInfo = treeInfo; this.Options = options; UseTabs = options.GetOption(FormattingOptions2.UseTabs); TabSize = options.GetOption(FormattingOptions2.TabSize); IndentationSize = options.GetOption(FormattingOptions2.IndentationSize); _spaces = new Whitespace[SpaceCacheSize]; for (var i = 0; i < SpaceCacheSize; i++) { _spaces[i] = new Whitespace(this.Options, space: i, elastic: false, language: treeInfo.Root.Language); } } protected TriviaData GetSpaceTriviaData(int space, bool elastic = false) { Contract.ThrowIfFalse(space >= 0); // if result has elastic trivia in them, never use cache if (elastic) { return new Whitespace(this.Options, space, elastic: true, language: this.TreeInfo.Root.Language); } if (space < SpaceCacheSize) { return _spaces[space]; } // create a new space return new Whitespace(this.Options, space, elastic: false, language: this.TreeInfo.Root.Language); } protected TriviaData GetWhitespaceTriviaData(int lineBreaks, int indentation, bool useTriviaAsItIs, bool elastic) { Contract.ThrowIfFalse(lineBreaks >= 0); Contract.ThrowIfFalse(indentation >= 0); // we can use cache // #1. if whitespace trivia don't have any elastic trivia and // #2. analysis (Item1) didn't find anything preventing us from using cache such as trailing whitespace before new line // #3. number of line breaks (Item2) are under cache capacity (line breaks) // #4. indentation (Item3) is aligned to indentation level var canUseCache = !elastic && useTriviaAsItIs && lineBreaks > 0 && lineBreaks <= LineBreakCacheSize && indentation % IndentationSize == 0; if (canUseCache) { var indentationLevel = indentation / IndentationSize; if (indentationLevel < IndentationLevelCacheSize) { var lineIndex = lineBreaks - 1; EnsureWhitespaceTriviaInfo(lineIndex, indentationLevel); return _whitespaces[lineIndex, indentationLevel]!; } } return useTriviaAsItIs ? new Whitespace(this.Options, lineBreaks, indentation, elastic, language: this.TreeInfo.Root.Language) : new ModifiedWhitespace(this.Options, lineBreaks, indentation, elastic, language: this.TreeInfo.Root.Language); } private void EnsureWhitespaceTriviaInfo(int lineIndex, int indentationLevel) { Contract.ThrowIfFalse(lineIndex >= 0 && lineIndex < LineBreakCacheSize); Contract.ThrowIfFalse(indentationLevel >= 0 && indentationLevel < _whitespaces.Length / _whitespaces.Rank); // set up caches if (_whitespaces[lineIndex, indentationLevel] == null) { var indentation = indentationLevel * IndentationSize; var triviaInfo = new Whitespace(this.Options, lineBreaks: lineIndex + 1, indentation: indentation, elastic: false, language: this.TreeInfo.Root.Language); Interlocked.CompareExchange(ref _whitespaces[lineIndex, indentationLevel], triviaInfo, null); } } public abstract TriviaData CreateLeadingTrivia(SyntaxToken token); public abstract TriviaData CreateTrailingTrivia(SyntaxToken token); public abstract TriviaData Create(SyntaxToken token1, SyntaxToken token2); } }
// 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. using System.Threading; using Microsoft.CodeAnalysis.Diagnostics; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Formatting { internal abstract partial class AbstractTriviaDataFactory { private const int SpaceCacheSize = 10; private const int LineBreakCacheSize = 5; private const int IndentationLevelCacheSize = 20; protected readonly TreeData TreeInfo; protected readonly AnalyzerConfigOptions Options; protected readonly bool UseTabs; protected readonly int TabSize; protected readonly int IndentationSize; private readonly Whitespace[] _spaces; private readonly Whitespace?[,] _whitespaces = new Whitespace[LineBreakCacheSize, IndentationLevelCacheSize]; protected AbstractTriviaDataFactory(TreeData treeInfo, AnalyzerConfigOptions options) { Contract.ThrowIfNull(treeInfo); Contract.ThrowIfNull(options); this.TreeInfo = treeInfo; this.Options = options; UseTabs = options.GetOption(FormattingOptions2.UseTabs); TabSize = options.GetOption(FormattingOptions2.TabSize); IndentationSize = options.GetOption(FormattingOptions2.IndentationSize); _spaces = new Whitespace[SpaceCacheSize]; for (var i = 0; i < SpaceCacheSize; i++) { _spaces[i] = new Whitespace(this.Options, space: i, elastic: false, language: treeInfo.Root.Language); } } protected TriviaData GetSpaceTriviaData(int space, bool elastic = false) { Contract.ThrowIfFalse(space >= 0); // if result has elastic trivia in them, never use cache if (elastic) { return new Whitespace(this.Options, space, elastic: true, language: this.TreeInfo.Root.Language); } if (space < SpaceCacheSize) { return _spaces[space]; } // create a new space return new Whitespace(this.Options, space, elastic: false, language: this.TreeInfo.Root.Language); } protected TriviaData GetWhitespaceTriviaData(int lineBreaks, int indentation, bool useTriviaAsItIs, bool elastic) { Contract.ThrowIfFalse(lineBreaks >= 0); Contract.ThrowIfFalse(indentation >= 0); // we can use cache // #1. if whitespace trivia don't have any elastic trivia and // #2. analysis (Item1) didn't find anything preventing us from using cache such as trailing whitespace before new line // #3. number of line breaks (Item2) are under cache capacity (line breaks) // #4. indentation (Item3) is aligned to indentation level var canUseCache = !elastic && useTriviaAsItIs && lineBreaks > 0 && lineBreaks <= LineBreakCacheSize && indentation % IndentationSize == 0; if (canUseCache) { var indentationLevel = indentation / IndentationSize; if (indentationLevel < IndentationLevelCacheSize) { var lineIndex = lineBreaks - 1; EnsureWhitespaceTriviaInfo(lineIndex, indentationLevel); return _whitespaces[lineIndex, indentationLevel]!; } } return useTriviaAsItIs ? new Whitespace(this.Options, lineBreaks, indentation, elastic, language: this.TreeInfo.Root.Language) : new ModifiedWhitespace(this.Options, lineBreaks, indentation, elastic, language: this.TreeInfo.Root.Language); } private void EnsureWhitespaceTriviaInfo(int lineIndex, int indentationLevel) { Contract.ThrowIfFalse(lineIndex >= 0 && lineIndex < LineBreakCacheSize); Contract.ThrowIfFalse(indentationLevel >= 0 && indentationLevel < _whitespaces.Length / _whitespaces.Rank); // set up caches if (_whitespaces[lineIndex, indentationLevel] == null) { var indentation = indentationLevel * IndentationSize; var triviaInfo = new Whitespace(this.Options, lineBreaks: lineIndex + 1, indentation: indentation, elastic: false, language: this.TreeInfo.Root.Language); Interlocked.CompareExchange(ref _whitespaces[lineIndex, indentationLevel], triviaInfo, null); } } public abstract TriviaData CreateLeadingTrivia(SyntaxToken token); public abstract TriviaData CreateTrailingTrivia(SyntaxToken token); public abstract TriviaData Create(SyntaxToken token1, SyntaxToken token2); } }
-1
dotnet/roslyn
56,015
Remove obsolete APIs
Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
tmat
"2021-08-30T20:53:26Z"
"2021-09-02T16:56:01Z"
bdf1025480ad91f8db054959553257746f58f527
e782ce78f087060a3bc51737d3f07a6d102fb7b1
Remove obsolete APIs. Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
./src/Workspaces/Core/Portable/CodeGeneration/ICodeGenerationService.cs
// 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. using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.CodeGeneration { internal interface ICodeGenerationService : ILanguageService { /// <summary> /// Returns a newly created event declaration node from the provided event. /// </summary> SyntaxNode CreateEventDeclaration(IEventSymbol @event, CodeGenerationDestination destination = CodeGenerationDestination.Unspecified, CodeGenerationOptions? options = null); /// <summary> /// Returns a newly created field declaration node from the provided field. /// </summary> SyntaxNode CreateFieldDeclaration(IFieldSymbol field, CodeGenerationDestination destination = CodeGenerationDestination.Unspecified, CodeGenerationOptions? options = null); /// <summary> /// Returns a newly created method declaration node from the provided method. /// </summary> SyntaxNode CreateMethodDeclaration(IMethodSymbol method, CodeGenerationDestination destination = CodeGenerationDestination.Unspecified, CodeGenerationOptions? options = null); /// <summary> /// Returns a newly created property declaration node from the provided property. /// </summary> SyntaxNode CreatePropertyDeclaration(IPropertySymbol property, CodeGenerationDestination destination = CodeGenerationDestination.Unspecified, CodeGenerationOptions? options = null); /// <summary> /// Returns a newly created named type declaration node from the provided named type. /// </summary> SyntaxNode CreateNamedTypeDeclaration(INamedTypeSymbol namedType, CodeGenerationDestination destination = CodeGenerationDestination.Unspecified, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default); /// <summary> /// Returns a newly created namespace declaration node from the provided namespace. /// </summary> SyntaxNode CreateNamespaceDeclaration(INamespaceSymbol @namespace, CodeGenerationDestination destination = CodeGenerationDestination.Unspecified, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default); /// <summary> /// Adds an event into destination. /// </summary> TDeclarationNode AddEvent<TDeclarationNode>(TDeclarationNode destination, IEventSymbol @event, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default) where TDeclarationNode : SyntaxNode; /// <summary> /// Adds a field into destination. /// </summary> TDeclarationNode AddField<TDeclarationNode>(TDeclarationNode destination, IFieldSymbol field, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default) where TDeclarationNode : SyntaxNode; /// <summary> /// Adds a method into destination. /// </summary> TDeclarationNode AddMethod<TDeclarationNode>(TDeclarationNode destination, IMethodSymbol method, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default) where TDeclarationNode : SyntaxNode; /// <summary> /// Adds a property into destination. /// </summary> TDeclarationNode AddProperty<TDeclarationNode>(TDeclarationNode destination, IPropertySymbol property, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default) where TDeclarationNode : SyntaxNode; /// <summary> /// Adds a named type into destination. /// </summary> TDeclarationNode AddNamedType<TDeclarationNode>(TDeclarationNode destination, INamedTypeSymbol namedType, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default) where TDeclarationNode : SyntaxNode; /// <summary> /// Adds a namespace into destination. /// </summary> TDeclarationNode AddNamespace<TDeclarationNode>(TDeclarationNode destination, INamespaceSymbol @namespace, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default) where TDeclarationNode : SyntaxNode; /// <summary> /// Adds members into destination. /// </summary> TDeclarationNode AddMembers<TDeclarationNode>(TDeclarationNode destination, IEnumerable<ISymbol> members, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default) where TDeclarationNode : SyntaxNode; /// <summary> /// Adds the parameters to destination. /// </summary> TDeclarationNode AddParameters<TDeclarationNode>(TDeclarationNode destination, IEnumerable<IParameterSymbol> parameters, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default) where TDeclarationNode : SyntaxNode; /// <summary> /// Adds the attributes to destination. /// </summary> TDeclarationNode AddAttributes<TDeclarationNode>(TDeclarationNode destination, IEnumerable<AttributeData> attributes, SyntaxToken? target = null, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default) where TDeclarationNode : SyntaxNode; /// <summary> /// Remove the given attribute from destination. /// </summary> TDeclarationNode RemoveAttribute<TDeclarationNode>(TDeclarationNode destination, SyntaxNode attributeToRemove, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default) where TDeclarationNode : SyntaxNode; /// <summary> /// Remove the given attribute from destination. /// </summary> TDeclarationNode RemoveAttribute<TDeclarationNode>(TDeclarationNode destination, AttributeData attributeToRemove, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default) where TDeclarationNode : SyntaxNode; /// <summary> /// Update the modifiers list for the given declaration node. /// </summary> TDeclarationNode UpdateDeclarationModifiers<TDeclarationNode>(TDeclarationNode declaration, IEnumerable<SyntaxToken> newModifiers, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default) where TDeclarationNode : SyntaxNode; /// <summary> /// Update the accessibility modifiers for the given declaration node, retaining the trivia of the existing modifiers. /// </summary> TDeclarationNode UpdateDeclarationAccessibility<TDeclarationNode>(TDeclarationNode declaration, Accessibility newAccessibility, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default) where TDeclarationNode : SyntaxNode; /// <summary> /// Update the type for the given declaration node. /// </summary> TDeclarationNode UpdateDeclarationType<TDeclarationNode>(TDeclarationNode declaration, ITypeSymbol newType, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default) where TDeclarationNode : SyntaxNode; /// <summary> /// Replace the existing members with the given newMembers for the given declaration node. /// </summary> TDeclarationNode UpdateDeclarationMembers<TDeclarationNode>(TDeclarationNode declaration, IList<ISymbol> newMembers, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default) where TDeclarationNode : SyntaxNode; /// <summary> /// Adds the statements to destination. /// </summary> TDeclarationNode AddStatements<TDeclarationNode>(TDeclarationNode destination, IEnumerable<SyntaxNode> statements, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default) where TDeclarationNode : SyntaxNode; /// <summary> /// Adds a field with the provided signature into destination. /// </summary> Task<Document> AddEventAsync(Solution solution, INamedTypeSymbol destination, IEventSymbol @event, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default); /// <summary> /// Adds a field with the provided signature into destination. /// </summary> Task<Document> AddFieldAsync(Solution solution, INamedTypeSymbol destination, IFieldSymbol field, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default); /// <summary> /// Adds a method with the provided signature into destination. /// </summary> Task<Document> AddMethodAsync(Solution solution, INamedTypeSymbol destination, IMethodSymbol method, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default); /// <summary> /// Adds a property with the provided signature into destination. /// </summary> Task<Document> AddPropertyAsync(Solution solution, INamedTypeSymbol destination, IPropertySymbol property, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default); /// <summary> /// Adds a named type into destination. /// </summary> Task<Document> AddNamedTypeAsync(Solution solution, INamedTypeSymbol destination, INamedTypeSymbol namedType, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default); /// <summary> /// Adds a named type into destination. /// </summary> Task<Document> AddNamedTypeAsync(Solution solution, INamespaceSymbol destination, INamedTypeSymbol namedType, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default); /// <summary> /// Adds a namespace into destination. /// </summary> Task<Document> AddNamespaceAsync(Solution solution, INamespaceSymbol destination, INamespaceSymbol @namespace, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default); /// <summary> /// Adds a namespace or type into destination. /// </summary> Task<Document> AddNamespaceOrTypeAsync(Solution solution, INamespaceSymbol destination, INamespaceOrTypeSymbol namespaceOrType, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default); /// <summary> /// Adds all the provided members into destination. /// </summary> Task<Document> AddMembersAsync(Solution solution, INamedTypeSymbol destination, IEnumerable<ISymbol> members, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default); /// <summary> /// <c>true</c> if destination is a location where other symbols can be added to. /// </summary> bool CanAddTo(ISymbol destination, Solution solution, CancellationToken cancellationToken = default); /// <summary> /// <c>true</c> if destination is a location where other symbols can be added to. /// </summary> bool CanAddTo(SyntaxNode destination, Solution solution, CancellationToken cancellationToken = default); /// <summary> /// Return the most relevant declaration to namespaceOrType, /// it will first search the context node contained within, /// then the declaration in the same file, then non auto-generated file, /// then all the potential location. Return null if no declaration. /// </summary> Task<SyntaxNode?> FindMostRelevantNameSpaceOrTypeDeclarationAsync(Solution solution, INamespaceOrTypeSymbol namespaceOrType, CodeGenerationOptions options, CancellationToken cancellationToken); } }
// 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. using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.CodeGeneration { internal interface ICodeGenerationService : ILanguageService { /// <summary> /// Returns a newly created event declaration node from the provided event. /// </summary> SyntaxNode CreateEventDeclaration(IEventSymbol @event, CodeGenerationDestination destination = CodeGenerationDestination.Unspecified, CodeGenerationOptions? options = null); /// <summary> /// Returns a newly created field declaration node from the provided field. /// </summary> SyntaxNode CreateFieldDeclaration(IFieldSymbol field, CodeGenerationDestination destination = CodeGenerationDestination.Unspecified, CodeGenerationOptions? options = null); /// <summary> /// Returns a newly created method declaration node from the provided method. /// </summary> SyntaxNode CreateMethodDeclaration(IMethodSymbol method, CodeGenerationDestination destination = CodeGenerationDestination.Unspecified, CodeGenerationOptions? options = null); /// <summary> /// Returns a newly created property declaration node from the provided property. /// </summary> SyntaxNode CreatePropertyDeclaration(IPropertySymbol property, CodeGenerationDestination destination = CodeGenerationDestination.Unspecified, CodeGenerationOptions? options = null); /// <summary> /// Returns a newly created named type declaration node from the provided named type. /// </summary> SyntaxNode CreateNamedTypeDeclaration(INamedTypeSymbol namedType, CodeGenerationDestination destination = CodeGenerationDestination.Unspecified, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default); /// <summary> /// Returns a newly created namespace declaration node from the provided namespace. /// </summary> SyntaxNode CreateNamespaceDeclaration(INamespaceSymbol @namespace, CodeGenerationDestination destination = CodeGenerationDestination.Unspecified, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default); /// <summary> /// Adds an event into destination. /// </summary> TDeclarationNode AddEvent<TDeclarationNode>(TDeclarationNode destination, IEventSymbol @event, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default) where TDeclarationNode : SyntaxNode; /// <summary> /// Adds a field into destination. /// </summary> TDeclarationNode AddField<TDeclarationNode>(TDeclarationNode destination, IFieldSymbol field, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default) where TDeclarationNode : SyntaxNode; /// <summary> /// Adds a method into destination. /// </summary> TDeclarationNode AddMethod<TDeclarationNode>(TDeclarationNode destination, IMethodSymbol method, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default) where TDeclarationNode : SyntaxNode; /// <summary> /// Adds a property into destination. /// </summary> TDeclarationNode AddProperty<TDeclarationNode>(TDeclarationNode destination, IPropertySymbol property, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default) where TDeclarationNode : SyntaxNode; /// <summary> /// Adds a named type into destination. /// </summary> TDeclarationNode AddNamedType<TDeclarationNode>(TDeclarationNode destination, INamedTypeSymbol namedType, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default) where TDeclarationNode : SyntaxNode; /// <summary> /// Adds a namespace into destination. /// </summary> TDeclarationNode AddNamespace<TDeclarationNode>(TDeclarationNode destination, INamespaceSymbol @namespace, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default) where TDeclarationNode : SyntaxNode; /// <summary> /// Adds members into destination. /// </summary> TDeclarationNode AddMembers<TDeclarationNode>(TDeclarationNode destination, IEnumerable<ISymbol> members, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default) where TDeclarationNode : SyntaxNode; /// <summary> /// Adds the parameters to destination. /// </summary> TDeclarationNode AddParameters<TDeclarationNode>(TDeclarationNode destination, IEnumerable<IParameterSymbol> parameters, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default) where TDeclarationNode : SyntaxNode; /// <summary> /// Adds the attributes to destination. /// </summary> TDeclarationNode AddAttributes<TDeclarationNode>(TDeclarationNode destination, IEnumerable<AttributeData> attributes, SyntaxToken? target = null, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default) where TDeclarationNode : SyntaxNode; /// <summary> /// Remove the given attribute from destination. /// </summary> TDeclarationNode RemoveAttribute<TDeclarationNode>(TDeclarationNode destination, SyntaxNode attributeToRemove, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default) where TDeclarationNode : SyntaxNode; /// <summary> /// Remove the given attribute from destination. /// </summary> TDeclarationNode RemoveAttribute<TDeclarationNode>(TDeclarationNode destination, AttributeData attributeToRemove, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default) where TDeclarationNode : SyntaxNode; /// <summary> /// Update the modifiers list for the given declaration node. /// </summary> TDeclarationNode UpdateDeclarationModifiers<TDeclarationNode>(TDeclarationNode declaration, IEnumerable<SyntaxToken> newModifiers, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default) where TDeclarationNode : SyntaxNode; /// <summary> /// Update the accessibility modifiers for the given declaration node, retaining the trivia of the existing modifiers. /// </summary> TDeclarationNode UpdateDeclarationAccessibility<TDeclarationNode>(TDeclarationNode declaration, Accessibility newAccessibility, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default) where TDeclarationNode : SyntaxNode; /// <summary> /// Update the type for the given declaration node. /// </summary> TDeclarationNode UpdateDeclarationType<TDeclarationNode>(TDeclarationNode declaration, ITypeSymbol newType, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default) where TDeclarationNode : SyntaxNode; /// <summary> /// Replace the existing members with the given newMembers for the given declaration node. /// </summary> TDeclarationNode UpdateDeclarationMembers<TDeclarationNode>(TDeclarationNode declaration, IList<ISymbol> newMembers, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default) where TDeclarationNode : SyntaxNode; /// <summary> /// Adds the statements to destination. /// </summary> TDeclarationNode AddStatements<TDeclarationNode>(TDeclarationNode destination, IEnumerable<SyntaxNode> statements, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default) where TDeclarationNode : SyntaxNode; /// <summary> /// Adds a field with the provided signature into destination. /// </summary> Task<Document> AddEventAsync(Solution solution, INamedTypeSymbol destination, IEventSymbol @event, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default); /// <summary> /// Adds a field with the provided signature into destination. /// </summary> Task<Document> AddFieldAsync(Solution solution, INamedTypeSymbol destination, IFieldSymbol field, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default); /// <summary> /// Adds a method with the provided signature into destination. /// </summary> Task<Document> AddMethodAsync(Solution solution, INamedTypeSymbol destination, IMethodSymbol method, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default); /// <summary> /// Adds a property with the provided signature into destination. /// </summary> Task<Document> AddPropertyAsync(Solution solution, INamedTypeSymbol destination, IPropertySymbol property, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default); /// <summary> /// Adds a named type into destination. /// </summary> Task<Document> AddNamedTypeAsync(Solution solution, INamedTypeSymbol destination, INamedTypeSymbol namedType, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default); /// <summary> /// Adds a named type into destination. /// </summary> Task<Document> AddNamedTypeAsync(Solution solution, INamespaceSymbol destination, INamedTypeSymbol namedType, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default); /// <summary> /// Adds a namespace into destination. /// </summary> Task<Document> AddNamespaceAsync(Solution solution, INamespaceSymbol destination, INamespaceSymbol @namespace, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default); /// <summary> /// Adds a namespace or type into destination. /// </summary> Task<Document> AddNamespaceOrTypeAsync(Solution solution, INamespaceSymbol destination, INamespaceOrTypeSymbol namespaceOrType, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default); /// <summary> /// Adds all the provided members into destination. /// </summary> Task<Document> AddMembersAsync(Solution solution, INamedTypeSymbol destination, IEnumerable<ISymbol> members, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default); /// <summary> /// <c>true</c> if destination is a location where other symbols can be added to. /// </summary> bool CanAddTo(ISymbol destination, Solution solution, CancellationToken cancellationToken = default); /// <summary> /// <c>true</c> if destination is a location where other symbols can be added to. /// </summary> bool CanAddTo(SyntaxNode destination, Solution solution, CancellationToken cancellationToken = default); /// <summary> /// Return the most relevant declaration to namespaceOrType, /// it will first search the context node contained within, /// then the declaration in the same file, then non auto-generated file, /// then all the potential location. Return null if no declaration. /// </summary> Task<SyntaxNode?> FindMostRelevantNameSpaceOrTypeDeclarationAsync(Solution solution, INamespaceOrTypeSymbol namespaceOrType, CodeGenerationOptions options, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
56,015
Remove obsolete APIs
Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
tmat
"2021-08-30T20:53:26Z"
"2021-09-02T16:56:01Z"
bdf1025480ad91f8db054959553257746f58f527
e782ce78f087060a3bc51737d3f07a6d102fb7b1
Remove obsolete APIs. Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
./src/Features/Core/Portable/EditAndContinue/SolutionUpdate.cs
// 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. using System; using System.Collections.Immutable; using Microsoft.CodeAnalysis.Emit; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; namespace Microsoft.CodeAnalysis.EditAndContinue { internal readonly struct SolutionUpdate { public readonly ManagedModuleUpdates ModuleUpdates; public readonly ImmutableArray<(Guid ModuleId, ImmutableArray<(ManagedModuleMethodId Method, NonRemappableRegion Region)>)> NonRemappableRegions; public readonly ImmutableArray<(ProjectId ProjectId, EmitBaseline Baseline)> EmitBaselines; public readonly ImmutableArray<(ProjectId ProjectId, ImmutableArray<Diagnostic> Diagnostics)> Diagnostics; public readonly ImmutableArray<(DocumentId DocumentId, ImmutableArray<RudeEditDiagnostic> Diagnostics)> DocumentsWithRudeEdits; public SolutionUpdate( ManagedModuleUpdates moduleUpdates, ImmutableArray<(Guid ModuleId, ImmutableArray<(ManagedModuleMethodId Method, NonRemappableRegion Region)>)> nonRemappableRegions, ImmutableArray<(ProjectId ProjectId, EmitBaseline Baseline)> emitBaselines, ImmutableArray<(ProjectId ProjectId, ImmutableArray<Diagnostic> Diagnostics)> diagnostics, ImmutableArray<(DocumentId DocumentId, ImmutableArray<RudeEditDiagnostic> Diagnostics)> documentsWithRudeEdits) { ModuleUpdates = moduleUpdates; NonRemappableRegions = nonRemappableRegions; EmitBaselines = emitBaselines; Diagnostics = diagnostics; DocumentsWithRudeEdits = documentsWithRudeEdits; } public static SolutionUpdate Blocked( ImmutableArray<(ProjectId, ImmutableArray<Diagnostic>)> diagnostics, ImmutableArray<(DocumentId, ImmutableArray<RudeEditDiagnostic>)> documentsWithRudeEdits) => new( new(ManagedModuleUpdateStatus.Blocked, ImmutableArray<ManagedModuleUpdate>.Empty), ImmutableArray<(Guid, ImmutableArray<(ManagedModuleMethodId, NonRemappableRegion)>)>.Empty, ImmutableArray<(ProjectId, EmitBaseline)>.Empty, diagnostics, documentsWithRudeEdits); } }
// 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. using System; using System.Collections.Immutable; using Microsoft.CodeAnalysis.Emit; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; namespace Microsoft.CodeAnalysis.EditAndContinue { internal readonly struct SolutionUpdate { public readonly ManagedModuleUpdates ModuleUpdates; public readonly ImmutableArray<(Guid ModuleId, ImmutableArray<(ManagedModuleMethodId Method, NonRemappableRegion Region)>)> NonRemappableRegions; public readonly ImmutableArray<(ProjectId ProjectId, EmitBaseline Baseline)> EmitBaselines; public readonly ImmutableArray<(ProjectId ProjectId, ImmutableArray<Diagnostic> Diagnostics)> Diagnostics; public readonly ImmutableArray<(DocumentId DocumentId, ImmutableArray<RudeEditDiagnostic> Diagnostics)> DocumentsWithRudeEdits; public SolutionUpdate( ManagedModuleUpdates moduleUpdates, ImmutableArray<(Guid ModuleId, ImmutableArray<(ManagedModuleMethodId Method, NonRemappableRegion Region)>)> nonRemappableRegions, ImmutableArray<(ProjectId ProjectId, EmitBaseline Baseline)> emitBaselines, ImmutableArray<(ProjectId ProjectId, ImmutableArray<Diagnostic> Diagnostics)> diagnostics, ImmutableArray<(DocumentId DocumentId, ImmutableArray<RudeEditDiagnostic> Diagnostics)> documentsWithRudeEdits) { ModuleUpdates = moduleUpdates; NonRemappableRegions = nonRemappableRegions; EmitBaselines = emitBaselines; Diagnostics = diagnostics; DocumentsWithRudeEdits = documentsWithRudeEdits; } public static SolutionUpdate Blocked( ImmutableArray<(ProjectId, ImmutableArray<Diagnostic>)> diagnostics, ImmutableArray<(DocumentId, ImmutableArray<RudeEditDiagnostic>)> documentsWithRudeEdits) => new( new(ManagedModuleUpdateStatus.Blocked, ImmutableArray<ManagedModuleUpdate>.Empty), ImmutableArray<(Guid, ImmutableArray<(ManagedModuleMethodId, NonRemappableRegion)>)>.Empty, ImmutableArray<(ProjectId, EmitBaseline)>.Empty, diagnostics, documentsWithRudeEdits); } }
-1
dotnet/roslyn
56,015
Remove obsolete APIs
Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
tmat
"2021-08-30T20:53:26Z"
"2021-09-02T16:56:01Z"
bdf1025480ad91f8db054959553257746f58f527
e782ce78f087060a3bc51737d3f07a6d102fb7b1
Remove obsolete APIs. Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
./src/EditorFeatures/Core/Implementation/IntelliSense/AsyncCompletion/CompletionSource.cs
// 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. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.QuickInfo; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Core.Imaging; using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Adornments; using Microsoft.VisualStudio.Text.Editor; using AsyncCompletionData = Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data; using RoslynCompletionItem = Microsoft.CodeAnalysis.Completion.CompletionItem; using VSCompletionItem = Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data.CompletionItem; using VSUtilities = Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.AsyncCompletion { internal sealed class CompletionSource : ForegroundThreadAffinitizedObject, IAsyncExpandingCompletionSource { internal const string RoslynItem = nameof(RoslynItem); internal const string TriggerLocation = nameof(TriggerLocation); internal const string ExpandedItemTriggerLocation = nameof(ExpandedItemTriggerLocation); internal const string CompletionListSpan = nameof(CompletionListSpan); internal const string InsertionText = nameof(InsertionText); internal const string HasSuggestionItemOptions = nameof(HasSuggestionItemOptions); internal const string Description = nameof(Description); internal const string PotentialCommitCharacters = nameof(PotentialCommitCharacters); internal const string ExcludedCommitCharacters = nameof(ExcludedCommitCharacters); internal const string NonBlockingCompletion = nameof(NonBlockingCompletion); internal const string TypeImportCompletionEnabled = nameof(TypeImportCompletionEnabled); internal const string TargetTypeFilterExperimentEnabled = nameof(TargetTypeFilterExperimentEnabled); private static readonly ImmutableArray<ImageElement> s_WarningImageAttributeImagesArray = ImmutableArray.Create(new ImageElement(Glyph.CompletionWarning.GetImageId(), EditorFeaturesResources.Warning_image_element)); private static readonly EditorOptionKey<bool> NonBlockingCompletionEditorOption = new(NonBlockingCompletion); // Use CWT to cache data needed to create VSCompletionItem, so the table would be cleared when Roslyn completion item cache is cleared. private static readonly ConditionalWeakTable<RoslynCompletionItem, StrongBox<VSCompletionItemData>> s_roslynItemToVsItemData = new(); private readonly ITextView _textView; private readonly bool _isDebuggerTextView; private readonly ImmutableHashSet<string> _roles; private readonly Lazy<IStreamingFindUsagesPresenter> _streamingPresenter; private readonly VSUtilities.IUIThreadOperationExecutor _operationExecutor; private readonly IAsynchronousOperationListener _asyncListener; private bool _snippetCompletionTriggeredIndirectly; internal CompletionSource( ITextView textView, Lazy<IStreamingFindUsagesPresenter> streamingPresenter, IThreadingContext threadingContext, VSUtilities.IUIThreadOperationExecutor operationExecutor, IAsynchronousOperationListener asyncListener) : base(threadingContext) { _textView = textView; _streamingPresenter = streamingPresenter; _operationExecutor = operationExecutor; _asyncListener = asyncListener; _isDebuggerTextView = textView is IDebuggerTextView; _roles = textView.Roles.ToImmutableHashSet(); } public AsyncCompletionData.CompletionStartData InitializeCompletion( AsyncCompletionData.CompletionTrigger trigger, SnapshotPoint triggerLocation, CancellationToken cancellationToken) { // We take sourceText from document to get a snapshot span. // We would like to be sure that nobody changes buffers at the same time. AssertIsForeground(); if (_textView.Selection.Mode == TextSelectionMode.Box) { // No completion with multiple selection return AsyncCompletionData.CompletionStartData.DoesNotParticipateInCompletion; } var document = triggerLocation.Snapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document == null) { return AsyncCompletionData.CompletionStartData.DoesNotParticipateInCompletion; } var service = document.GetLanguageService<CompletionService>(); if (service == null) { return AsyncCompletionData.CompletionStartData.DoesNotParticipateInCompletion; } // The Editor supports the option per textView. // There could be mixed desired behavior per textView and even per same completion session. // The right fix would be to send this information as a result of the method. // Then, the Editor would choose the right behavior for mixed cases. _textView.Options.GlobalOptions.SetOptionValue(NonBlockingCompletionEditorOption, !document.Project.Solution.Workspace.Options.GetOption(CompletionOptions.BlockForCompletionItems2, service.Language)); // In case of calls with multiple completion services for the same view (e.g. TypeScript and C#), those completion services must not be called simultaneously for the same session. // Therefore, in each completion session we use a list of commit character for a specific completion service and a specific content type. _textView.Properties[PotentialCommitCharacters] = service.GetRules().DefaultCommitCharacters; // Reset a flag which means a snippet triggered by ? + Tab. // Set it later if met the condition. _snippetCompletionTriggeredIndirectly = false; CheckForExperimentStatus(_textView, document); var sourceText = document.GetTextSynchronously(cancellationToken); return ShouldTriggerCompletion(trigger, triggerLocation, sourceText, document, service) ? new AsyncCompletionData.CompletionStartData( participation: AsyncCompletionData.CompletionParticipation.ProvidesItems, applicableToSpan: new SnapshotSpan( triggerLocation.Snapshot, service.GetDefaultCompletionListSpan(sourceText, triggerLocation.Position).ToSpan())) : AsyncCompletionData.CompletionStartData.DoesNotParticipateInCompletion; // For telemetry reporting purpose static void CheckForExperimentStatus(ITextView textView, Document document) { var options = document.Project.Solution.Options; textView.Properties[TargetTypeFilterExperimentEnabled] = options.GetOption(CompletionOptions.TargetTypedCompletionFilterFeatureFlag); var importCompletionOptionValue = options.GetOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, document.Project.Language); var importCompletionExperimentValue = options.GetOption(CompletionOptions.TypeImportCompletionFeatureFlag); var isTypeImportEnababled = importCompletionOptionValue == true || (importCompletionOptionValue == null && importCompletionExperimentValue); textView.Properties[TypeImportCompletionEnabled] = isTypeImportEnababled; } } private bool ShouldTriggerCompletion( AsyncCompletionData.CompletionTrigger trigger, SnapshotPoint triggerLocation, SourceText sourceText, Document document, CompletionService completionService) { // The trigger reason guarantees that user wants a completion. if (trigger.Reason == AsyncCompletionData.CompletionTriggerReason.Invoke || trigger.Reason == AsyncCompletionData.CompletionTriggerReason.InvokeAndCommitIfUnique) { return true; } // Enter does not trigger completion. if (trigger.Reason == AsyncCompletionData.CompletionTriggerReason.Insertion && trigger.Character == '\n') { return false; } //The user may be trying to invoke snippets through question-tab. // We may provide a completion after that. // Otherwise, tab should not be a completion trigger. if (trigger.Reason == AsyncCompletionData.CompletionTriggerReason.Insertion && trigger.Character == '\t') { return TryInvokeSnippetCompletion(completionService, document, sourceText, triggerLocation.Position); } var roslynTrigger = Helpers.GetRoslynTrigger(trigger, triggerLocation); // The completion service decides that user may want a completion. if (completionService.ShouldTriggerCompletion(document.Project, sourceText, triggerLocation.Position, roslynTrigger)) { return true; } return false; } private bool TryInvokeSnippetCompletion( CompletionService completionService, Document document, SourceText text, int caretPoint) { var rules = completionService.GetRules(); // Do not invoke snippet if the corresponding rule is not set in options. if (rules.SnippetsRule != SnippetsRule.IncludeAfterTypingIdentifierQuestionTab) { return false; } var syntaxFactsOpt = document.GetLanguageService<ISyntaxFactsService>(); // Snippets are included if the user types: <quesiton><tab> // If at least one condition for snippets do not hold, bail out. if (syntaxFactsOpt == null || caretPoint < 3 || text[caretPoint - 2] != '?' || !QuestionMarkIsPrecededByIdentifierAndWhitespace(text, caretPoint - 2, syntaxFactsOpt)) { return false; } // Because <question><tab> is actually a command to bring up snippets, // we delete the last <question> that was typed. var textChange = new TextChange(TextSpan.FromBounds(caretPoint - 2, caretPoint), string.Empty); document.Project.Solution.Workspace.ApplyTextChanges(document.Id, textChange, CancellationToken.None); _snippetCompletionTriggeredIndirectly = true; return true; } public Task<AsyncCompletionData.CompletionContext> GetCompletionContextAsync( IAsyncCompletionSession session, AsyncCompletionData.CompletionTrigger trigger, SnapshotPoint triggerLocation, SnapshotSpan applicableToSpan, CancellationToken cancellationToken) { if (session is null) throw new ArgumentNullException(nameof(session)); return GetCompletionContextWorkerAsync(session, trigger, triggerLocation, isExpanded: false, cancellationToken); } public async Task<AsyncCompletionData.CompletionContext> GetExpandedCompletionContextAsync( IAsyncCompletionSession session, AsyncCompletionData.CompletionExpander expander, AsyncCompletionData.CompletionTrigger intialTrigger, SnapshotSpan applicableToSpan, CancellationToken cancellationToken) { // We only want to provide expanded items for Roslyn's expander. if ((object)expander == FilterSet.Expander && session.Properties.TryGetProperty(ExpandedItemTriggerLocation, out SnapshotPoint initialTriggerLocation)) { return await GetCompletionContextWorkerAsync(session, intialTrigger, initialTriggerLocation, isExpanded: true, cancellationToken).ConfigureAwait(false); } return AsyncCompletionData.CompletionContext.Empty; } private async Task<AsyncCompletionData.CompletionContext> GetCompletionContextWorkerAsync( IAsyncCompletionSession session, AsyncCompletionData.CompletionTrigger trigger, SnapshotPoint triggerLocation, bool isExpanded, CancellationToken cancellationToken) { var document = triggerLocation.Snapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document == null) { return AsyncCompletionData.CompletionContext.Empty; } var completionService = document.GetRequiredLanguageService<CompletionService>(); var roslynTrigger = Helpers.GetRoslynTrigger(trigger, triggerLocation); if (_snippetCompletionTriggeredIndirectly) { roslynTrigger = new CompletionTrigger(CompletionTriggerKind.Snippets); } var documentOptions = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var options = documentOptions .WithChangedOption(CompletionServiceOptions.IsExpandedCompletion, isExpanded); if (_isDebuggerTextView) { options = options .WithChangedOption(CompletionControllerOptions.FilterOutOfScopeLocals, false) .WithChangedOption(CompletionControllerOptions.ShowXmlDocCommentCompletion, false); } var (completionList, expandItemsAvailable) = await completionService.GetCompletionsInternalAsync( document, triggerLocation, roslynTrigger, _roles, options, cancellationToken).ConfigureAwait(false); ImmutableArray<VSCompletionItem> items; AsyncCompletionData.SuggestionItemOptions? suggestionItemOptions; var filterSet = new FilterSet(); if (completionList == null) { items = ImmutableArray<VSCompletionItem>.Empty; suggestionItemOptions = null; } else { var itemsBuilder = new ArrayBuilder<VSCompletionItem>(completionList.Items.Length); foreach (var roslynItem in completionList.Items) { cancellationToken.ThrowIfCancellationRequested(); var item = Convert(document, roslynItem, filterSet, triggerLocation); itemsBuilder.Add(item); } items = itemsBuilder.ToImmutableAndFree(); suggestionItemOptions = completionList.SuggestionModeItem != null ? new AsyncCompletionData.SuggestionItemOptions( completionList.SuggestionModeItem.DisplayText, completionList.SuggestionModeItem.Properties.TryGetValue(Description, out var description) ? description : string.Empty) : null; // Store around the span this completion list applies to. We'll use this later // to pass this value in when we're committing a completion list item. // It's OK to overwrite this value when expanded items are requested. session.Properties[CompletionListSpan] = completionList.Span; // This is a code supporting original completion scenarios: // Controller.Session_ComputeModel: if completionList.SuggestionModeItem != null, then suggestionMode = true // If there are suggestionItemOptions, then later HandleNormalFiltering should set selection to SoftSelection. if (!session.Properties.TryGetProperty(HasSuggestionItemOptions, out bool hasSuggestionItemOptionsBefore) || !hasSuggestionItemOptionsBefore) { session.Properties[HasSuggestionItemOptions] = suggestionItemOptions != null; } var excludedCommitCharacters = GetExcludedCommitCharacters(completionList.Items); if (excludedCommitCharacters.Length > 0) { if (session.Properties.TryGetProperty(ExcludedCommitCharacters, out ImmutableArray<char> excludedCommitCharactersBefore)) { excludedCommitCharacters = excludedCommitCharacters.Union(excludedCommitCharactersBefore).ToImmutableArray(); } session.Properties[ExcludedCommitCharacters] = excludedCommitCharacters; } } // We need to remember the trigger location for when a completion service claims expanded items are available // since the initial trigger we are able to get from IAsyncCompletionSession might not be the same (e.g. in projection scenarios) // so when they are requested via expander later, we can retrieve it. // Technically we should save the trigger location for each individual service that made such claim, but in reality only Roslyn's // completion service uses expander, so we can get away with not making such distinction. if (!isExpanded && expandItemsAvailable) { session.Properties[ExpandedItemTriggerLocation] = triggerLocation; } // It's possible that some providers can provide expanded items, in which case we will need to show expander as unselected. return new AsyncCompletionData.CompletionContext( items, suggestionItemOptions, suggestionItemOptions == null ? AsyncCompletionData.InitialSelectionHint.RegularSelection : AsyncCompletionData.InitialSelectionHint.SoftSelection, filterSet.GetFilterStatesInSet(addUnselectedExpander: expandItemsAvailable)); } public async Task<object?> GetDescriptionAsync(IAsyncCompletionSession session, VSCompletionItem item, CancellationToken cancellationToken) { if (session is null) throw new ArgumentNullException(nameof(session)); if (item is null) throw new ArgumentNullException(nameof(item)); if (!item.Properties.TryGetProperty(RoslynItem, out RoslynCompletionItem roslynItem) || !item.Properties.TryGetProperty(TriggerLocation, out SnapshotPoint triggerLocation)) { return null; } var document = triggerLocation.Snapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document == null) return null; var service = document.GetLanguageService<CompletionService>(); if (service == null) return null; var description = await service.GetDescriptionAsync(document, roslynItem, cancellationToken).ConfigureAwait(false); var context = new IntellisenseQuickInfoBuilderContext( document, ThreadingContext, _operationExecutor, _asyncListener, _streamingPresenter); var elements = IntelliSense.Helpers.BuildInteractiveTextElements(description.TaggedParts, context).ToArray(); if (elements.Length == 0) { return new ClassifiedTextElement(); } else if (elements.Length == 1) { return elements[0]; } else { return new ContainerElement(ContainerElementStyle.Stacked | ContainerElementStyle.VerticalPadding, elements); } } /// <summary> /// We'd like to cache VS Completion item directly to avoid allocation completely. However it holds references /// to transient objects, which would cause memory leak (among other potential issues) if cached. /// So as a compromise, we cache data that can be calculated from Roslyn completion item to avoid repeated /// calculation cost for cached Roslyn completion items. /// </summary> private readonly struct VSCompletionItemData { public VSCompletionItemData( string displayText, ImageElement icon, ImmutableArray<AsyncCompletionData.CompletionFilter> filters, int filterSetData, ImmutableArray<ImageElement> attributeIcons, string insertionText) { DisplayText = displayText; Icon = icon; Filters = filters; FilterSetData = filterSetData; AttributeIcons = attributeIcons; InsertionText = insertionText; } public string DisplayText { get; } public ImageElement Icon { get; } public ImmutableArray<AsyncCompletionData.CompletionFilter> Filters { get; } /// <summary> /// This is the bit vector value from the FilterSet of this item. /// </summary> public int FilterSetData { get; } public ImmutableArray<ImageElement> AttributeIcons { get; } public string InsertionText { get; } } private VSCompletionItem Convert( Document document, RoslynCompletionItem roslynItem, FilterSet filterSet, SnapshotPoint initialTriggerLocation) { VSCompletionItemData itemData; if (roslynItem.Flags.IsCached() && s_roslynItemToVsItemData.TryGetValue(roslynItem, out var boxedItemData)) { itemData = boxedItemData.Value; filterSet.CombineData(itemData.FilterSetData); } else { var imageId = roslynItem.Tags.GetFirstGlyph().GetImageId(); var (filters, filterSetData) = filterSet.GetFiltersAndAddToSet(roslynItem); // roslynItem generated by providers can contain an insertionText in a property bag. // We will not use it but other providers may need it. // We actually will calculate the insertion text once again when called TryCommit. if (!roslynItem.Properties.TryGetValue(InsertionText, out var insertionText)) { insertionText = roslynItem.DisplayText; } var supportedPlatforms = SymbolCompletionItem.GetSupportedPlatforms(roslynItem, document.Project.Solution); var attributeImages = supportedPlatforms != null ? s_WarningImageAttributeImagesArray : ImmutableArray<ImageElement>.Empty; itemData = new VSCompletionItemData( displayText: roslynItem.GetEntireDisplayText(), icon: new ImageElement(new ImageId(imageId.Guid, imageId.Id), roslynItem.DisplayText), filters: filters, filterSetData: filterSetData, attributeIcons: attributeImages, insertionText: insertionText); // It doesn't make sense to cache VS item data for those Roslyn items created from scratch for each session, // since CWT uses object identity for comparison. if (roslynItem.Flags.IsCached()) { s_roslynItemToVsItemData.Add(roslynItem, new StrongBox<VSCompletionItemData>(itemData)); } } var item = new VSCompletionItem( displayText: itemData.DisplayText, source: this, icon: itemData.Icon, filters: itemData.Filters, suffix: roslynItem.InlineDescription, // InlineDescription will be right-aligned in the selection popup insertText: itemData.InsertionText, sortText: roslynItem.SortText, filterText: roslynItem.FilterText, automationText: roslynItem.AutomationText ?? roslynItem.DisplayText, attributeIcons: itemData.AttributeIcons); item.Properties.AddProperty(RoslynItem, roslynItem); item.Properties.AddProperty(TriggerLocation, initialTriggerLocation); return item; } private static ImmutableArray<char> GetExcludedCommitCharacters(ImmutableArray<RoslynCompletionItem> roslynItems) { var hashSet = new HashSet<char>(); foreach (var roslynItem in roslynItems) { foreach (var rule in roslynItem.Rules.FilterCharacterRules) { if (rule.Kind == CharacterSetModificationKind.Add) { foreach (var c in rule.Characters) { hashSet.Add(c); } } } } return hashSet.ToImmutableArray(); } internal static bool QuestionMarkIsPrecededByIdentifierAndWhitespace( SourceText text, int questionPosition, ISyntaxFactsService syntaxFacts) { var startOfLine = text.Lines.GetLineFromPosition(questionPosition).Start; // First, skip all the whitespace. var current = startOfLine; while (current < questionPosition && char.IsWhiteSpace(text[current])) { current++; } if (current < questionPosition && syntaxFacts.IsIdentifierStartCharacter(text[current])) { current++; } else { return false; } while (current < questionPosition && syntaxFacts.IsIdentifierPartCharacter(text[current])) { current++; } return current == questionPosition; } } }
// 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. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.QuickInfo; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Core.Imaging; using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Adornments; using Microsoft.VisualStudio.Text.Editor; using AsyncCompletionData = Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data; using RoslynCompletionItem = Microsoft.CodeAnalysis.Completion.CompletionItem; using VSCompletionItem = Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data.CompletionItem; using VSUtilities = Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.AsyncCompletion { internal sealed class CompletionSource : ForegroundThreadAffinitizedObject, IAsyncExpandingCompletionSource { internal const string RoslynItem = nameof(RoslynItem); internal const string TriggerLocation = nameof(TriggerLocation); internal const string ExpandedItemTriggerLocation = nameof(ExpandedItemTriggerLocation); internal const string CompletionListSpan = nameof(CompletionListSpan); internal const string InsertionText = nameof(InsertionText); internal const string HasSuggestionItemOptions = nameof(HasSuggestionItemOptions); internal const string Description = nameof(Description); internal const string PotentialCommitCharacters = nameof(PotentialCommitCharacters); internal const string ExcludedCommitCharacters = nameof(ExcludedCommitCharacters); internal const string NonBlockingCompletion = nameof(NonBlockingCompletion); internal const string TypeImportCompletionEnabled = nameof(TypeImportCompletionEnabled); internal const string TargetTypeFilterExperimentEnabled = nameof(TargetTypeFilterExperimentEnabled); private static readonly ImmutableArray<ImageElement> s_WarningImageAttributeImagesArray = ImmutableArray.Create(new ImageElement(Glyph.CompletionWarning.GetImageId(), EditorFeaturesResources.Warning_image_element)); private static readonly EditorOptionKey<bool> NonBlockingCompletionEditorOption = new(NonBlockingCompletion); // Use CWT to cache data needed to create VSCompletionItem, so the table would be cleared when Roslyn completion item cache is cleared. private static readonly ConditionalWeakTable<RoslynCompletionItem, StrongBox<VSCompletionItemData>> s_roslynItemToVsItemData = new(); private readonly ITextView _textView; private readonly bool _isDebuggerTextView; private readonly ImmutableHashSet<string> _roles; private readonly Lazy<IStreamingFindUsagesPresenter> _streamingPresenter; private readonly VSUtilities.IUIThreadOperationExecutor _operationExecutor; private readonly IAsynchronousOperationListener _asyncListener; private bool _snippetCompletionTriggeredIndirectly; internal CompletionSource( ITextView textView, Lazy<IStreamingFindUsagesPresenter> streamingPresenter, IThreadingContext threadingContext, VSUtilities.IUIThreadOperationExecutor operationExecutor, IAsynchronousOperationListener asyncListener) : base(threadingContext) { _textView = textView; _streamingPresenter = streamingPresenter; _operationExecutor = operationExecutor; _asyncListener = asyncListener; _isDebuggerTextView = textView is IDebuggerTextView; _roles = textView.Roles.ToImmutableHashSet(); } public AsyncCompletionData.CompletionStartData InitializeCompletion( AsyncCompletionData.CompletionTrigger trigger, SnapshotPoint triggerLocation, CancellationToken cancellationToken) { // We take sourceText from document to get a snapshot span. // We would like to be sure that nobody changes buffers at the same time. AssertIsForeground(); if (_textView.Selection.Mode == TextSelectionMode.Box) { // No completion with multiple selection return AsyncCompletionData.CompletionStartData.DoesNotParticipateInCompletion; } var document = triggerLocation.Snapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document == null) { return AsyncCompletionData.CompletionStartData.DoesNotParticipateInCompletion; } var service = document.GetLanguageService<CompletionService>(); if (service == null) { return AsyncCompletionData.CompletionStartData.DoesNotParticipateInCompletion; } // The Editor supports the option per textView. // There could be mixed desired behavior per textView and even per same completion session. // The right fix would be to send this information as a result of the method. // Then, the Editor would choose the right behavior for mixed cases. _textView.Options.GlobalOptions.SetOptionValue(NonBlockingCompletionEditorOption, !document.Project.Solution.Workspace.Options.GetOption(CompletionOptions.BlockForCompletionItems2, service.Language)); // In case of calls with multiple completion services for the same view (e.g. TypeScript and C#), those completion services must not be called simultaneously for the same session. // Therefore, in each completion session we use a list of commit character for a specific completion service and a specific content type. _textView.Properties[PotentialCommitCharacters] = service.GetRules().DefaultCommitCharacters; // Reset a flag which means a snippet triggered by ? + Tab. // Set it later if met the condition. _snippetCompletionTriggeredIndirectly = false; CheckForExperimentStatus(_textView, document); var sourceText = document.GetTextSynchronously(cancellationToken); return ShouldTriggerCompletion(trigger, triggerLocation, sourceText, document, service) ? new AsyncCompletionData.CompletionStartData( participation: AsyncCompletionData.CompletionParticipation.ProvidesItems, applicableToSpan: new SnapshotSpan( triggerLocation.Snapshot, service.GetDefaultCompletionListSpan(sourceText, triggerLocation.Position).ToSpan())) : AsyncCompletionData.CompletionStartData.DoesNotParticipateInCompletion; // For telemetry reporting purpose static void CheckForExperimentStatus(ITextView textView, Document document) { var options = document.Project.Solution.Options; textView.Properties[TargetTypeFilterExperimentEnabled] = options.GetOption(CompletionOptions.TargetTypedCompletionFilterFeatureFlag); var importCompletionOptionValue = options.GetOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, document.Project.Language); var importCompletionExperimentValue = options.GetOption(CompletionOptions.TypeImportCompletionFeatureFlag); var isTypeImportEnababled = importCompletionOptionValue == true || (importCompletionOptionValue == null && importCompletionExperimentValue); textView.Properties[TypeImportCompletionEnabled] = isTypeImportEnababled; } } private bool ShouldTriggerCompletion( AsyncCompletionData.CompletionTrigger trigger, SnapshotPoint triggerLocation, SourceText sourceText, Document document, CompletionService completionService) { // The trigger reason guarantees that user wants a completion. if (trigger.Reason == AsyncCompletionData.CompletionTriggerReason.Invoke || trigger.Reason == AsyncCompletionData.CompletionTriggerReason.InvokeAndCommitIfUnique) { return true; } // Enter does not trigger completion. if (trigger.Reason == AsyncCompletionData.CompletionTriggerReason.Insertion && trigger.Character == '\n') { return false; } //The user may be trying to invoke snippets through question-tab. // We may provide a completion after that. // Otherwise, tab should not be a completion trigger. if (trigger.Reason == AsyncCompletionData.CompletionTriggerReason.Insertion && trigger.Character == '\t') { return TryInvokeSnippetCompletion(completionService, document, sourceText, triggerLocation.Position); } var roslynTrigger = Helpers.GetRoslynTrigger(trigger, triggerLocation); // The completion service decides that user may want a completion. if (completionService.ShouldTriggerCompletion(document.Project, sourceText, triggerLocation.Position, roslynTrigger)) { return true; } return false; } private bool TryInvokeSnippetCompletion( CompletionService completionService, Document document, SourceText text, int caretPoint) { var rules = completionService.GetRules(); // Do not invoke snippet if the corresponding rule is not set in options. if (rules.SnippetsRule != SnippetsRule.IncludeAfterTypingIdentifierQuestionTab) { return false; } var syntaxFactsOpt = document.GetLanguageService<ISyntaxFactsService>(); // Snippets are included if the user types: <quesiton><tab> // If at least one condition for snippets do not hold, bail out. if (syntaxFactsOpt == null || caretPoint < 3 || text[caretPoint - 2] != '?' || !QuestionMarkIsPrecededByIdentifierAndWhitespace(text, caretPoint - 2, syntaxFactsOpt)) { return false; } // Because <question><tab> is actually a command to bring up snippets, // we delete the last <question> that was typed. var textChange = new TextChange(TextSpan.FromBounds(caretPoint - 2, caretPoint), string.Empty); document.Project.Solution.Workspace.ApplyTextChanges(document.Id, textChange, CancellationToken.None); _snippetCompletionTriggeredIndirectly = true; return true; } public Task<AsyncCompletionData.CompletionContext> GetCompletionContextAsync( IAsyncCompletionSession session, AsyncCompletionData.CompletionTrigger trigger, SnapshotPoint triggerLocation, SnapshotSpan applicableToSpan, CancellationToken cancellationToken) { if (session is null) throw new ArgumentNullException(nameof(session)); return GetCompletionContextWorkerAsync(session, trigger, triggerLocation, isExpanded: false, cancellationToken); } public async Task<AsyncCompletionData.CompletionContext> GetExpandedCompletionContextAsync( IAsyncCompletionSession session, AsyncCompletionData.CompletionExpander expander, AsyncCompletionData.CompletionTrigger intialTrigger, SnapshotSpan applicableToSpan, CancellationToken cancellationToken) { // We only want to provide expanded items for Roslyn's expander. if ((object)expander == FilterSet.Expander && session.Properties.TryGetProperty(ExpandedItemTriggerLocation, out SnapshotPoint initialTriggerLocation)) { return await GetCompletionContextWorkerAsync(session, intialTrigger, initialTriggerLocation, isExpanded: true, cancellationToken).ConfigureAwait(false); } return AsyncCompletionData.CompletionContext.Empty; } private async Task<AsyncCompletionData.CompletionContext> GetCompletionContextWorkerAsync( IAsyncCompletionSession session, AsyncCompletionData.CompletionTrigger trigger, SnapshotPoint triggerLocation, bool isExpanded, CancellationToken cancellationToken) { var document = triggerLocation.Snapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document == null) { return AsyncCompletionData.CompletionContext.Empty; } var completionService = document.GetRequiredLanguageService<CompletionService>(); var roslynTrigger = Helpers.GetRoslynTrigger(trigger, triggerLocation); if (_snippetCompletionTriggeredIndirectly) { roslynTrigger = new CompletionTrigger(CompletionTriggerKind.Snippets); } var documentOptions = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var options = documentOptions .WithChangedOption(CompletionServiceOptions.IsExpandedCompletion, isExpanded); if (_isDebuggerTextView) { options = options .WithChangedOption(CompletionControllerOptions.FilterOutOfScopeLocals, false) .WithChangedOption(CompletionControllerOptions.ShowXmlDocCommentCompletion, false); } var (completionList, expandItemsAvailable) = await completionService.GetCompletionsInternalAsync( document, triggerLocation, roslynTrigger, _roles, options, cancellationToken).ConfigureAwait(false); ImmutableArray<VSCompletionItem> items; AsyncCompletionData.SuggestionItemOptions? suggestionItemOptions; var filterSet = new FilterSet(); if (completionList == null) { items = ImmutableArray<VSCompletionItem>.Empty; suggestionItemOptions = null; } else { var itemsBuilder = new ArrayBuilder<VSCompletionItem>(completionList.Items.Length); foreach (var roslynItem in completionList.Items) { cancellationToken.ThrowIfCancellationRequested(); var item = Convert(document, roslynItem, filterSet, triggerLocation); itemsBuilder.Add(item); } items = itemsBuilder.ToImmutableAndFree(); suggestionItemOptions = completionList.SuggestionModeItem != null ? new AsyncCompletionData.SuggestionItemOptions( completionList.SuggestionModeItem.DisplayText, completionList.SuggestionModeItem.Properties.TryGetValue(Description, out var description) ? description : string.Empty) : null; // Store around the span this completion list applies to. We'll use this later // to pass this value in when we're committing a completion list item. // It's OK to overwrite this value when expanded items are requested. session.Properties[CompletionListSpan] = completionList.Span; // This is a code supporting original completion scenarios: // Controller.Session_ComputeModel: if completionList.SuggestionModeItem != null, then suggestionMode = true // If there are suggestionItemOptions, then later HandleNormalFiltering should set selection to SoftSelection. if (!session.Properties.TryGetProperty(HasSuggestionItemOptions, out bool hasSuggestionItemOptionsBefore) || !hasSuggestionItemOptionsBefore) { session.Properties[HasSuggestionItemOptions] = suggestionItemOptions != null; } var excludedCommitCharacters = GetExcludedCommitCharacters(completionList.Items); if (excludedCommitCharacters.Length > 0) { if (session.Properties.TryGetProperty(ExcludedCommitCharacters, out ImmutableArray<char> excludedCommitCharactersBefore)) { excludedCommitCharacters = excludedCommitCharacters.Union(excludedCommitCharactersBefore).ToImmutableArray(); } session.Properties[ExcludedCommitCharacters] = excludedCommitCharacters; } } // We need to remember the trigger location for when a completion service claims expanded items are available // since the initial trigger we are able to get from IAsyncCompletionSession might not be the same (e.g. in projection scenarios) // so when they are requested via expander later, we can retrieve it. // Technically we should save the trigger location for each individual service that made such claim, but in reality only Roslyn's // completion service uses expander, so we can get away with not making such distinction. if (!isExpanded && expandItemsAvailable) { session.Properties[ExpandedItemTriggerLocation] = triggerLocation; } // It's possible that some providers can provide expanded items, in which case we will need to show expander as unselected. return new AsyncCompletionData.CompletionContext( items, suggestionItemOptions, suggestionItemOptions == null ? AsyncCompletionData.InitialSelectionHint.RegularSelection : AsyncCompletionData.InitialSelectionHint.SoftSelection, filterSet.GetFilterStatesInSet(addUnselectedExpander: expandItemsAvailable)); } public async Task<object?> GetDescriptionAsync(IAsyncCompletionSession session, VSCompletionItem item, CancellationToken cancellationToken) { if (session is null) throw new ArgumentNullException(nameof(session)); if (item is null) throw new ArgumentNullException(nameof(item)); if (!item.Properties.TryGetProperty(RoslynItem, out RoslynCompletionItem roslynItem) || !item.Properties.TryGetProperty(TriggerLocation, out SnapshotPoint triggerLocation)) { return null; } var document = triggerLocation.Snapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document == null) return null; var service = document.GetLanguageService<CompletionService>(); if (service == null) return null; var description = await service.GetDescriptionAsync(document, roslynItem, cancellationToken).ConfigureAwait(false); var context = new IntellisenseQuickInfoBuilderContext( document, ThreadingContext, _operationExecutor, _asyncListener, _streamingPresenter); var elements = IntelliSense.Helpers.BuildInteractiveTextElements(description.TaggedParts, context).ToArray(); if (elements.Length == 0) { return new ClassifiedTextElement(); } else if (elements.Length == 1) { return elements[0]; } else { return new ContainerElement(ContainerElementStyle.Stacked | ContainerElementStyle.VerticalPadding, elements); } } /// <summary> /// We'd like to cache VS Completion item directly to avoid allocation completely. However it holds references /// to transient objects, which would cause memory leak (among other potential issues) if cached. /// So as a compromise, we cache data that can be calculated from Roslyn completion item to avoid repeated /// calculation cost for cached Roslyn completion items. /// </summary> private readonly struct VSCompletionItemData { public VSCompletionItemData( string displayText, ImageElement icon, ImmutableArray<AsyncCompletionData.CompletionFilter> filters, int filterSetData, ImmutableArray<ImageElement> attributeIcons, string insertionText) { DisplayText = displayText; Icon = icon; Filters = filters; FilterSetData = filterSetData; AttributeIcons = attributeIcons; InsertionText = insertionText; } public string DisplayText { get; } public ImageElement Icon { get; } public ImmutableArray<AsyncCompletionData.CompletionFilter> Filters { get; } /// <summary> /// This is the bit vector value from the FilterSet of this item. /// </summary> public int FilterSetData { get; } public ImmutableArray<ImageElement> AttributeIcons { get; } public string InsertionText { get; } } private VSCompletionItem Convert( Document document, RoslynCompletionItem roslynItem, FilterSet filterSet, SnapshotPoint initialTriggerLocation) { VSCompletionItemData itemData; if (roslynItem.Flags.IsCached() && s_roslynItemToVsItemData.TryGetValue(roslynItem, out var boxedItemData)) { itemData = boxedItemData.Value; filterSet.CombineData(itemData.FilterSetData); } else { var imageId = roslynItem.Tags.GetFirstGlyph().GetImageId(); var (filters, filterSetData) = filterSet.GetFiltersAndAddToSet(roslynItem); // roslynItem generated by providers can contain an insertionText in a property bag. // We will not use it but other providers may need it. // We actually will calculate the insertion text once again when called TryCommit. if (!roslynItem.Properties.TryGetValue(InsertionText, out var insertionText)) { insertionText = roslynItem.DisplayText; } var supportedPlatforms = SymbolCompletionItem.GetSupportedPlatforms(roslynItem, document.Project.Solution); var attributeImages = supportedPlatforms != null ? s_WarningImageAttributeImagesArray : ImmutableArray<ImageElement>.Empty; itemData = new VSCompletionItemData( displayText: roslynItem.GetEntireDisplayText(), icon: new ImageElement(new ImageId(imageId.Guid, imageId.Id), roslynItem.DisplayText), filters: filters, filterSetData: filterSetData, attributeIcons: attributeImages, insertionText: insertionText); // It doesn't make sense to cache VS item data for those Roslyn items created from scratch for each session, // since CWT uses object identity for comparison. if (roslynItem.Flags.IsCached()) { s_roslynItemToVsItemData.Add(roslynItem, new StrongBox<VSCompletionItemData>(itemData)); } } var item = new VSCompletionItem( displayText: itemData.DisplayText, source: this, icon: itemData.Icon, filters: itemData.Filters, suffix: roslynItem.InlineDescription, // InlineDescription will be right-aligned in the selection popup insertText: itemData.InsertionText, sortText: roslynItem.SortText, filterText: roslynItem.FilterText, automationText: roslynItem.AutomationText ?? roslynItem.DisplayText, attributeIcons: itemData.AttributeIcons); item.Properties.AddProperty(RoslynItem, roslynItem); item.Properties.AddProperty(TriggerLocation, initialTriggerLocation); return item; } private static ImmutableArray<char> GetExcludedCommitCharacters(ImmutableArray<RoslynCompletionItem> roslynItems) { var hashSet = new HashSet<char>(); foreach (var roslynItem in roslynItems) { foreach (var rule in roslynItem.Rules.FilterCharacterRules) { if (rule.Kind == CharacterSetModificationKind.Add) { foreach (var c in rule.Characters) { hashSet.Add(c); } } } } return hashSet.ToImmutableArray(); } internal static bool QuestionMarkIsPrecededByIdentifierAndWhitespace( SourceText text, int questionPosition, ISyntaxFactsService syntaxFacts) { var startOfLine = text.Lines.GetLineFromPosition(questionPosition).Start; // First, skip all the whitespace. var current = startOfLine; while (current < questionPosition && char.IsWhiteSpace(text[current])) { current++; } if (current < questionPosition && syntaxFacts.IsIdentifierStartCharacter(text[current])) { current++; } else { return false; } while (current < questionPosition && syntaxFacts.IsIdentifierPartCharacter(text[current])) { current++; } return current == questionPosition; } } }
-1
dotnet/roslyn
56,015
Remove obsolete APIs
Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
tmat
"2021-08-30T20:53:26Z"
"2021-09-02T16:56:01Z"
bdf1025480ad91f8db054959553257746f58f527
e782ce78f087060a3bc51737d3f07a6d102fb7b1
Remove obsolete APIs. Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
./src/Compilers/Test/Resources/Core/SymbolsTests/Delegates/DelegatesWithoutInvoke.il
// build using: // ilasm DelegatesWithoutInvoke.il /output=DelegatesWithoutInvoke.dll /dll // Microsoft (R) .NET Framework IL Disassembler. Version 4.0.30319.1 // Metadata version: v4.0.30319 .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. .ver 4:0:0:0 } .assembly extern System { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. .ver 4:0:0:0 } .assembly DelegatesWithoutInvoke { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilationRelaxationsAttribute::.ctor(int32) = ( 01 00 08 00 00 00 00 00 ) .custom instance void [mscorlib]System.Runtime.CompilerServices.RuntimeCompatibilityAttribute::.ctor() = ( 01 00 01 00 54 02 16 57 72 61 70 4E 6F 6E 45 78 // ....T..WrapNonEx 63 65 70 74 69 6F 6E 54 68 72 6F 77 73 01 ) // ceptionThrows. .hash algorithm 0x00008004 .ver 1:0:0:0 } .module DelegatesWithoutInvoke.dll // MVID: {23AC8B14-AEA4-4D44-A317-2721A45F95B7} .imagebase 0x00400000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0002 // WINDOWS_GUI .corflags 0x00000001 // ILONLY // Image base: 0x001C0000 .class public auto ansi DelegateWithoutInvoke extends [mscorlib]System.Object { .class auto ansi sealed nested public DelegateSubWithoutInvoke extends [mscorlib]System.MulticastDelegate { .method public specialname rtspecialname instance void .ctor(object TargetObject, native int TargetMethod) runtime managed { } // end of method DelegateSubWithoutInvoke::.ctor .method public newslot strict virtual instance class [mscorlib]System.IAsyncResult BeginInvoke(string p, class [mscorlib]System.AsyncCallback DelegateCallback, object DelegateAsyncState) runtime managed { } // end of method DelegateSubWithoutInvoke::BeginInvoke .method public newslot strict virtual instance void EndInvoke(class [mscorlib]System.IAsyncResult DelegateAsyncResult) runtime managed { } // end of method DelegateSubWithoutInvoke::EndInvoke // .method public newslot strict virtual // instance void Invoke(string p) runtime managed // { // } end of method DelegateSubWithoutInvoke::Invoke } // end of class DelegateSubWithoutInvoke .class auto ansi sealed nested public DelegateFunctionWithoutInvoke extends [mscorlib]System.MulticastDelegate { .method public specialname rtspecialname instance void .ctor(object TargetObject, native int TargetMethod) runtime managed { } // end of method DelegateFunctionWithoutInvoke::.ctor .method public newslot strict virtual instance class [mscorlib]System.IAsyncResult BeginInvoke(string p, class [mscorlib]System.AsyncCallback DelegateCallback, object DelegateAsyncState) runtime managed { } // end of method DelegateFunctionWithoutInvoke::BeginInvoke .method public newslot strict virtual instance string EndInvoke(class [mscorlib]System.IAsyncResult DelegateAsyncResult) runtime managed { } // end of method DelegateFunctionWithoutInvoke::EndInvoke // .method public newslot strict virtual // instance string Invoke(string p) runtime managed // { // } } // end of class DelegateFunctionWithoutInvoke .class auto ansi sealed nested public DelegateGenericFunctionWithoutInvoke`1<T> extends [mscorlib]System.MulticastDelegate { .method public specialname rtspecialname instance void .ctor(object TargetObject, native int TargetMethod) runtime managed { } // end of method DelegateGenericFunctionWithoutInvoke`1::.ctor .method public newslot strict virtual instance class [mscorlib]System.IAsyncResult BeginInvoke(!T p, class [mscorlib]System.AsyncCallback DelegateCallback, object DelegateAsyncState) runtime managed { } // end of method DelegateGenericFunctionWithoutInvoke`1::BeginInvoke .method public newslot strict virtual instance !T EndInvoke(class [mscorlib]System.IAsyncResult DelegateAsyncResult) runtime managed { } // end of method DelegateGenericFunctionWithoutInvoke`1::EndInvoke } // end of class DelegateGenericFunctionWithoutInvoke`1 .field public class DelegateWithoutInvoke/DelegateSubWithoutInvoke SubDel .field public class DelegateWithoutInvoke/DelegateFunctionWithoutInvoke FuncDel .method public specialname rtspecialname instance void .ctor() cil managed { // Code size 43 (0x2b) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: ldnull IL_0008: ldftn void DelegateWithoutInvoke::DelSubImpl(string) IL_000e: newobj instance void DelegateWithoutInvoke/DelegateSubWithoutInvoke::.ctor(object, native int) IL_0013: stfld class DelegateWithoutInvoke/DelegateSubWithoutInvoke DelegateWithoutInvoke::SubDel IL_0018: ldarg.0 IL_0019: ldnull IL_001a: ldftn string DelegateWithoutInvoke::DelFuncImpl(string) IL_0020: newobj instance void DelegateWithoutInvoke/DelegateFunctionWithoutInvoke::.ctor(object, native int) IL_0025: stfld class DelegateWithoutInvoke/DelegateFunctionWithoutInvoke DelegateWithoutInvoke::FuncDel IL_002a: ret } // end of method DelegateWithoutInvoke::.ctor .method public static void DelSubImpl(string p) cil managed { // Code size 17 (0x11) .maxstack 8 IL_0000: ldstr "DelegateWithoutInvoke.DelSubImpl called " IL_0005: ldarg.0 IL_0006: call string [mscorlib]System.String::Concat(string, string) IL_000b: call void [mscorlib]System.Console::WriteLine(string) IL_0010: ret } // end of method DelegateWithoutInvoke::DelSubImpl .method public static string DelFuncImpl(string p) cil managed { // Code size 16 (0x10) .maxstack 2 .locals init (string V_0) IL_0000: ldstr "DelegateWithoutInvoke.DelFuncImpl called " IL_0005: ldarg.0 IL_0006: call string [mscorlib]System.String::Concat(string, string) IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method DelegateWithoutInvoke::DelFuncImpl } // end of class DelegateWithoutInvoke // ============================================================= // *********** DISASSEMBLY COMPLETE *********************** // WARNING: Created Win32 resource file test.res
// build using: // ilasm DelegatesWithoutInvoke.il /output=DelegatesWithoutInvoke.dll /dll // Microsoft (R) .NET Framework IL Disassembler. Version 4.0.30319.1 // Metadata version: v4.0.30319 .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. .ver 4:0:0:0 } .assembly extern System { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. .ver 4:0:0:0 } .assembly DelegatesWithoutInvoke { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilationRelaxationsAttribute::.ctor(int32) = ( 01 00 08 00 00 00 00 00 ) .custom instance void [mscorlib]System.Runtime.CompilerServices.RuntimeCompatibilityAttribute::.ctor() = ( 01 00 01 00 54 02 16 57 72 61 70 4E 6F 6E 45 78 // ....T..WrapNonEx 63 65 70 74 69 6F 6E 54 68 72 6F 77 73 01 ) // ceptionThrows. .hash algorithm 0x00008004 .ver 1:0:0:0 } .module DelegatesWithoutInvoke.dll // MVID: {23AC8B14-AEA4-4D44-A317-2721A45F95B7} .imagebase 0x00400000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0002 // WINDOWS_GUI .corflags 0x00000001 // ILONLY // Image base: 0x001C0000 .class public auto ansi DelegateWithoutInvoke extends [mscorlib]System.Object { .class auto ansi sealed nested public DelegateSubWithoutInvoke extends [mscorlib]System.MulticastDelegate { .method public specialname rtspecialname instance void .ctor(object TargetObject, native int TargetMethod) runtime managed { } // end of method DelegateSubWithoutInvoke::.ctor .method public newslot strict virtual instance class [mscorlib]System.IAsyncResult BeginInvoke(string p, class [mscorlib]System.AsyncCallback DelegateCallback, object DelegateAsyncState) runtime managed { } // end of method DelegateSubWithoutInvoke::BeginInvoke .method public newslot strict virtual instance void EndInvoke(class [mscorlib]System.IAsyncResult DelegateAsyncResult) runtime managed { } // end of method DelegateSubWithoutInvoke::EndInvoke // .method public newslot strict virtual // instance void Invoke(string p) runtime managed // { // } end of method DelegateSubWithoutInvoke::Invoke } // end of class DelegateSubWithoutInvoke .class auto ansi sealed nested public DelegateFunctionWithoutInvoke extends [mscorlib]System.MulticastDelegate { .method public specialname rtspecialname instance void .ctor(object TargetObject, native int TargetMethod) runtime managed { } // end of method DelegateFunctionWithoutInvoke::.ctor .method public newslot strict virtual instance class [mscorlib]System.IAsyncResult BeginInvoke(string p, class [mscorlib]System.AsyncCallback DelegateCallback, object DelegateAsyncState) runtime managed { } // end of method DelegateFunctionWithoutInvoke::BeginInvoke .method public newslot strict virtual instance string EndInvoke(class [mscorlib]System.IAsyncResult DelegateAsyncResult) runtime managed { } // end of method DelegateFunctionWithoutInvoke::EndInvoke // .method public newslot strict virtual // instance string Invoke(string p) runtime managed // { // } } // end of class DelegateFunctionWithoutInvoke .class auto ansi sealed nested public DelegateGenericFunctionWithoutInvoke`1<T> extends [mscorlib]System.MulticastDelegate { .method public specialname rtspecialname instance void .ctor(object TargetObject, native int TargetMethod) runtime managed { } // end of method DelegateGenericFunctionWithoutInvoke`1::.ctor .method public newslot strict virtual instance class [mscorlib]System.IAsyncResult BeginInvoke(!T p, class [mscorlib]System.AsyncCallback DelegateCallback, object DelegateAsyncState) runtime managed { } // end of method DelegateGenericFunctionWithoutInvoke`1::BeginInvoke .method public newslot strict virtual instance !T EndInvoke(class [mscorlib]System.IAsyncResult DelegateAsyncResult) runtime managed { } // end of method DelegateGenericFunctionWithoutInvoke`1::EndInvoke } // end of class DelegateGenericFunctionWithoutInvoke`1 .field public class DelegateWithoutInvoke/DelegateSubWithoutInvoke SubDel .field public class DelegateWithoutInvoke/DelegateFunctionWithoutInvoke FuncDel .method public specialname rtspecialname instance void .ctor() cil managed { // Code size 43 (0x2b) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: ldnull IL_0008: ldftn void DelegateWithoutInvoke::DelSubImpl(string) IL_000e: newobj instance void DelegateWithoutInvoke/DelegateSubWithoutInvoke::.ctor(object, native int) IL_0013: stfld class DelegateWithoutInvoke/DelegateSubWithoutInvoke DelegateWithoutInvoke::SubDel IL_0018: ldarg.0 IL_0019: ldnull IL_001a: ldftn string DelegateWithoutInvoke::DelFuncImpl(string) IL_0020: newobj instance void DelegateWithoutInvoke/DelegateFunctionWithoutInvoke::.ctor(object, native int) IL_0025: stfld class DelegateWithoutInvoke/DelegateFunctionWithoutInvoke DelegateWithoutInvoke::FuncDel IL_002a: ret } // end of method DelegateWithoutInvoke::.ctor .method public static void DelSubImpl(string p) cil managed { // Code size 17 (0x11) .maxstack 8 IL_0000: ldstr "DelegateWithoutInvoke.DelSubImpl called " IL_0005: ldarg.0 IL_0006: call string [mscorlib]System.String::Concat(string, string) IL_000b: call void [mscorlib]System.Console::WriteLine(string) IL_0010: ret } // end of method DelegateWithoutInvoke::DelSubImpl .method public static string DelFuncImpl(string p) cil managed { // Code size 16 (0x10) .maxstack 2 .locals init (string V_0) IL_0000: ldstr "DelegateWithoutInvoke.DelFuncImpl called " IL_0005: ldarg.0 IL_0006: call string [mscorlib]System.String::Concat(string, string) IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method DelegateWithoutInvoke::DelFuncImpl } // end of class DelegateWithoutInvoke // ============================================================= // *********** DISASSEMBLY COMPLETE *********************** // WARNING: Created Win32 resource file test.res
-1
dotnet/roslyn
56,015
Remove obsolete APIs
Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
tmat
"2021-08-30T20:53:26Z"
"2021-09-02T16:56:01Z"
bdf1025480ad91f8db054959553257746f58f527
e782ce78f087060a3bc51737d3f07a6d102fb7b1
Remove obsolete APIs. Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
./src/Compilers/Core/Portable/CommandLine/CommonCompiler.LoggingSourceFileResolver.cs
// 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. using System.Collections.Generic; using System.Collections.Immutable; namespace Microsoft.CodeAnalysis { internal abstract partial class CommonCompiler { internal sealed class LoggingSourceFileResolver : SourceFileResolver { private readonly TouchedFileLogger? _logger; public LoggingSourceFileResolver( ImmutableArray<string> searchPaths, string? baseDirectory, ImmutableArray<KeyValuePair<string, string>> pathMap, TouchedFileLogger? logger) : base(searchPaths, baseDirectory, pathMap) { _logger = logger; } protected override bool FileExists(string? fullPath) { if (fullPath != null) { _logger?.AddRead(fullPath); } return base.FileExists(fullPath); } public LoggingSourceFileResolver WithBaseDirectory(string value) => (BaseDirectory == value) ? this : new LoggingSourceFileResolver(SearchPaths, value, PathMap, _logger); public LoggingSourceFileResolver WithSearchPaths(ImmutableArray<string> value) => (SearchPaths == value) ? this : new LoggingSourceFileResolver(value, BaseDirectory, PathMap, _logger); } } }
// 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. using System.Collections.Generic; using System.Collections.Immutable; namespace Microsoft.CodeAnalysis { internal abstract partial class CommonCompiler { internal sealed class LoggingSourceFileResolver : SourceFileResolver { private readonly TouchedFileLogger? _logger; public LoggingSourceFileResolver( ImmutableArray<string> searchPaths, string? baseDirectory, ImmutableArray<KeyValuePair<string, string>> pathMap, TouchedFileLogger? logger) : base(searchPaths, baseDirectory, pathMap) { _logger = logger; } protected override bool FileExists(string? fullPath) { if (fullPath != null) { _logger?.AddRead(fullPath); } return base.FileExists(fullPath); } public LoggingSourceFileResolver WithBaseDirectory(string value) => (BaseDirectory == value) ? this : new LoggingSourceFileResolver(SearchPaths, value, PathMap, _logger); public LoggingSourceFileResolver WithSearchPaths(ImmutableArray<string> value) => (SearchPaths == value) ? this : new LoggingSourceFileResolver(value, BaseDirectory, PathMap, _logger); } } }
-1
dotnet/roslyn
56,015
Remove obsolete APIs
Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
tmat
"2021-08-30T20:53:26Z"
"2021-09-02T16:56:01Z"
bdf1025480ad91f8db054959553257746f58f527
e782ce78f087060a3bc51737d3f07a6d102fb7b1
Remove obsolete APIs. Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
./src/Compilers/CSharp/Portable/Symbols/MetadataOrSourceAssemblySymbol.cs
// 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. #nullable disable using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Represents source or metadata assembly. /// </summary> internal abstract class MetadataOrSourceAssemblySymbol : NonMissingAssemblySymbol { /// <summary> /// An array of cached Cor types defined in this assembly. /// Lazily filled by GetDeclaredSpecialType method. /// </summary> private NamedTypeSymbol[] _lazySpecialTypes; /// <summary> /// How many Cor types have we cached so far. /// </summary> private int _cachedSpecialTypes; private NativeIntegerTypeSymbol[] _lazyNativeIntegerTypes; /// <summary> /// Lookup declaration for predefined CorLib type in this Assembly. /// </summary> /// <param name="type"></param> /// <returns></returns> internal sealed override NamedTypeSymbol GetDeclaredSpecialType(SpecialType type) { #if DEBUG foreach (var module in this.Modules) { Debug.Assert(module.GetReferencedAssemblies().Length == 0); } #endif if (_lazySpecialTypes == null || (object)_lazySpecialTypes[(int)type] == null) { MetadataTypeName emittedName = MetadataTypeName.FromFullName(type.GetMetadataName(), useCLSCompliantNameArityEncoding: true); ModuleSymbol module = this.Modules[0]; NamedTypeSymbol result = module.LookupTopLevelMetadataType(ref emittedName); if (result.Kind != SymbolKind.ErrorType && result.DeclaredAccessibility != Accessibility.Public) { result = new MissingMetadataTypeSymbol.TopLevel(module, ref emittedName, type); } RegisterDeclaredSpecialType(result); } return _lazySpecialTypes[(int)type]; } /// <summary> /// Register declaration of predefined CorLib type in this Assembly. /// </summary> /// <param name="corType"></param> internal sealed override void RegisterDeclaredSpecialType(NamedTypeSymbol corType) { SpecialType typeId = corType.SpecialType; Debug.Assert(typeId != SpecialType.None); Debug.Assert(ReferenceEquals(corType.ContainingAssembly, this)); Debug.Assert(corType.ContainingModule.Ordinal == 0); Debug.Assert(ReferenceEquals(this.CorLibrary, this)); if (_lazySpecialTypes == null) { Interlocked.CompareExchange(ref _lazySpecialTypes, new NamedTypeSymbol[(int)SpecialType.Count + 1], null); } if ((object)Interlocked.CompareExchange(ref _lazySpecialTypes[(int)typeId], corType, null) != null) { Debug.Assert(ReferenceEquals(corType, _lazySpecialTypes[(int)typeId]) || (corType.Kind == SymbolKind.ErrorType && _lazySpecialTypes[(int)typeId].Kind == SymbolKind.ErrorType)); } else { Interlocked.Increment(ref _cachedSpecialTypes); Debug.Assert(_cachedSpecialTypes > 0 && _cachedSpecialTypes <= (int)SpecialType.Count); } } /// <summary> /// Continue looking for declaration of predefined CorLib type in this Assembly /// while symbols for new type declarations are constructed. /// </summary> internal override bool KeepLookingForDeclaredSpecialTypes { get { return ReferenceEquals(this.CorLibrary, this) && _cachedSpecialTypes < (int)SpecialType.Count; } } private ICollection<string> _lazyTypeNames; private ICollection<string> _lazyNamespaceNames; public override ICollection<string> TypeNames { get { if (_lazyTypeNames == null) { Interlocked.CompareExchange(ref _lazyTypeNames, UnionCollection<string>.Create(this.Modules, m => m.TypeNames), null); } return _lazyTypeNames; } } internal sealed override NamedTypeSymbol GetNativeIntegerType(NamedTypeSymbol underlyingType) { if (_lazyNativeIntegerTypes == null) { Interlocked.CompareExchange(ref _lazyNativeIntegerTypes, new NativeIntegerTypeSymbol[2], null); } int index = underlyingType.SpecialType switch { SpecialType.System_IntPtr => 0, SpecialType.System_UIntPtr => 1, _ => throw ExceptionUtilities.UnexpectedValue(underlyingType.SpecialType), }; if (_lazyNativeIntegerTypes[index] is null) { Interlocked.CompareExchange(ref _lazyNativeIntegerTypes[index], new NativeIntegerTypeSymbol(underlyingType), null); } return _lazyNativeIntegerTypes[index]; } public override ICollection<string> NamespaceNames { get { if (_lazyNamespaceNames == null) { Interlocked.CompareExchange(ref _lazyNamespaceNames, UnionCollection<string>.Create(this.Modules, m => m.NamespaceNames), null); } return _lazyNamespaceNames; } } /// <summary> /// Not yet known value is represented by ErrorTypeSymbol.UnknownResultType /// </summary> private Symbol[] _lazySpecialTypeMembers; /// <summary> /// Lookup member declaration in predefined CorLib type in this Assembly. Only valid if this /// assembly is the Cor Library /// </summary> internal override Symbol GetDeclaredSpecialTypeMember(SpecialMember member) { #if DEBUG foreach (var module in this.Modules) { Debug.Assert(module.GetReferencedAssemblies().Length == 0); } #endif if (_lazySpecialTypeMembers == null || ReferenceEquals(_lazySpecialTypeMembers[(int)member], ErrorTypeSymbol.UnknownResultType)) { if (_lazySpecialTypeMembers == null) { var specialTypeMembers = new Symbol[(int)SpecialMember.Count]; for (int i = 0; i < specialTypeMembers.Length; i++) { specialTypeMembers[i] = ErrorTypeSymbol.UnknownResultType; } Interlocked.CompareExchange(ref _lazySpecialTypeMembers, specialTypeMembers, null); } var descriptor = SpecialMembers.GetDescriptor(member); NamedTypeSymbol type = GetDeclaredSpecialType((SpecialType)descriptor.DeclaringTypeId); Symbol result = null; if (!type.IsErrorType()) { result = CSharpCompilation.GetRuntimeMember(type, descriptor, CSharpCompilation.SpecialMembersSignatureComparer.Instance, accessWithinOpt: null); } Interlocked.CompareExchange(ref _lazySpecialTypeMembers[(int)member], result, ErrorTypeSymbol.UnknownResultType); } return _lazySpecialTypeMembers[(int)member]; } /// <summary> /// Determine whether this assembly has been granted access to <paramref name="potentialGiverOfAccess"></paramref>. /// Assumes that the public key has been determined. The result will be cached. /// </summary> /// <param name="potentialGiverOfAccess"></param> /// <returns></returns> /// <remarks></remarks> protected IVTConclusion MakeFinalIVTDetermination(AssemblySymbol potentialGiverOfAccess) { IVTConclusion result; if (AssembliesToWhichInternalAccessHasBeenDetermined.TryGetValue(potentialGiverOfAccess, out result)) return result; result = IVTConclusion.NoRelationshipClaimed; // returns an empty list if there was no IVT attribute at all for the given name // A name w/o a key is represented by a list with an entry that is empty IEnumerable<ImmutableArray<byte>> publicKeys = potentialGiverOfAccess.GetInternalsVisibleToPublicKeys(this.Name); // We have an easy out here. Suppose the assembly wanting access is // being compiled as a module. You can only strong-name an assembly. So we are going to optimistically // assume that it is going to be compiled into an assembly with a matching strong name, if necessary. if (publicKeys.Any() && this.IsNetModule()) { return IVTConclusion.Match; } // look for one that works, if none work, then return the failure for the last one examined. foreach (var key in publicKeys) { // We pass the public key of this assembly explicitly so PerformIVTCheck does not need // to get it from this.Identity, which would trigger an infinite recursion. result = potentialGiverOfAccess.Identity.PerformIVTCheck(this.PublicKey, key); Debug.Assert(result != IVTConclusion.NoRelationshipClaimed); if (result == IVTConclusion.Match || result == IVTConclusion.OneSignedOneNot) { break; } } AssembliesToWhichInternalAccessHasBeenDetermined.TryAdd(potentialGiverOfAccess, result); return result; } //EDMAURER This is a cache mapping from assemblies which we have analyzed whether or not they grant //internals access to us to the conclusion reached. private ConcurrentDictionary<AssemblySymbol, IVTConclusion> _assembliesToWhichInternalAccessHasBeenAnalyzed; private ConcurrentDictionary<AssemblySymbol, IVTConclusion> AssembliesToWhichInternalAccessHasBeenDetermined { get { if (_assembliesToWhichInternalAccessHasBeenAnalyzed == null) Interlocked.CompareExchange(ref _assembliesToWhichInternalAccessHasBeenAnalyzed, new ConcurrentDictionary<AssemblySymbol, IVTConclusion>(), null); return _assembliesToWhichInternalAccessHasBeenAnalyzed; } } internal virtual bool IsNetModule() => false; } }
// 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. #nullable disable using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Represents source or metadata assembly. /// </summary> internal abstract class MetadataOrSourceAssemblySymbol : NonMissingAssemblySymbol { /// <summary> /// An array of cached Cor types defined in this assembly. /// Lazily filled by GetDeclaredSpecialType method. /// </summary> private NamedTypeSymbol[] _lazySpecialTypes; /// <summary> /// How many Cor types have we cached so far. /// </summary> private int _cachedSpecialTypes; private NativeIntegerTypeSymbol[] _lazyNativeIntegerTypes; /// <summary> /// Lookup declaration for predefined CorLib type in this Assembly. /// </summary> /// <param name="type"></param> /// <returns></returns> internal sealed override NamedTypeSymbol GetDeclaredSpecialType(SpecialType type) { #if DEBUG foreach (var module in this.Modules) { Debug.Assert(module.GetReferencedAssemblies().Length == 0); } #endif if (_lazySpecialTypes == null || (object)_lazySpecialTypes[(int)type] == null) { MetadataTypeName emittedName = MetadataTypeName.FromFullName(type.GetMetadataName(), useCLSCompliantNameArityEncoding: true); ModuleSymbol module = this.Modules[0]; NamedTypeSymbol result = module.LookupTopLevelMetadataType(ref emittedName); if (result.Kind != SymbolKind.ErrorType && result.DeclaredAccessibility != Accessibility.Public) { result = new MissingMetadataTypeSymbol.TopLevel(module, ref emittedName, type); } RegisterDeclaredSpecialType(result); } return _lazySpecialTypes[(int)type]; } /// <summary> /// Register declaration of predefined CorLib type in this Assembly. /// </summary> /// <param name="corType"></param> internal sealed override void RegisterDeclaredSpecialType(NamedTypeSymbol corType) { SpecialType typeId = corType.SpecialType; Debug.Assert(typeId != SpecialType.None); Debug.Assert(ReferenceEquals(corType.ContainingAssembly, this)); Debug.Assert(corType.ContainingModule.Ordinal == 0); Debug.Assert(ReferenceEquals(this.CorLibrary, this)); if (_lazySpecialTypes == null) { Interlocked.CompareExchange(ref _lazySpecialTypes, new NamedTypeSymbol[(int)SpecialType.Count + 1], null); } if ((object)Interlocked.CompareExchange(ref _lazySpecialTypes[(int)typeId], corType, null) != null) { Debug.Assert(ReferenceEquals(corType, _lazySpecialTypes[(int)typeId]) || (corType.Kind == SymbolKind.ErrorType && _lazySpecialTypes[(int)typeId].Kind == SymbolKind.ErrorType)); } else { Interlocked.Increment(ref _cachedSpecialTypes); Debug.Assert(_cachedSpecialTypes > 0 && _cachedSpecialTypes <= (int)SpecialType.Count); } } /// <summary> /// Continue looking for declaration of predefined CorLib type in this Assembly /// while symbols for new type declarations are constructed. /// </summary> internal override bool KeepLookingForDeclaredSpecialTypes { get { return ReferenceEquals(this.CorLibrary, this) && _cachedSpecialTypes < (int)SpecialType.Count; } } private ICollection<string> _lazyTypeNames; private ICollection<string> _lazyNamespaceNames; public override ICollection<string> TypeNames { get { if (_lazyTypeNames == null) { Interlocked.CompareExchange(ref _lazyTypeNames, UnionCollection<string>.Create(this.Modules, m => m.TypeNames), null); } return _lazyTypeNames; } } internal sealed override NamedTypeSymbol GetNativeIntegerType(NamedTypeSymbol underlyingType) { if (_lazyNativeIntegerTypes == null) { Interlocked.CompareExchange(ref _lazyNativeIntegerTypes, new NativeIntegerTypeSymbol[2], null); } int index = underlyingType.SpecialType switch { SpecialType.System_IntPtr => 0, SpecialType.System_UIntPtr => 1, _ => throw ExceptionUtilities.UnexpectedValue(underlyingType.SpecialType), }; if (_lazyNativeIntegerTypes[index] is null) { Interlocked.CompareExchange(ref _lazyNativeIntegerTypes[index], new NativeIntegerTypeSymbol(underlyingType), null); } return _lazyNativeIntegerTypes[index]; } public override ICollection<string> NamespaceNames { get { if (_lazyNamespaceNames == null) { Interlocked.CompareExchange(ref _lazyNamespaceNames, UnionCollection<string>.Create(this.Modules, m => m.NamespaceNames), null); } return _lazyNamespaceNames; } } /// <summary> /// Not yet known value is represented by ErrorTypeSymbol.UnknownResultType /// </summary> private Symbol[] _lazySpecialTypeMembers; /// <summary> /// Lookup member declaration in predefined CorLib type in this Assembly. Only valid if this /// assembly is the Cor Library /// </summary> internal override Symbol GetDeclaredSpecialTypeMember(SpecialMember member) { #if DEBUG foreach (var module in this.Modules) { Debug.Assert(module.GetReferencedAssemblies().Length == 0); } #endif if (_lazySpecialTypeMembers == null || ReferenceEquals(_lazySpecialTypeMembers[(int)member], ErrorTypeSymbol.UnknownResultType)) { if (_lazySpecialTypeMembers == null) { var specialTypeMembers = new Symbol[(int)SpecialMember.Count]; for (int i = 0; i < specialTypeMembers.Length; i++) { specialTypeMembers[i] = ErrorTypeSymbol.UnknownResultType; } Interlocked.CompareExchange(ref _lazySpecialTypeMembers, specialTypeMembers, null); } var descriptor = SpecialMembers.GetDescriptor(member); NamedTypeSymbol type = GetDeclaredSpecialType((SpecialType)descriptor.DeclaringTypeId); Symbol result = null; if (!type.IsErrorType()) { result = CSharpCompilation.GetRuntimeMember(type, descriptor, CSharpCompilation.SpecialMembersSignatureComparer.Instance, accessWithinOpt: null); } Interlocked.CompareExchange(ref _lazySpecialTypeMembers[(int)member], result, ErrorTypeSymbol.UnknownResultType); } return _lazySpecialTypeMembers[(int)member]; } /// <summary> /// Determine whether this assembly has been granted access to <paramref name="potentialGiverOfAccess"></paramref>. /// Assumes that the public key has been determined. The result will be cached. /// </summary> /// <param name="potentialGiverOfAccess"></param> /// <returns></returns> /// <remarks></remarks> protected IVTConclusion MakeFinalIVTDetermination(AssemblySymbol potentialGiverOfAccess) { IVTConclusion result; if (AssembliesToWhichInternalAccessHasBeenDetermined.TryGetValue(potentialGiverOfAccess, out result)) return result; result = IVTConclusion.NoRelationshipClaimed; // returns an empty list if there was no IVT attribute at all for the given name // A name w/o a key is represented by a list with an entry that is empty IEnumerable<ImmutableArray<byte>> publicKeys = potentialGiverOfAccess.GetInternalsVisibleToPublicKeys(this.Name); // We have an easy out here. Suppose the assembly wanting access is // being compiled as a module. You can only strong-name an assembly. So we are going to optimistically // assume that it is going to be compiled into an assembly with a matching strong name, if necessary. if (publicKeys.Any() && this.IsNetModule()) { return IVTConclusion.Match; } // look for one that works, if none work, then return the failure for the last one examined. foreach (var key in publicKeys) { // We pass the public key of this assembly explicitly so PerformIVTCheck does not need // to get it from this.Identity, which would trigger an infinite recursion. result = potentialGiverOfAccess.Identity.PerformIVTCheck(this.PublicKey, key); Debug.Assert(result != IVTConclusion.NoRelationshipClaimed); if (result == IVTConclusion.Match || result == IVTConclusion.OneSignedOneNot) { break; } } AssembliesToWhichInternalAccessHasBeenDetermined.TryAdd(potentialGiverOfAccess, result); return result; } //EDMAURER This is a cache mapping from assemblies which we have analyzed whether or not they grant //internals access to us to the conclusion reached. private ConcurrentDictionary<AssemblySymbol, IVTConclusion> _assembliesToWhichInternalAccessHasBeenAnalyzed; private ConcurrentDictionary<AssemblySymbol, IVTConclusion> AssembliesToWhichInternalAccessHasBeenDetermined { get { if (_assembliesToWhichInternalAccessHasBeenAnalyzed == null) Interlocked.CompareExchange(ref _assembliesToWhichInternalAccessHasBeenAnalyzed, new ConcurrentDictionary<AssemblySymbol, IVTConclusion>(), null); return _assembliesToWhichInternalAccessHasBeenAnalyzed; } } internal virtual bool IsNetModule() => false; } }
-1
dotnet/roslyn
56,015
Remove obsolete APIs
Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
tmat
"2021-08-30T20:53:26Z"
"2021-09-02T16:56:01Z"
bdf1025480ad91f8db054959553257746f58f527
e782ce78f087060a3bc51737d3f07a6d102fb7b1
Remove obsolete APIs. Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
./src/Compilers/VisualBasic/Portable/Compilation/VisualBasicScriptCompilationInfo.vb
' 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.VisualBasic Friend NotInheritable Class VisualBasicScriptCompilationInfo Inherits ScriptCompilationInfo Public Shadows ReadOnly Property PreviousScriptCompilation As VisualBasicCompilation Friend Sub New(previousCompilationOpt As VisualBasicCompilation, returnType As Type, globalsType As Type) MyBase.New(returnType, globalsType) Debug.Assert(previousCompilationOpt Is Nothing OrElse previousCompilationOpt.HostObjectType Is globalsType) PreviousScriptCompilation = previousCompilationOpt End Sub Friend Overrides ReadOnly Property CommonPreviousScriptCompilation As Compilation Get Return PreviousScriptCompilation End Get End Property Public Shadows Function WithPreviousScriptCompilation(compilation As VisualBasicCompilation) As VisualBasicScriptCompilationInfo Return If(compilation Is PreviousScriptCompilation, Me, New VisualBasicScriptCompilationInfo(compilation, ReturnTypeOpt, GlobalsType)) End Function Friend Overrides Function CommonWithPreviousScriptCompilation(compilation As Compilation) As ScriptCompilationInfo Return WithPreviousScriptCompilation(DirectCast(compilation, VisualBasicCompilation)) End Function End Class End Namespace
' 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.VisualBasic Friend NotInheritable Class VisualBasicScriptCompilationInfo Inherits ScriptCompilationInfo Public Shadows ReadOnly Property PreviousScriptCompilation As VisualBasicCompilation Friend Sub New(previousCompilationOpt As VisualBasicCompilation, returnType As Type, globalsType As Type) MyBase.New(returnType, globalsType) Debug.Assert(previousCompilationOpt Is Nothing OrElse previousCompilationOpt.HostObjectType Is globalsType) PreviousScriptCompilation = previousCompilationOpt End Sub Friend Overrides ReadOnly Property CommonPreviousScriptCompilation As Compilation Get Return PreviousScriptCompilation End Get End Property Public Shadows Function WithPreviousScriptCompilation(compilation As VisualBasicCompilation) As VisualBasicScriptCompilationInfo Return If(compilation Is PreviousScriptCompilation, Me, New VisualBasicScriptCompilationInfo(compilation, ReturnTypeOpt, GlobalsType)) End Function Friend Overrides Function CommonWithPreviousScriptCompilation(compilation As Compilation) As ScriptCompilationInfo Return WithPreviousScriptCompilation(DirectCast(compilation, VisualBasicCompilation)) End Function End Class End Namespace
-1
dotnet/roslyn
56,011
React to string comparison changing on .NET Core
The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
jaredpar
"2021-08-30T17:18:52Z"
"2021-08-30T20:20:04Z"
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
4d99cda6e446e77dbb302e26388c1093bd3ef569
React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
./src/Compilers/Test/Utilities/VisualBasic/CompilationTestUtils.vb
' 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.IO Imports System.Runtime.CompilerServices Imports System.Runtime.InteropServices Imports System.Text Imports System.Xml.Linq Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Roslyn.Test.Utilities Imports Roslyn.Test.Utilities.TestBase Imports Roslyn.Test.Utilities.TestMetadata Imports Xunit Friend Module CompilationUtils Private Function ParseSources(source As IEnumerable(Of String), parseOptions As VisualBasicParseOptions) As IEnumerable(Of SyntaxTree) Return source.Select(Function(s) VisualBasicSyntaxTree.ParseText(s, parseOptions)) End Function Public Function CreateCompilation( source As BasicTestSource, Optional references As IEnumerable(Of MetadataReference) = Nothing, Optional options As VisualBasicCompilationOptions = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing, Optional targetFramework As TargetFramework = TargetFramework.StandardAndVBRuntime, Optional assemblyName As String = Nothing) As VisualBasicCompilation references = TargetFrameworkUtil.GetReferences(targetFramework, references) Return CreateEmptyCompilation(source, references, options, parseOptions, assemblyName) End Function Public Function CreateEmptyCompilation( source As BasicTestSource, Optional references As IEnumerable(Of MetadataReference) = Nothing, Optional options As VisualBasicCompilationOptions = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing, Optional assemblyName As String = Nothing) As VisualBasicCompilation If options Is Nothing Then options = TestOptions.ReleaseDll End If ' Using single-threaded build if debugger attached, to simplify debugging. If Debugger.IsAttached Then options = options.WithConcurrentBuild(False) End If Dim trees = source.GetSyntaxTrees(parseOptions, assemblyName) Dim createCompilationLambda = Function() Return VisualBasicCompilation.Create( If(assemblyName, GetUniqueName()), trees, references, options) End Function ValidateCompilation(createCompilationLambda) Return createCompilationLambda() End Function Private Sub ValidateCompilation(createCompilationLambda As Func(Of VisualBasicCompilation)) CompilationExtensions.ValidateIOperations(createCompilationLambda) VerifyUsedAssemblyReferences(createCompilationLambda) End Sub Private Sub VerifyUsedAssemblyReferences(createCompilationLambda As Func(Of VisualBasicCompilation)) If Not CompilationExtensions.EnableVerifyUsedAssemblies Then Return End If Dim comp = createCompilationLambda() Dim used = comp.GetUsedAssemblyReferences() Dim compileDiagnostics = comp.GetDiagnostics() Dim emitDiagnostics = comp.GetEmitDiagnostics() Dim resolvedReferences = comp.References.Where(Function(r) r.Properties.Kind = MetadataImageKind.Assembly) If Not compileDiagnostics.Any(Function(d) d.DefaultSeverity = DiagnosticSeverity.Error) Then If resolvedReferences.Count() > used.Length Then AssertSubset(used, resolvedReferences) If Not compileDiagnostics.Any(Function(d) d.Code = ERRID.HDN_UnusedImportClause OrElse d.Code = ERRID.HDN_UnusedImportStatement) Then Dim comp2 = comp.RemoveAllReferences().AddReferences(used.Concat(comp.References.Where(Function(r) r.Properties.Kind = MetadataImageKind.Module))) comp2.GetEmitDiagnostics().Verify( emitDiagnostics.Select(Function(d) New DiagnosticDescription(d, errorCodeOnly:=False, includeDefaultSeverity:=False, includeEffectiveSeverity:=False)).ToArray()) End If Else AssertEx.Equal(resolvedReferences, used) End If Else AssertSubset(used, resolvedReferences) End If End Sub Private Sub AssertSubset(used As ImmutableArray(Of MetadataReference), resolvedReferences As IEnumerable(Of MetadataReference)) For Each reference In used Assert.Contains(reference, resolvedReferences) Next End Sub Public Function CreateEmptyCompilation( identity As AssemblyIdentity, source As BasicTestSource, Optional references As MetadataReference() = Nothing, Optional options As VisualBasicCompilationOptions = Nothing) As VisualBasicCompilation Dim trees = source.GetSyntaxTrees() Dim createCompilationLambda = Function() Return VisualBasicCompilation.Create(identity.Name, trees, references, options) End Function ValidateCompilation(createCompilationLambda) Dim c = createCompilationLambda() Assert.NotNull(c.Assembly) ' force creation of SourceAssemblySymbol DirectCast(c.Assembly, SourceAssemblySymbol).m_lazyIdentity = identity Return c End Function Public Function CreateCompilationWithMscorlib40( source As BasicTestSource, Optional references As IEnumerable(Of MetadataReference) = Nothing, Optional options As VisualBasicCompilationOptions = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing, Optional assemblyName As String = Nothing) As VisualBasicCompilation Return CreateCompilation(source, references, options, parseOptions, TargetFramework.Mscorlib40, assemblyName) End Function Public Function CreateCompilationWithMscorlib45( source As BasicTestSource, Optional references As IEnumerable(Of MetadataReference) = Nothing, Optional options As VisualBasicCompilationOptions = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing, Optional assemblyName As String = Nothing) As VisualBasicCompilation Return CreateCompilation(source, references, options, parseOptions, TargetFramework.Mscorlib45, assemblyName) End Function Public Function CreateCompilationWithMscorlib45AndVBRuntime( source As BasicTestSource, Optional references As IEnumerable(Of MetadataReference) = Nothing, Optional options As VisualBasicCompilationOptions = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing, Optional assemblyName As String = Nothing) As VisualBasicCompilation Return CreateCompilation(source, references, options, parseOptions, TargetFramework.Mscorlib45AndVBRuntime, assemblyName) End Function Public Function CreateCompilationWithWinRt(source As XElement) As VisualBasicCompilation Return CreateEmptyCompilationWithReferences(source, WinRtRefs) End Function Public Function CreateCompilationWithMscorlib40AndReferences(source As XElement, references As IEnumerable(Of MetadataReference), Optional options As VisualBasicCompilationOptions = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing) As VisualBasicCompilation Return CreateEmptyCompilationWithReferences(source, {CType(Net40.mscorlib, MetadataReference)}.Concat(references), options, parseOptions:=parseOptions) End Function ''' <summary> ''' ''' </summary> ''' <param name="source">The sources compile according to the following schema ''' &lt;compilation name="assemblyname[optional]"&gt; ''' &lt;file name="file1.vb[optional]"&gt; ''' source ''' &lt;/file&gt; ''' &lt;/compilation&gt; ''' </param> Public Function CreateCompilationWithMscorlib40(source As XElement, outputKind As OutputKind, Optional parseOptions As VisualBasicParseOptions = Nothing) As VisualBasicCompilation Return CreateEmptyCompilationWithReferences(source, {Net40.mscorlib}, New VisualBasicCompilationOptions(outputKind), parseOptions:=parseOptions) End Function ''' <summary> ''' ''' </summary> ''' <param name="source">The sources compile according to the following schema ''' &lt;compilation name="assemblyname[optional]"&gt; ''' &lt;file name="file1.vb[optional]"&gt; ''' source ''' &lt;/file&gt; ''' &lt;/compilation&gt; ''' </param> Public Function CreateCompilationWithMscorlib40AndVBRuntime( source As XElement, Optional additionalRefs As MetadataReference() = Nothing, Optional options As VisualBasicCompilationOptions = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing, Optional assemblyName As String = Nothing) As VisualBasicCompilation If additionalRefs Is Nothing Then additionalRefs = {} Dim references = {CType(Net40.mscorlib, MetadataReference), Net40.System, Net40.MicrosoftVisualBasic}.Concat(additionalRefs) Return CreateEmptyCompilationWithReferences(source, references, options, parseOptions:=parseOptions, assemblyName:=assemblyName) End Function Public Function CreateCompilationWithMscorlib40AndVBRuntime(source As IEnumerable(Of SyntaxTree), options As VisualBasicCompilationOptions, Optional assemblyName As String = Nothing) As VisualBasicCompilation Dim references = {MscorlibRef, SystemRef, MsvbRef} Return CreateEmptyCompilation(source.ToArray(), references, options:=options, assemblyName:=assemblyName) End Function Public Function CreateCompilationWithMscorlib40AndVBRuntime(source As XElement, options As VisualBasicCompilationOptions) As VisualBasicCompilation Return CreateCompilationWithMscorlib40AndVBRuntime(source, Nothing, options, parseOptions:=If(options Is Nothing, Nothing, options.ParseOptions)) End Function Public ReadOnly XmlReferences As MetadataReference() = {SystemRef, SystemCoreRef, SystemXmlRef, SystemXmlLinqRef} Public ReadOnly Net40XmlReferences As MetadataReference() = {Net40.SystemCore, Net40.SystemXml, Net40.SystemXmlLinq} Public ReadOnly Net451XmlReferences As MetadataReference() = {Net451.SystemCore, Net451.SystemXml, Net451.SystemXmlLinq} ''' <summary> ''' ''' </summary> ''' <param name="source">The sources compile according to the following schema ''' &lt;compilation name="assemblyname[optional]"&gt; ''' &lt;file name="file1.vb[optional]"&gt; ''' source ''' &lt;/file&gt; ''' &lt;/compilation&gt; ''' </param> Public Function CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( source As XElement, Optional references As IEnumerable(Of MetadataReference) = Nothing, Optional options As VisualBasicCompilationOptions = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing) As VisualBasicCompilation If references Is Nothing Then references = {} Dim allReferences = {CType(Net40.mscorlib, MetadataReference), Net40.System, Net40.MicrosoftVisualBasic}.Concat(references) If parseOptions Is Nothing AndAlso options IsNot Nothing Then parseOptions = options.ParseOptions End If Return CreateEmptyCompilationWithReferences(source, allReferences, options, parseOptions:=parseOptions) End Function ''' <summary> ''' ''' </summary> ''' <param name="source">The sources compile according to the following schema ''' &lt;compilation name="assemblyname[optional]"&gt; ''' &lt;file name="file1.vb[optional]"&gt; ''' source ''' &lt;/file&gt; ''' &lt;/compilation&gt; ''' </param> Public Function CreateCompilationWithMscorlib45AndVBRuntime( source As XElement, Optional references As IEnumerable(Of MetadataReference) = Nothing, Optional options As VisualBasicCompilationOptions = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing) As VisualBasicCompilation Dim allReferences = {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}.Concat(If(references, {})) Return CreateEmptyCompilationWithReferences(source, allReferences, options, parseOptions:=parseOptions) End Function ''' <summary> ''' ''' </summary> ''' <param name="source">The sources compile according to the following schema ''' &lt;compilation name="assemblyname[optional]"&gt; ''' &lt;file name="file1.vb[optional]"&gt; ''' source ''' &lt;/file&gt; ''' &lt;/compilation&gt; ''' </param> Public Function CreateEmptyCompilationWithReferences(source As XElement, references As IEnumerable(Of MetadataReference), Optional options As VisualBasicCompilationOptions = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing, Optional assemblyName As String = Nothing) As VisualBasicCompilation Dim sourceTrees = ParseSourceXml(source, parseOptions, assemblyName) Return CreateEmptyCompilationWithReferences(sourceTrees, references, options, assemblyName) End Function Public Function ParseSourceXml(sources As XElement, parseOptions As VisualBasicParseOptions, Optional ByRef assemblyName As String = Nothing, Optional ByRef spans As IEnumerable(Of IEnumerable(Of TextSpan)) = Nothing) As IEnumerable(Of SyntaxTree) If sources.@name IsNot Nothing Then assemblyName = sources.@name End If Dim sourcesTreesAndSpans = From f In sources.<file> Select CreateParseTreeAndSpans(f, parseOptions) spans = From t In sourcesTreesAndSpans Select s = t.spans Return From t In sourcesTreesAndSpans Select t.tree End Function Public Function ToSourceTrees(compilationSources As XElement, Optional parseOptions As VisualBasicParseOptions = Nothing) As IEnumerable(Of SyntaxTree) Dim sourcesTreesAndSpans = From f In compilationSources.<file> Select CreateParseTreeAndSpans(f, parseOptions) Return From t In sourcesTreesAndSpans Select t.tree End Function Public Function CreateEmptyCompilationWithReferences(source As SyntaxTree, references As IEnumerable(Of MetadataReference), Optional options As VisualBasicCompilationOptions = Nothing, Optional assemblyName As String = Nothing) As VisualBasicCompilation Return CreateEmptyCompilationWithReferences({source}, references, options, assemblyName) End Function Public Function CreateEmptyCompilationWithReferences(source As IEnumerable(Of SyntaxTree), references As IEnumerable(Of MetadataReference), Optional options As VisualBasicCompilationOptions = Nothing, Optional assemblyName As String = Nothing) As VisualBasicCompilation If options Is Nothing Then options = TestOptions.ReleaseDll ' Using single-threaded build if debugger attached, to simplify debugging. If Debugger.IsAttached Then options = options.WithConcurrentBuild(False) End If End If Dim createCompilationLambda = Function() Return VisualBasicCompilation.Create(If(assemblyName, GetUniqueName()), source, references, options) End Function ValidateCompilation(createCompilationLambda) Return createCompilationLambda() End Function ''' <summary> ''' ''' </summary> ''' <param name="sources">The sources compile according to the following schema ''' &lt;compilation name="assemblyname[optional]"&gt; ''' &lt;file name="file1.vb[optional]"&gt; ''' source ''' &lt;/file&gt; ''' &lt;/compilation&gt; ''' </param> ''' <param name="ilSource"></param> ''' <returns></returns> ''' <remarks></remarks> Public Function CreateCompilationWithCustomILSource(sources As XElement, ilSource As XCData) As VisualBasicCompilation Return CreateCompilationWithCustomILSource(sources, ilSource.Value) End Function ''' <summary> ''' ''' </summary> ''' <param name="sources">The sources compile according to the following schema ''' &lt;compilation name="assemblyname[optional]"&gt; ''' &lt;file name="file1.vb[optional]"&gt; ''' source ''' &lt;/file&gt; ''' &lt;/compilation&gt; ''' </param> ''' <param name="ilSource"></param> ''' <returns></returns> ''' <remarks></remarks> Public Function CreateCompilationWithCustomILSource(sources As XElement, ilSource As String, Optional options As VisualBasicCompilationOptions = Nothing, Optional ByRef spans As IEnumerable(Of IEnumerable(Of TextSpan)) = Nothing, Optional includeVbRuntime As Boolean = False, Optional includeSystemCore As Boolean = False, Optional appendDefaultHeader As Boolean = True, Optional parseOptions As VisualBasicParseOptions = Nothing, Optional additionalReferences As IEnumerable(Of MetadataReference) = Nothing, <Out> Optional ByRef ilReference As MetadataReference = Nothing, <Out> Optional ByRef ilImage As ImmutableArray(Of Byte) = Nothing ) As VisualBasicCompilation Dim references = If(additionalReferences IsNot Nothing, New List(Of MetadataReference)(additionalReferences), New List(Of MetadataReference)) If includeVbRuntime Then references.Add(MsvbRef) End If If includeSystemCore Then references.Add(SystemCoreRef) End If If ilSource Is Nothing Then Return CreateCompilationWithMscorlib40AndReferences(sources, references, options, parseOptions) End If ilReference = CreateReferenceFromIlCode(ilSource, appendDefaultHeader, ilImage) references.Add(ilReference) Return CreateCompilationWithMscorlib40AndReferences(sources, references, options, parseOptions) End Function Public Function CreateReferenceFromIlCode(ilSource As String, Optional appendDefaultHeader As Boolean = True, <Out> Optional ByRef ilImage As ImmutableArray(Of Byte) = Nothing) As MetadataReference Using reference = IlasmUtilities.CreateTempAssembly(ilSource, appendDefaultHeader) ilImage = ImmutableArray.Create(File.ReadAllBytes(reference.Path)) End Using Return MetadataReference.CreateFromImage(ilImage) End Function Public Function GetUniqueName() As String Return Guid.NewGuid().ToString("D") End Function ' Filter text from within an XElement Public Function FilterString(s As String) As String s = s.Replace(vbCrLf, vbLf) ' If there are already "0d0a", don't replace them with "0d0a0a" s = s.Replace(vbLf, vbCrLf) Dim needToAddBackNewline = s.EndsWith(vbCrLf, StringComparison.Ordinal) s = s.Trim() If needToAddBackNewline Then s &= vbCrLf Return s End Function Public Function FindBindingText(Of TNode As SyntaxNode)(compilation As Compilation, fileName As String, Optional which As Integer = 0, Optional prefixMatch As Boolean = False) As TNode Dim tree = (From t In compilation.SyntaxTrees Where t.FilePath = fileName).Single() Dim bindText As String = Nothing Dim bindPoint = FindBindingTextPosition(compilation, fileName, bindText, which) Dim token = tree.GetRoot().FindToken(bindPoint, True) Dim node = token.Parent Dim hasMatchingText As Func(Of SyntaxNode, Boolean) = Function(n) n.ToString = bindText OrElse (prefixMatch AndAlso TryCast(n, TNode) IsNot Nothing AndAlso n.ToString.StartsWith(bindText)) While (node IsNot Nothing AndAlso Not hasMatchingText(node)) node = node.Parent End While If node IsNot Nothing Then While TryCast(node, TNode) Is Nothing If node.Parent IsNot Nothing AndAlso hasMatchingText(node.Parent) Then node = node.Parent Else Exit While End If End While End If Assert.NotNull(node) ' If this trips, then node wasn't found Assert.IsAssignableFrom(GetType(TNode), node) If Not prefixMatch Then Assert.Equal(bindText, node.ToString()) Else Assert.StartsWith(bindText, node.ToString) End If Return DirectCast(node, TNode) End Function Public Function FindBindingTextPosition(compilation As Compilation, fileName As String, ByRef bindText As String, Optional which As Integer = 0) As Integer Dim tree = (From t In compilation.SyntaxTrees Where t.FilePath = fileName).Single() Dim bindMarker As String If which > 0 Then bindMarker = "'BIND" & which.ToString() & ":""" Else bindMarker = "'BIND:""" End If Dim text As String = tree.GetRoot().ToFullString() Dim startCommentIndex As Integer = text.IndexOf(bindMarker, StringComparison.Ordinal) + bindMarker.Length Dim endCommentIndex As Integer = text.Length Dim endOfLineIndex = text.IndexOfAny({CChar(vbLf), CChar(vbCr)}, startCommentIndex) If endOfLineIndex > -1 Then endCommentIndex = endOfLineIndex End If ' There may be more than one 'BIND{1234...} marker per line Dim nextMarkerIndex = text.IndexOf("'BIND", startCommentIndex, endCommentIndex - startCommentIndex, StringComparison.Ordinal) If nextMarkerIndex > -1 Then endCommentIndex = nextMarkerIndex End If Dim commentText = text.Substring(startCommentIndex, endCommentIndex - startCommentIndex) Dim endBindCommentLength = commentText.LastIndexOf(""""c) If endBindCommentLength = 0 Then ' This cannot be 0 so it must be text that is quoted. Look for double ending quote ' 'Bind:""some quoted string"" endBindCommentLength = commentText.LastIndexOf("""""", 1, StringComparison.Ordinal) End If bindText = commentText.Substring(0, endBindCommentLength) Dim bindPoint = text.LastIndexOf(bindText, startCommentIndex - bindMarker.Length, StringComparison.Ordinal) Return bindPoint End Function Public Function FindBindingTextPosition(compilation As Compilation, fileName As String) As Integer Dim bindText As String = Nothing Return FindBindingTextPosition(compilation, fileName, bindText) End Function Public Function FindBindingStartText(Of TNode As SyntaxNode)(compilation As Compilation, fileName As String, Optional which As Integer = 0) As TNode Dim tree = (From t In compilation.SyntaxTrees Where t.FilePath = fileName).Single() Dim bindText As String = Nothing Dim bindPoint = FindBindingTextPosition(compilation, fileName, bindText, which) Dim token As SyntaxToken = tree.GetRoot().FindToken(bindPoint) Dim node = token.Parent While (node IsNot Nothing AndAlso node.ToString.StartsWith(bindText, StringComparison.Ordinal) AndAlso Not (TypeOf node Is TNode)) node = node.Parent End While Assert.NotNull(node) ' If this trips, then node wasn't found Assert.IsAssignableFrom(GetType(TNode), node) Assert.Contains(bindText, node.ToString(), StringComparison.Ordinal) Return DirectCast(node, TNode) End Function Friend Class SemanticInfoSummary Public Symbol As Symbol = Nothing Public CandidateReason As CandidateReason = CandidateReason.None Public CandidateSymbols As ImmutableArray(Of ISymbol) = ImmutableArray.Create(Of ISymbol)() Public AllSymbols As ImmutableArray(Of ISymbol) = ImmutableArray.Create(Of ISymbol)() Public [Type] As ITypeSymbol = Nothing Public ConvertedType As ITypeSymbol = Nothing Public ImplicitConversion As Conversion = Nothing Public MemberGroup As ImmutableArray(Of ISymbol) = ImmutableArray.Create(Of ISymbol)() Public [Alias] As IAliasSymbol = Nothing Public ConstantValue As [Optional](Of Object) = Nothing End Class <Extension()> Public Function GetSemanticInfoSummary(model As SemanticModel, node As SyntaxNode) As SemanticInfoSummary Dim summary As New SemanticInfoSummary ' The information that is available varies by the type of the syntax node. Dim semanticModel = DirectCast(model, VBSemanticModel) Dim symbolInfo As SymbolInfo If TypeOf node Is ExpressionSyntax Then symbolInfo = semanticModel.GetSymbolInfo(DirectCast(node, ExpressionSyntax)) summary.MemberGroup = semanticModel.GetMemberGroup(DirectCast(node, ExpressionSyntax)) summary.ConstantValue = semanticModel.GetConstantValue(DirectCast(node, ExpressionSyntax)) Dim typeInfo = semanticModel.GetTypeInfo(DirectCast(node, ExpressionSyntax)) summary.Type = DirectCast(typeInfo.Type, TypeSymbol) summary.ConvertedType = DirectCast(typeInfo.ConvertedType, TypeSymbol) summary.ImplicitConversion = semanticModel.GetConversion(DirectCast(node, ExpressionSyntax)) ElseIf TypeOf node Is AttributeSyntax Then symbolInfo = semanticModel.GetSymbolInfo(DirectCast(node, AttributeSyntax)) summary.MemberGroup = semanticModel.GetMemberGroup(DirectCast(node, AttributeSyntax)) Dim typeInfo = semanticModel.GetTypeInfo(DirectCast(node, AttributeSyntax)) summary.Type = DirectCast(typeInfo.Type, TypeSymbol) summary.ConvertedType = DirectCast(typeInfo.ConvertedType, TypeSymbol) summary.ImplicitConversion = semanticModel.GetConversion(DirectCast(node, AttributeSyntax)) ElseIf TypeOf node Is QueryClauseSyntax Then symbolInfo = semanticModel.GetSymbolInfo(DirectCast(node, QueryClauseSyntax)) Else Throw New NotSupportedException("Type of syntax node is not supported by GetSemanticInfo") End If Assert.NotNull(symbolInfo) summary.Symbol = DirectCast(symbolInfo.Symbol, Symbol) summary.CandidateReason = symbolInfo.CandidateReason summary.CandidateSymbols = symbolInfo.CandidateSymbols summary.AllSymbols = symbolInfo.GetAllSymbols() If TypeOf node Is IdentifierNameSyntax Then summary.Alias = semanticModel.GetAliasInfo(DirectCast(node, IdentifierNameSyntax)) End If Return summary End Function <Extension()> Public Function GetSpeculativeSemanticInfoSummary(model As SemanticModel, position As Integer, expression As ExpressionSyntax, bindingOption As SpeculativeBindingOption) As SemanticInfoSummary Dim summary As New SemanticInfoSummary ' The information that is available varies by the type of the syntax node. Dim semanticModel = DirectCast(model, VBSemanticModel) Dim symbolInfo As SymbolInfo symbolInfo = semanticModel.GetSpeculativeSymbolInfo(position, expression, bindingOption) summary.MemberGroup = semanticModel.GetSpeculativeMemberGroup(position, expression) summary.ConstantValue = semanticModel.GetSpeculativeConstantValue(position, expression) Dim typeInfo = semanticModel.GetSpeculativeTypeInfo(position, expression, bindingOption) summary.Type = DirectCast(typeInfo.Type, TypeSymbol) summary.ConvertedType = DirectCast(typeInfo.ConvertedType, TypeSymbol) summary.ImplicitConversion = semanticModel.GetSpeculativeConversion(position, expression, bindingOption) Assert.NotNull(symbolInfo) summary.Symbol = DirectCast(symbolInfo.Symbol, Symbol) summary.CandidateReason = symbolInfo.CandidateReason summary.CandidateSymbols = symbolInfo.CandidateSymbols summary.AllSymbols = symbolInfo.GetAllSymbols() If TypeOf expression Is IdentifierNameSyntax Then summary.Alias = semanticModel.GetSpeculativeAliasInfo(position, DirectCast(expression, IdentifierNameSyntax), bindingOption) End If Return summary End Function Public Function GetSemanticInfoSummary(compilation As Compilation, node As SyntaxNode) As SemanticInfoSummary Dim tree = node.SyntaxTree Dim semanticModel = DirectCast(compilation.GetSemanticModel(tree), VBSemanticModel) Return GetSemanticInfoSummary(semanticModel, node) End Function Public Function GetSemanticInfoSummary(Of TSyntax As SyntaxNode)(compilation As Compilation, fileName As String, Optional which As Integer = 0) As SemanticInfoSummary Dim node As TSyntax = CompilationUtils.FindBindingText(Of TSyntax)(compilation, fileName, which) Return GetSemanticInfoSummary(compilation, node) End Function Public Function GetPreprocessingSymbolInfo(compilation As Compilation, fileName As String, Optional which As Integer = 0) As VisualBasicPreprocessingSymbolInfo Dim node = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, fileName, which) Dim semanticModel = DirectCast(compilation.GetSemanticModel(node.SyntaxTree), VBSemanticModel) Return semanticModel.GetPreprocessingSymbolInfo(node) End Function Public Function GetSemanticModel(compilation As Compilation, fileName As String) As VBSemanticModel Dim tree = (From t In compilation.SyntaxTrees Where t.FilePath = fileName).Single() Return DirectCast(compilation.GetSemanticModel(tree), VBSemanticModel) End Function ''' <summary> ''' Create a parse tree from the data inside an XElement ''' </summary> ''' <param name="programElement">The program element to create the tree from according to the following schema ''' &lt;file name="filename.vb[optional]"&gt; ''' source ''' &lt;/file&gt; ''' </param> Public Function CreateParseTree(programElement As XElement) As SyntaxTree Return VisualBasicSyntaxTree.ParseText(FilterString(programElement.Value), path:=If(programElement.@name, ""), encoding:=Encoding.UTF8) End Function ''' <summary> ''' Create a parse tree from the data inside an XElement ''' </summary> ''' <param name="programElement">The program element to create the tree from according to the following schema ''' &lt;file name="filename.vb[optional]"&gt; ''' source ''' &lt;/file&gt; ''' </param> Public Function CreateParseTreeAndSpans(programElement As XElement, Optional parseOptions As VisualBasicParseOptions = Nothing) As (tree As SyntaxTree, spans As IList(Of TextSpan)) Dim codeWithMarker As String = FilterString(programElement.Value) Dim codeWithoutMarker As String = Nothing Dim spans As ImmutableArray(Of TextSpan) = Nothing MarkupTestFile.GetSpans(codeWithMarker, codeWithoutMarker, spans) Dim text = SourceText.From(codeWithoutMarker, Encoding.UTF8) Return (VisualBasicSyntaxTree.ParseText(text, parseOptions, If(programElement.@name, "")), spans) End Function ' Find a node inside a tree. Public Function FindTokenFromText(tree As SyntaxTree, textToFind As String) As SyntaxToken Dim text As String = tree.GetText().ToString() Dim position As Integer = text.IndexOf(textToFind, StringComparison.Ordinal) Dim node = tree.GetRoot().FindToken(position) Return node End Function ' Find a position inside a tree. Public Function FindPositionFromText(tree As SyntaxTree, textToFind As String) As Integer Dim text As String = tree.GetText().ToString() Dim position As Integer = text.IndexOf(textToFind, StringComparison.Ordinal) Return position End Function ' Find a node inside a tree. Public Function FindNodeFromText(tree As SyntaxTree, textToFind As String) As SyntaxNode Return FindTokenFromText(tree, textToFind).Parent End Function ' Find a node of a type inside a tree. Public Function FindNodeOfTypeFromText(Of TNode As SyntaxNode)(tree As SyntaxTree, textToFind As String) As TNode Dim node = FindNodeFromText(tree, textToFind) While node IsNot Nothing AndAlso Not TypeOf node Is TNode node = node.Parent End While Return DirectCast(node, TNode) End Function ' Get the syntax tree with a given name. Public Function GetTree(compilation As Compilation, name As String) As SyntaxTree Return (From t In compilation.SyntaxTrees Where t.FilePath = name).First() End Function ' Get the symbol with a given full name. It must be unambiguous. Public Function GetSymbolByFullName(compilation As VisualBasicCompilation, methodName As String) As Symbol Dim names = New List(Of String)() Dim offset = 0 While True ' Find the next "."c separator but skip the first character since ' the name may begin with "."c (in ".ctor" for instance). Dim separator = methodName.IndexOf("."c, offset + 1) If separator < 0 Then names.Add(methodName.Substring(offset)) Exit While End If names.Add(methodName.Substring(offset, separator - offset)) offset = separator + 1 End While Dim currentSymbol As Symbol = compilation.GlobalNamespace For Each name In names Assert.True(TypeOf currentSymbol Is NamespaceOrTypeSymbol, String.Format("{0} does not have members", currentSymbol.ToDisplayString(SymbolDisplayFormat.TestFormat))) Dim currentContainer = DirectCast(currentSymbol, NamespaceOrTypeSymbol) Dim members = currentContainer.GetMembers(name) Assert.True(members.Any(), String.Format("No members named {0} inside {1}", name, currentSymbol.ToDisplayString(SymbolDisplayFormat.TestFormat))) Assert.True(members.Length() <= 1, String.Format("Multiple members named {0} inside {1}", name, currentSymbol.ToDisplayString(SymbolDisplayFormat.TestFormat))) currentSymbol = members.First() Next Return currentSymbol End Function ' Check that the compilation has no parse or declaration errors. Public Sub AssertNoDeclarationDiagnostics(compilation As VisualBasicCompilation, Optional suppressInfos As Boolean = True) AssertNoDiagnostics(compilation.GetDeclarationDiagnostics(), suppressInfos) End Sub ''' <remarks> ''' Does not consider INFO diagnostics. ''' </remarks> <Extension()> Public Sub AssertNoDiagnostics(compilation As VisualBasicCompilation, Optional suppressInfos As Boolean = True) AssertNoDiagnostics(compilation.GetDiagnostics(), suppressInfos) End Sub ' Check that the compilation has no parse, declaration errors/warnings, or compilation errors/warnings. ''' <remarks> ''' Does not consider INFO and HIDDEN diagnostics. ''' </remarks> Private Sub AssertNoDiagnostics(diags As ImmutableArray(Of Diagnostic), suppressInfos As Boolean) If suppressInfos Then diags = diags.WhereAsArray(Function(d) d.Severity > DiagnosticSeverity.Info) End If If diags.Length > 0 Then Console.WriteLine("Unexpected diagnostics found:") For Each d In diags Console.WriteLine(ErrorText(d)) Next Assert.True(False, "Should not have any diagnostics") End If End Sub ' Check that the compilation has no parse, declaration errors, or compilation errors. <Extension()> Public Sub AssertNoErrors(compilation As Compilation) AssertNoErrors(compilation.GetDiagnostics()) End Sub ' Check that the compilation has no parse, declaration errors, or compilation errors. <Extension()> Public Sub AssertNoErrors(errors As ImmutableArray(Of Diagnostic)) Dim diags As ImmutableArray(Of Diagnostic) = errors.WhereAsArray(Function(e) e.Severity = DiagnosticSeverity.Error) If diags.Length > 0 Then Console.WriteLine("Unexpected errors found:") For Each d In diags Console.WriteLine(ErrorText(d)) Next Assert.True(False, "Should not have any errors") End If End Sub ''' <summary> ''' Check that a compilation has these declaration errors. ''' </summary> ''' <param name="compilation"></param> ''' <param name="errs">Expected errors according to this schema ''' &lt;error&gt;[full errors text]&lt;/error&gt;</param> ''' <param name="suppressInfos">True to ignore info-severity diagnostics.</param> ''' <remarks></remarks> <Extension()> Public Sub AssertTheseDeclarationDiagnostics(compilation As VisualBasicCompilation, errs As XElement, Optional suppressInfos As Boolean = True) AssertTheseDiagnostics(compilation.GetDeclarationDiagnostics(), errs, suppressInfos) End Sub <Extension()> Public Sub AssertTheseParseDiagnostics(compilation As VisualBasicCompilation, errs As XElement, Optional suppressInfos As Boolean = True) AssertTheseDiagnostics(compilation.GetParseDiagnostics(), errs, suppressInfos) End Sub ''' <summary> ''' Check that a compilation has these errors at Compile stage or before. ''' </summary> ''' <param name="compilation"></param> ''' <param name="errs">Expected errors according to this schema ''' &lt;error&gt;[full errors text]&lt;/error&gt;</param> ''' <param name="suppressInfos">True to ignore info-severity diagnostics.</param> ''' <remarks></remarks> <Extension()> Public Sub AssertTheseCompileDiagnostics(compilation As Compilation, Optional errs As XElement = Nothing, Optional suppressInfos As Boolean = True) If errs Is Nothing Then errs = <errors/> End If AssertTheseDiagnostics(DirectCast(compilation, VisualBasicCompilation).GetDiagnostics(CompilationStage.Compile), errs, suppressInfos) End Sub ''' <summary> ''' Check that a compilation has these errors during Emit. ''' </summary> ''' <param name="compilation"></param> ''' <param name="errs">Expected errors according to this schema ''' &lt;error&gt;[full errors text]&lt;/error&gt;</param> ''' <param name="suppressInfos">True to ignore info-severity diagnostics.</param> ''' <remarks></remarks> <Extension()> Public Sub AssertTheseEmitDiagnostics(compilation As Compilation, Optional errs As XElement = Nothing, Optional suppressInfos As Boolean = True) If errs Is Nothing Then errs = <errors/> End If Using assemblyStream As New MemoryStream() Using pdbStream As New MemoryStream() Dim diagnostics = compilation.Emit(assemblyStream, pdbStream:=pdbStream).Diagnostics AssertTheseDiagnostics(diagnostics, errs, suppressInfos) End Using End Using End Sub <Extension()> Public Sub AssertTheseDiagnostics(tree As SyntaxTree, errs As XElement, Optional suppressInfos As Boolean = True) AssertTheseDiagnostics(tree.GetDiagnostics().AsImmutable(), errs, suppressInfos) End Sub ''' <summary> ''' Check that a compilation has these declaration or compilation errors. ''' </summary> ''' <param name="compilation"></param> ''' <param name="errs">Expected errors according to this schema ''' &lt;error&gt;[full errors text]&lt;/error&gt;</param> ''' <param name="suppressInfos">True to ignore info-severity diagnostics.</param> ''' <remarks></remarks> <Extension()> Public Sub AssertTheseDiagnostics(compilation As Compilation, Optional errs As XElement = Nothing, Optional suppressInfos As Boolean = True) If errs Is Nothing Then errs = <errors/> End If AssertTheseDiagnostics(DirectCast(compilation, VisualBasicCompilation).GetDiagnostics(CompilationStage.Compile), errs, suppressInfos) End Sub <Extension()> Public Sub AssertTheseDiagnostics(compilation As Compilation, errs As XCData, Optional suppressInfos As Boolean = True) AssertTheseDiagnostics(DirectCast(compilation, VisualBasicCompilation).GetDiagnostics(CompilationStage.Compile), errs, suppressInfos) End Sub ' Check that a compilation has these declaration or compilation errors. <Extension()> Public Sub AssertTheseDiagnostics(compilation As Compilation, errs As String, Optional suppressInfos As Boolean = True) AssertTheseDiagnostics(DirectCast(compilation, VisualBasicCompilation).GetDiagnostics(CompilationStage.Compile), errs, suppressInfos) End Sub ''' <param name="errors"></param> ''' <param name="errs">Expected errors according to this schema ''' &lt;expected&gt;[full errors text]&lt;/expected&gt;</param> ''' <param name="suppressInfos">True to ignore info-severity diagnostics.</param> ''' <remarks></remarks> <Extension()> Public Sub AssertTheseDiagnostics(errors As ImmutableArray(Of Diagnostic), errs As XElement, Optional suppressInfos As Boolean = True) If errs Is Nothing Then errs = <errors/> End If Dim expectedText = FilterString(errs.Value) AssertTheseDiagnostics(errors, expectedText, suppressInfos) End Sub <Extension()> Public Sub AssertTheseDiagnostics(errors As ImmutableArray(Of Diagnostic), errs As XCData, Optional suppressInfos As Boolean = True) Dim expectedText = FilterString(errs.Value) AssertTheseDiagnostics(errors, expectedText, suppressInfos) End Sub Private Sub AssertTheseDiagnostics(errors As ImmutableArray(Of Diagnostic), expectedText As String, suppressInfos As Boolean) Dim actualText = DumpAllDiagnostics(errors.ToArray(), suppressInfos) If expectedText <> actualText Then Dim messages = ParserTestUtilities.PooledStringBuilderPool.Allocate() With messages.Builder .AppendLine() If actualText.StartsWith(expectedText, StringComparison.Ordinal) AndAlso actualText.Substring(expectedText.Length).Trim().Length > 0 Then .AppendLine("UNEXPECTED ERROR MESSAGES:") .AppendLine(actualText.Substring(expectedText.Length)) Assert.True(False, .ToString()) Else Dim expectedLines = expectedText.Split({vbCrLf, vbLf}, StringSplitOptions.RemoveEmptyEntries) Dim actualLines = actualText.Split({vbCrLf, vbLf}, StringSplitOptions.RemoveEmptyEntries) Dim appendedLines As Integer = 0 .AppendLine("MISSING ERROR MESSAGES:") For Each l In expectedLines If Not actualLines.Contains(l) Then .AppendLine(l) appendedLines += 1 End If Next .AppendLine("UNEXPECTED ERROR MESSAGES:") For Each l In actualLines If Not expectedLines.Contains(l) Then .AppendLine(l) appendedLines += 1 End If Next If appendedLines > 0 Then Assert.True(False, .ToString()) Else CompareLineByLine(expectedText, actualText) End If End If End With messages.Free() End If End Sub Private Sub CompareLineByLine(expected As String, actual As String) Dim expectedReader = New StringReader(expected) Dim actualReader = New StringReader(actual) Dim expectedPooledBuilder = PooledStringBuilderPool.Allocate() Dim actualPooledBuilder = PooledStringBuilderPool.Allocate() Dim expectedBuilder = expectedPooledBuilder.Builder Dim actualBuilder = actualPooledBuilder.Builder Dim expectedLine = expectedReader.ReadLine() Dim actualLine = actualReader.ReadLine() While expectedLine IsNot Nothing AndAlso actualLine IsNot Nothing If Not expectedLine.Equals(actualLine) Then expectedBuilder.AppendLine("<! " & expectedLine) actualBuilder.AppendLine("!> " & actualLine) Else expectedBuilder.AppendLine(expectedLine) actualBuilder.AppendLine(actualLine) End If expectedLine = expectedReader.ReadLine() actualLine = actualReader.ReadLine() End While While expectedLine IsNot Nothing expectedBuilder.AppendLine("<! " & expectedLine) expectedLine = expectedReader.ReadLine() End While While actualLine IsNot Nothing actualBuilder.AppendLine("!> " & actualLine) actualLine = actualReader.ReadLine() End While Assert.Equal(expectedPooledBuilder.ToStringAndFree(), actualPooledBuilder.ToStringAndFree()) End Sub ' There are certain cases where multiple distinct errors are ' reported where the error code and text span are the same. When ' sorting such cases, we should preserve the original order. Private Structure DiagnosticAndIndex Public Sub New(diagnostic As Diagnostic, index As Integer) Me.Diagnostic = diagnostic Me.Index = index End Sub Public ReadOnly Diagnostic As Diagnostic Public ReadOnly Index As Integer End Structure Private Function DumpAllDiagnostics(allDiagnostics As Diagnostic(), suppressInfos As Boolean) As String Return DumpAllDiagnostics(allDiagnostics.ToImmutableArray(), suppressInfos) End Function Friend Function DumpAllDiagnostics(allDiagnostics As ImmutableArray(Of Diagnostic), suppressInfos As Boolean) As String Dim diagnosticsAndIndices(allDiagnostics.Length - 1) As DiagnosticAndIndex For i = 0 To allDiagnostics.Length - 1 diagnosticsAndIndices(i) = New DiagnosticAndIndex(allDiagnostics(i), i) Next Array.Sort(diagnosticsAndIndices, Function(diag1, diag2) CompareErrors(diag1, diag2)) Dim builder = PooledStringBuilderPool.Allocate() With builder.Builder For Each e In diagnosticsAndIndices If Not suppressInfos OrElse e.Diagnostic.Severity > DiagnosticSeverity.Info Then .Append(ErrorText(e.Diagnostic)) End If Next End With Return builder.ToStringAndFree() End Function ' Get the text of a diagnostic. For source error, includes the text of the line itself, with the ' span underlined. Private Function ErrorText(e As Diagnostic) As String Dim message = e.Id + ": " + e.GetMessage(EnsureEnglishUICulture.PreferredOrNull) If e.Location.IsInSource Then Dim sourceLocation = e.Location Dim offsetInLine As Integer = 0 Dim lineText As String = GetLineText(sourceLocation.SourceTree.GetText(), sourceLocation.SourceSpan.Start, offsetInLine) Return message + Environment.NewLine + lineText + Environment.NewLine + New String(" "c, offsetInLine) + New String("~"c, Math.Max(Math.Min(sourceLocation.SourceSpan.Length, lineText.Length - offsetInLine + 1), 1)) + Environment.NewLine ElseIf e.Location.IsInMetadata Then Return message + Environment.NewLine + String.Format("in metadata assembly '{0}'" + Environment.NewLine, e.Location.MetadataModule.ContainingAssembly.Identity.Name) Else Return message + Environment.NewLine End If End Function ' Get the text of a line that contains the offset, and return the offset within that line. Private Function GetLineText(text As SourceText, position As Integer, ByRef offsetInLine As Integer) As String Dim textLine = text.Lines.GetLineFromPosition(position) offsetInLine = position - textLine.Start Return textLine.ToString() End Function Private Function CompareErrors(diagAndIndex1 As DiagnosticAndIndex, diagAndIndex2 As DiagnosticAndIndex) As Integer ' Sort by no location, then source, then metadata. Sort within each group. Dim diag1 = diagAndIndex1.Diagnostic Dim diag2 = diagAndIndex2.Diagnostic Dim loc1 = diag1.Location Dim loc2 = diag2.Location If Not (loc1.IsInSource Or loc1.IsInMetadata) Then If Not (loc2.IsInSource Or loc2.IsInMetadata) Then ' Both have no location. Sort by code, then by message. If diag1.Code < diag2.Code Then Return -1 If diag1.Code > diag2.Code Then Return 1 Return diag1.GetMessage(EnsureEnglishUICulture.PreferredOrNull).CompareTo(diag2.GetMessage(EnsureEnglishUICulture.PreferredOrNull)) Else Return -1 End If ElseIf Not (loc2.IsInSource Or loc2.IsInMetadata) Then Return 1 ElseIf loc1.IsInSource AndAlso loc2.IsInSource Then ' source by tree, then span start, then span end, then error code, then message Dim sourceTree1 = loc1.SourceTree Dim sourceTree2 = loc2.SourceTree If sourceTree1.FilePath <> sourceTree2.FilePath Then Return sourceTree1.FilePath.CompareTo(sourceTree2.FilePath) If loc1.SourceSpan.Start < loc2.SourceSpan.Start Then Return -1 If loc1.SourceSpan.Start > loc2.SourceSpan.Start Then Return 1 If loc1.SourceSpan.Length < loc2.SourceSpan.Length Then Return -1 If loc1.SourceSpan.Length > loc2.SourceSpan.Length Then Return 1 If diag1.Code < diag2.Code Then Return -1 If diag1.Code > diag2.Code Then Return 1 Return diag1.GetMessage(EnsureEnglishUICulture.PreferredOrNull).CompareTo(diag2.GetMessage(EnsureEnglishUICulture.PreferredOrNull)) ElseIf loc1.IsInMetadata AndAlso loc2.IsInMetadata Then ' sort by assembly name, then by error code Dim name1 = loc1.MetadataModule.ContainingAssembly.Name Dim name2 = loc2.MetadataModule.ContainingAssembly.Name If name1 <> name2 Then Return name1.CompareTo(name2) If diag1.Code < diag2.Code Then Return -1 If diag1.Code > diag2.Code Then Return 1 Return diag1.GetMessage(EnsureEnglishUICulture.PreferredOrNull).CompareTo(diag2.GetMessage(EnsureEnglishUICulture.PreferredOrNull)) ElseIf loc1.IsInSource Then Return -1 ElseIf loc2.IsInSource Then Return 1 End If ' Preserve original order. Return diagAndIndex1.Index - diagAndIndex2.Index End Function Public Function GetTypeSymbol(compilation As Compilation, semanticModel As SemanticModel, treeName As String, stringInDecl As String) As INamedTypeSymbol Dim tree = CompilationUtils.GetTree(compilation, treeName) Dim node = CompilationUtils.FindTokenFromText(tree, stringInDecl).Parent While Not (TypeOf node Is TypeStatementSyntax) node = node.Parent Assert.NotNull(node) End While Return DirectCast(semanticModel, VBSemanticModel).GetDeclaredSymbol(DirectCast(node, TypeStatementSyntax)) End Function Public Function GetEnumSymbol(compilation As Compilation, semanticModel As SemanticModel, treeName As String, stringInDecl As String) As INamedTypeSymbol Dim tree = CompilationUtils.GetTree(compilation, treeName) Dim node = CompilationUtils.FindTokenFromText(tree, stringInDecl).Parent While Not (TypeOf node Is EnumStatementSyntax) node = node.Parent Assert.NotNull(node) End While Return DirectCast(semanticModel, VBSemanticModel).GetDeclaredSymbol(DirectCast(node, EnumStatementSyntax)) End Function Public Function GetDelegateSymbol(compilation As Compilation, semanticModel As SemanticModel, treeName As String, stringInDecl As String) As NamedTypeSymbol Dim tree = CompilationUtils.GetTree(compilation, treeName) Dim node = CompilationUtils.FindTokenFromText(tree, stringInDecl).Parent While Not (TypeOf node Is MethodBaseSyntax) node = node.Parent Assert.NotNull(node) End While Return DirectCast(semanticModel.GetDeclaredSymbol(DirectCast(node, MethodBaseSyntax)), NamedTypeSymbol) End Function Public Function GetTypeSymbol(compilation As Compilation, treeName As String, stringInDecl As String, Optional isDistinct As Boolean = True) As List(Of INamedTypeSymbol) Dim tree = CompilationUtils.GetTree(compilation, treeName) Dim bindings = DirectCast(compilation.GetSemanticModel(tree), VBSemanticModel) Dim text As String = tree.GetText().ToString() Dim pos = 0 Dim node As SyntaxNode Dim symType = New List(Of INamedTypeSymbol) Do pos = text.IndexOf(stringInDecl, pos + 1, StringComparison.Ordinal) If pos >= 0 Then node = tree.GetRoot().FindToken(pos).Parent While Not (TypeOf node Is TypeStatementSyntax OrElse TypeOf node Is EnumStatementSyntax) If node Is Nothing Then Exit While End If node = node.Parent End While If Not node Is Nothing Then If TypeOf node Is TypeStatementSyntax Then Dim temp = bindings.GetDeclaredSymbol(DirectCast(node, TypeStatementSyntax)) symType.Add(temp) Else Dim temp = bindings.GetDeclaredSymbol(DirectCast(node, EnumStatementSyntax)) symType.Add(temp) End If End If Else Exit Do End If Loop If (isDistinct) Then symType = (From temp In symType Distinct Select temp Order By temp.ToDisplayString()).ToList() Else symType = (From temp In symType Select temp Order By temp.ToDisplayString()).ToList() End If Return symType End Function Public Function VerifyGlobalNamespace(compilation As Compilation, treeName As String, symbolName As String, ExpectedDispName() As String, isDistinct As Boolean) As List(Of INamedTypeSymbol) Dim tree = CompilationUtils.GetTree(compilation, treeName) Dim bindings1 = compilation.GetSemanticModel(tree) Dim symbols = GetTypeSymbol(compilation, treeName, symbolName, isDistinct) Assert.Equal(ExpectedDispName.Count, symbols.Count) ExpectedDispName = (From temp In ExpectedDispName Select temp Order By temp).ToArray() Dim count = 0 For Each item In symbols Assert.NotNull(item) Assert.Equal(ExpectedDispName(count), item.ToDisplayString()) count += 1 Next Return symbols End Function Public Function VerifyGlobalNamespace(compilation As VisualBasicCompilation, treeName As String, symbolName As String, ParamArray expectedDisplayNames() As String) As List(Of INamedTypeSymbol) Return VerifyGlobalNamespace(compilation, treeName, symbolName, expectedDisplayNames, True) End Function Public Function VerifyIsGlobal(globalNS1 As ISymbol, Optional expected As Boolean = True) As NamespaceSymbol Dim nsSymbol = DirectCast(globalNS1, NamespaceSymbol) Assert.NotNull(nsSymbol) If (expected) Then Assert.True(nsSymbol.IsGlobalNamespace) Else Assert.False(nsSymbol.IsGlobalNamespace) End If Return nsSymbol End Function Public Sub CheckSymbols(Of TSymbol As ISymbol)(symbols As ImmutableArray(Of TSymbol), ParamArray descriptions As String()) Assert.Equal(symbols.Length, descriptions.Length) Dim symbolDescriptions As String() = (From s In symbols Select s.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)).ToArray() Array.Sort(descriptions) Array.Sort(symbolDescriptions) For i = 0 To descriptions.Length - 1 Assert.Equal(symbolDescriptions(i), descriptions(i)) Next End Sub Public Sub CheckSymbols(Of TSymbol As ISymbol)(symbols As TSymbol(), ParamArray descriptions As String()) CheckSymbols(symbols.AsImmutableOrNull(), descriptions) End Sub Public Sub CheckSymbol(symbol As ISymbol, description As String) Assert.Equal(symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat), description) End Sub Public Function SortAndMergeStrings(ParamArray strings As String()) As String Array.Sort(strings) Dim builder = PooledStringBuilderPool.Allocate() With builder.Builder For Each item In strings If .Length > 0 Then .AppendLine() End If .Append(item) Next End With Return builder.ToStringAndFree() End Function Public Sub CheckSymbolsUnordered(Of TSymbol As ISymbol)(symbols As ImmutableArray(Of TSymbol), ParamArray descriptions As String()) Assert.Equal(symbols.Length, descriptions.Length) Assert.Equal(SortAndMergeStrings(descriptions), SortAndMergeStrings(symbols.Select(Function(s) s.ToDisplayString()).ToArray())) End Sub <Extension> Friend Function LookupNames(model As SemanticModel, position As Integer, Optional container As INamespaceOrTypeSymbol = Nothing, Optional namespacesAndTypesOnly As Boolean = False) As List(Of String) Dim result = If(namespacesAndTypesOnly, model.LookupNamespacesAndTypes(position, container), model.LookupSymbols(position, container)) Return result.Select(Function(s) s.Name).Distinct().ToList() End Function End Module
' 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.IO Imports System.Runtime.CompilerServices Imports System.Runtime.InteropServices Imports System.Text Imports System.Xml.Linq Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Roslyn.Test.Utilities Imports Roslyn.Test.Utilities.TestBase Imports Roslyn.Test.Utilities.TestMetadata Imports Xunit Friend Module CompilationUtils Private Function ParseSources(source As IEnumerable(Of String), parseOptions As VisualBasicParseOptions) As IEnumerable(Of SyntaxTree) Return source.Select(Function(s) VisualBasicSyntaxTree.ParseText(s, parseOptions)) End Function Public Function CreateCompilation( source As BasicTestSource, Optional references As IEnumerable(Of MetadataReference) = Nothing, Optional options As VisualBasicCompilationOptions = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing, Optional targetFramework As TargetFramework = TargetFramework.StandardAndVBRuntime, Optional assemblyName As String = Nothing) As VisualBasicCompilation references = TargetFrameworkUtil.GetReferences(targetFramework, references) Return CreateEmptyCompilation(source, references, options, parseOptions, assemblyName) End Function Public Function CreateEmptyCompilation( source As BasicTestSource, Optional references As IEnumerable(Of MetadataReference) = Nothing, Optional options As VisualBasicCompilationOptions = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing, Optional assemblyName As String = Nothing) As VisualBasicCompilation If options Is Nothing Then options = TestOptions.ReleaseDll End If ' Using single-threaded build if debugger attached, to simplify debugging. If Debugger.IsAttached Then options = options.WithConcurrentBuild(False) End If Dim trees = source.GetSyntaxTrees(parseOptions, assemblyName) Dim createCompilationLambda = Function() Return VisualBasicCompilation.Create( If(assemblyName, GetUniqueName()), trees, references, options) End Function ValidateCompilation(createCompilationLambda) Return createCompilationLambda() End Function Private Sub ValidateCompilation(createCompilationLambda As Func(Of VisualBasicCompilation)) CompilationExtensions.ValidateIOperations(createCompilationLambda) VerifyUsedAssemblyReferences(createCompilationLambda) End Sub Private Sub VerifyUsedAssemblyReferences(createCompilationLambda As Func(Of VisualBasicCompilation)) If Not CompilationExtensions.EnableVerifyUsedAssemblies Then Return End If Dim comp = createCompilationLambda() Dim used = comp.GetUsedAssemblyReferences() Dim compileDiagnostics = comp.GetDiagnostics() Dim emitDiagnostics = comp.GetEmitDiagnostics() Dim resolvedReferences = comp.References.Where(Function(r) r.Properties.Kind = MetadataImageKind.Assembly) If Not compileDiagnostics.Any(Function(d) d.DefaultSeverity = DiagnosticSeverity.Error) Then If resolvedReferences.Count() > used.Length Then AssertSubset(used, resolvedReferences) If Not compileDiagnostics.Any(Function(d) d.Code = ERRID.HDN_UnusedImportClause OrElse d.Code = ERRID.HDN_UnusedImportStatement) Then Dim comp2 = comp.RemoveAllReferences().AddReferences(used.Concat(comp.References.Where(Function(r) r.Properties.Kind = MetadataImageKind.Module))) comp2.GetEmitDiagnostics().Verify( emitDiagnostics.Select(Function(d) New DiagnosticDescription(d, errorCodeOnly:=False, includeDefaultSeverity:=False, includeEffectiveSeverity:=False)).ToArray()) End If Else AssertEx.Equal(resolvedReferences, used) End If Else AssertSubset(used, resolvedReferences) End If End Sub Private Sub AssertSubset(used As ImmutableArray(Of MetadataReference), resolvedReferences As IEnumerable(Of MetadataReference)) For Each reference In used Assert.Contains(reference, resolvedReferences) Next End Sub Public Function CreateEmptyCompilation( identity As AssemblyIdentity, source As BasicTestSource, Optional references As MetadataReference() = Nothing, Optional options As VisualBasicCompilationOptions = Nothing) As VisualBasicCompilation Dim trees = source.GetSyntaxTrees() Dim createCompilationLambda = Function() Return VisualBasicCompilation.Create(identity.Name, trees, references, options) End Function ValidateCompilation(createCompilationLambda) Dim c = createCompilationLambda() Assert.NotNull(c.Assembly) ' force creation of SourceAssemblySymbol DirectCast(c.Assembly, SourceAssemblySymbol).m_lazyIdentity = identity Return c End Function Public Function CreateCompilationWithMscorlib40( source As BasicTestSource, Optional references As IEnumerable(Of MetadataReference) = Nothing, Optional options As VisualBasicCompilationOptions = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing, Optional assemblyName As String = Nothing) As VisualBasicCompilation Return CreateCompilation(source, references, options, parseOptions, TargetFramework.Mscorlib40, assemblyName) End Function Public Function CreateCompilationWithMscorlib45( source As BasicTestSource, Optional references As IEnumerable(Of MetadataReference) = Nothing, Optional options As VisualBasicCompilationOptions = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing, Optional assemblyName As String = Nothing) As VisualBasicCompilation Return CreateCompilation(source, references, options, parseOptions, TargetFramework.Mscorlib45, assemblyName) End Function Public Function CreateCompilationWithMscorlib45AndVBRuntime( source As BasicTestSource, Optional references As IEnumerable(Of MetadataReference) = Nothing, Optional options As VisualBasicCompilationOptions = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing, Optional assemblyName As String = Nothing) As VisualBasicCompilation Return CreateCompilation(source, references, options, parseOptions, TargetFramework.Mscorlib45AndVBRuntime, assemblyName) End Function Public Function CreateCompilationWithWinRt(source As XElement) As VisualBasicCompilation Return CreateEmptyCompilationWithReferences(source, WinRtRefs) End Function Public Function CreateCompilationWithMscorlib40AndReferences(source As XElement, references As IEnumerable(Of MetadataReference), Optional options As VisualBasicCompilationOptions = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing) As VisualBasicCompilation Return CreateEmptyCompilationWithReferences(source, {CType(Net40.mscorlib, MetadataReference)}.Concat(references), options, parseOptions:=parseOptions) End Function ''' <summary> ''' ''' </summary> ''' <param name="source">The sources compile according to the following schema ''' &lt;compilation name="assemblyname[optional]"&gt; ''' &lt;file name="file1.vb[optional]"&gt; ''' source ''' &lt;/file&gt; ''' &lt;/compilation&gt; ''' </param> Public Function CreateCompilationWithMscorlib40(source As XElement, outputKind As OutputKind, Optional parseOptions As VisualBasicParseOptions = Nothing) As VisualBasicCompilation Return CreateEmptyCompilationWithReferences(source, {Net40.mscorlib}, New VisualBasicCompilationOptions(outputKind), parseOptions:=parseOptions) End Function ''' <summary> ''' ''' </summary> ''' <param name="source">The sources compile according to the following schema ''' &lt;compilation name="assemblyname[optional]"&gt; ''' &lt;file name="file1.vb[optional]"&gt; ''' source ''' &lt;/file&gt; ''' &lt;/compilation&gt; ''' </param> Public Function CreateCompilationWithMscorlib40AndVBRuntime( source As XElement, Optional additionalRefs As MetadataReference() = Nothing, Optional options As VisualBasicCompilationOptions = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing, Optional assemblyName As String = Nothing) As VisualBasicCompilation If additionalRefs Is Nothing Then additionalRefs = {} Dim references = {CType(Net40.mscorlib, MetadataReference), Net40.System, Net40.MicrosoftVisualBasic}.Concat(additionalRefs) Return CreateEmptyCompilationWithReferences(source, references, options, parseOptions:=parseOptions, assemblyName:=assemblyName) End Function Public Function CreateCompilationWithMscorlib40AndVBRuntime(source As IEnumerable(Of SyntaxTree), options As VisualBasicCompilationOptions, Optional assemblyName As String = Nothing) As VisualBasicCompilation Dim references = {MscorlibRef, SystemRef, MsvbRef} Return CreateEmptyCompilation(source.ToArray(), references, options:=options, assemblyName:=assemblyName) End Function Public Function CreateCompilationWithMscorlib40AndVBRuntime(source As XElement, options As VisualBasicCompilationOptions) As VisualBasicCompilation Return CreateCompilationWithMscorlib40AndVBRuntime(source, Nothing, options, parseOptions:=If(options Is Nothing, Nothing, options.ParseOptions)) End Function Public ReadOnly XmlReferences As MetadataReference() = {SystemRef, SystemCoreRef, SystemXmlRef, SystemXmlLinqRef} Public ReadOnly Net40XmlReferences As MetadataReference() = {Net40.SystemCore, Net40.SystemXml, Net40.SystemXmlLinq} Public ReadOnly Net451XmlReferences As MetadataReference() = {Net451.SystemCore, Net451.SystemXml, Net451.SystemXmlLinq} ''' <summary> ''' ''' </summary> ''' <param name="source">The sources compile according to the following schema ''' &lt;compilation name="assemblyname[optional]"&gt; ''' &lt;file name="file1.vb[optional]"&gt; ''' source ''' &lt;/file&gt; ''' &lt;/compilation&gt; ''' </param> Public Function CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( source As XElement, Optional references As IEnumerable(Of MetadataReference) = Nothing, Optional options As VisualBasicCompilationOptions = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing) As VisualBasicCompilation If references Is Nothing Then references = {} Dim allReferences = {CType(Net40.mscorlib, MetadataReference), Net40.System, Net40.MicrosoftVisualBasic}.Concat(references) If parseOptions Is Nothing AndAlso options IsNot Nothing Then parseOptions = options.ParseOptions End If Return CreateEmptyCompilationWithReferences(source, allReferences, options, parseOptions:=parseOptions) End Function ''' <summary> ''' ''' </summary> ''' <param name="source">The sources compile according to the following schema ''' &lt;compilation name="assemblyname[optional]"&gt; ''' &lt;file name="file1.vb[optional]"&gt; ''' source ''' &lt;/file&gt; ''' &lt;/compilation&gt; ''' </param> Public Function CreateCompilationWithMscorlib45AndVBRuntime( source As XElement, Optional references As IEnumerable(Of MetadataReference) = Nothing, Optional options As VisualBasicCompilationOptions = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing) As VisualBasicCompilation Dim allReferences = {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}.Concat(If(references, {})) Return CreateEmptyCompilationWithReferences(source, allReferences, options, parseOptions:=parseOptions) End Function ''' <summary> ''' ''' </summary> ''' <param name="source">The sources compile according to the following schema ''' &lt;compilation name="assemblyname[optional]"&gt; ''' &lt;file name="file1.vb[optional]"&gt; ''' source ''' &lt;/file&gt; ''' &lt;/compilation&gt; ''' </param> Public Function CreateEmptyCompilationWithReferences(source As XElement, references As IEnumerable(Of MetadataReference), Optional options As VisualBasicCompilationOptions = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing, Optional assemblyName As String = Nothing) As VisualBasicCompilation Dim sourceTrees = ParseSourceXml(source, parseOptions, assemblyName) Return CreateEmptyCompilationWithReferences(sourceTrees, references, options, assemblyName) End Function Public Function ParseSourceXml(sources As XElement, parseOptions As VisualBasicParseOptions, Optional ByRef assemblyName As String = Nothing, Optional ByRef spans As IEnumerable(Of IEnumerable(Of TextSpan)) = Nothing) As IEnumerable(Of SyntaxTree) If sources.@name IsNot Nothing Then assemblyName = sources.@name End If Dim sourcesTreesAndSpans = From f In sources.<file> Select CreateParseTreeAndSpans(f, parseOptions) spans = From t In sourcesTreesAndSpans Select s = t.spans Return From t In sourcesTreesAndSpans Select t.tree End Function Public Function ToSourceTrees(compilationSources As XElement, Optional parseOptions As VisualBasicParseOptions = Nothing) As IEnumerable(Of SyntaxTree) Dim sourcesTreesAndSpans = From f In compilationSources.<file> Select CreateParseTreeAndSpans(f, parseOptions) Return From t In sourcesTreesAndSpans Select t.tree End Function Public Function CreateEmptyCompilationWithReferences(source As SyntaxTree, references As IEnumerable(Of MetadataReference), Optional options As VisualBasicCompilationOptions = Nothing, Optional assemblyName As String = Nothing) As VisualBasicCompilation Return CreateEmptyCompilationWithReferences({source}, references, options, assemblyName) End Function Public Function CreateEmptyCompilationWithReferences(source As IEnumerable(Of SyntaxTree), references As IEnumerable(Of MetadataReference), Optional options As VisualBasicCompilationOptions = Nothing, Optional assemblyName As String = Nothing) As VisualBasicCompilation If options Is Nothing Then options = TestOptions.ReleaseDll ' Using single-threaded build if debugger attached, to simplify debugging. If Debugger.IsAttached Then options = options.WithConcurrentBuild(False) End If End If Dim createCompilationLambda = Function() Return VisualBasicCompilation.Create(If(assemblyName, GetUniqueName()), source, references, options) End Function ValidateCompilation(createCompilationLambda) Return createCompilationLambda() End Function ''' <summary> ''' ''' </summary> ''' <param name="sources">The sources compile according to the following schema ''' &lt;compilation name="assemblyname[optional]"&gt; ''' &lt;file name="file1.vb[optional]"&gt; ''' source ''' &lt;/file&gt; ''' &lt;/compilation&gt; ''' </param> ''' <param name="ilSource"></param> ''' <returns></returns> ''' <remarks></remarks> Public Function CreateCompilationWithCustomILSource(sources As XElement, ilSource As XCData) As VisualBasicCompilation Return CreateCompilationWithCustomILSource(sources, ilSource.Value) End Function ''' <summary> ''' ''' </summary> ''' <param name="sources">The sources compile according to the following schema ''' &lt;compilation name="assemblyname[optional]"&gt; ''' &lt;file name="file1.vb[optional]"&gt; ''' source ''' &lt;/file&gt; ''' &lt;/compilation&gt; ''' </param> ''' <param name="ilSource"></param> ''' <returns></returns> ''' <remarks></remarks> Public Function CreateCompilationWithCustomILSource(sources As XElement, ilSource As String, Optional options As VisualBasicCompilationOptions = Nothing, Optional ByRef spans As IEnumerable(Of IEnumerable(Of TextSpan)) = Nothing, Optional includeVbRuntime As Boolean = False, Optional includeSystemCore As Boolean = False, Optional appendDefaultHeader As Boolean = True, Optional parseOptions As VisualBasicParseOptions = Nothing, Optional additionalReferences As IEnumerable(Of MetadataReference) = Nothing, <Out> Optional ByRef ilReference As MetadataReference = Nothing, <Out> Optional ByRef ilImage As ImmutableArray(Of Byte) = Nothing ) As VisualBasicCompilation Dim references = If(additionalReferences IsNot Nothing, New List(Of MetadataReference)(additionalReferences), New List(Of MetadataReference)) If includeVbRuntime Then references.Add(MsvbRef) End If If includeSystemCore Then references.Add(SystemCoreRef) End If If ilSource Is Nothing Then Return CreateCompilationWithMscorlib40AndReferences(sources, references, options, parseOptions) End If ilReference = CreateReferenceFromIlCode(ilSource, appendDefaultHeader, ilImage) references.Add(ilReference) Return CreateCompilationWithMscorlib40AndReferences(sources, references, options, parseOptions) End Function Public Function CreateReferenceFromIlCode(ilSource As String, Optional appendDefaultHeader As Boolean = True, <Out> Optional ByRef ilImage As ImmutableArray(Of Byte) = Nothing) As MetadataReference Using reference = IlasmUtilities.CreateTempAssembly(ilSource, appendDefaultHeader) ilImage = ImmutableArray.Create(File.ReadAllBytes(reference.Path)) End Using Return MetadataReference.CreateFromImage(ilImage) End Function Public Function GetUniqueName() As String Return Guid.NewGuid().ToString("D") End Function ' Filter text from within an XElement Public Function FilterString(s As String) As String s = s.Replace(vbCrLf, vbLf) ' If there are already "0d0a", don't replace them with "0d0a0a" s = s.Replace(vbLf, vbCrLf) Dim needToAddBackNewline = s.EndsWith(vbCrLf, StringComparison.Ordinal) s = s.Trim() If needToAddBackNewline Then s &= vbCrLf Return s End Function Public Function FindBindingText(Of TNode As SyntaxNode)(compilation As Compilation, fileName As String, Optional which As Integer = 0, Optional prefixMatch As Boolean = False) As TNode Dim tree = (From t In compilation.SyntaxTrees Where t.FilePath = fileName).Single() Dim bindText As String = Nothing Dim bindPoint = FindBindingTextPosition(compilation, fileName, bindText, which) Dim token = tree.GetRoot().FindToken(bindPoint, True) Dim node = token.Parent Dim hasMatchingText As Func(Of SyntaxNode, Boolean) = Function(n) n.ToString = bindText OrElse (prefixMatch AndAlso TryCast(n, TNode) IsNot Nothing AndAlso n.ToString.StartsWith(bindText)) While (node IsNot Nothing AndAlso Not hasMatchingText(node)) node = node.Parent End While If node IsNot Nothing Then While TryCast(node, TNode) Is Nothing If node.Parent IsNot Nothing AndAlso hasMatchingText(node.Parent) Then node = node.Parent Else Exit While End If End While End If Assert.NotNull(node) ' If this trips, then node wasn't found Assert.IsAssignableFrom(GetType(TNode), node) If Not prefixMatch Then Assert.Equal(bindText, node.ToString()) Else Assert.StartsWith(bindText, node.ToString) End If Return DirectCast(node, TNode) End Function Public Function FindBindingTextPosition(compilation As Compilation, fileName As String, ByRef bindText As String, Optional which As Integer = 0) As Integer Dim tree = (From t In compilation.SyntaxTrees Where t.FilePath = fileName).Single() Dim bindMarker As String If which > 0 Then bindMarker = "'BIND" & which.ToString() & ":""" Else bindMarker = "'BIND:""" End If Dim text As String = tree.GetRoot().ToFullString() Dim startCommentIndex As Integer = text.IndexOf(bindMarker, StringComparison.Ordinal) + bindMarker.Length Dim endCommentIndex As Integer = text.Length Dim endOfLineIndex = text.IndexOfAny({CChar(vbLf), CChar(vbCr)}, startCommentIndex) If endOfLineIndex > -1 Then endCommentIndex = endOfLineIndex End If ' There may be more than one 'BIND{1234...} marker per line Dim nextMarkerIndex = text.IndexOf("'BIND", startCommentIndex, endCommentIndex - startCommentIndex, StringComparison.Ordinal) If nextMarkerIndex > -1 Then endCommentIndex = nextMarkerIndex End If Dim commentText = text.Substring(startCommentIndex, endCommentIndex - startCommentIndex) Dim endBindCommentLength = commentText.LastIndexOf(""""c) If endBindCommentLength = 0 Then ' This cannot be 0 so it must be text that is quoted. Look for double ending quote ' 'Bind:""some quoted string"" endBindCommentLength = commentText.LastIndexOf("""""", 1, StringComparison.Ordinal) End If bindText = commentText.Substring(0, endBindCommentLength) Dim bindPoint = text.LastIndexOf(bindText, startCommentIndex - bindMarker.Length, StringComparison.Ordinal) Return bindPoint End Function Public Function FindBindingTextPosition(compilation As Compilation, fileName As String) As Integer Dim bindText As String = Nothing Return FindBindingTextPosition(compilation, fileName, bindText) End Function Public Function FindBindingStartText(Of TNode As SyntaxNode)(compilation As Compilation, fileName As String, Optional which As Integer = 0) As TNode Dim tree = (From t In compilation.SyntaxTrees Where t.FilePath = fileName).Single() Dim bindText As String = Nothing Dim bindPoint = FindBindingTextPosition(compilation, fileName, bindText, which) Dim token As SyntaxToken = tree.GetRoot().FindToken(bindPoint) Dim node = token.Parent While (node IsNot Nothing AndAlso node.ToString.StartsWith(bindText, StringComparison.Ordinal) AndAlso Not (TypeOf node Is TNode)) node = node.Parent End While Assert.NotNull(node) ' If this trips, then node wasn't found Assert.IsAssignableFrom(GetType(TNode), node) Assert.Contains(bindText, node.ToString(), StringComparison.Ordinal) Return DirectCast(node, TNode) End Function Friend Class SemanticInfoSummary Public Symbol As Symbol = Nothing Public CandidateReason As CandidateReason = CandidateReason.None Public CandidateSymbols As ImmutableArray(Of ISymbol) = ImmutableArray.Create(Of ISymbol)() Public AllSymbols As ImmutableArray(Of ISymbol) = ImmutableArray.Create(Of ISymbol)() Public [Type] As ITypeSymbol = Nothing Public ConvertedType As ITypeSymbol = Nothing Public ImplicitConversion As Conversion = Nothing Public MemberGroup As ImmutableArray(Of ISymbol) = ImmutableArray.Create(Of ISymbol)() Public [Alias] As IAliasSymbol = Nothing Public ConstantValue As [Optional](Of Object) = Nothing End Class <Extension()> Public Function GetSemanticInfoSummary(model As SemanticModel, node As SyntaxNode) As SemanticInfoSummary Dim summary As New SemanticInfoSummary ' The information that is available varies by the type of the syntax node. Dim semanticModel = DirectCast(model, VBSemanticModel) Dim symbolInfo As SymbolInfo If TypeOf node Is ExpressionSyntax Then symbolInfo = semanticModel.GetSymbolInfo(DirectCast(node, ExpressionSyntax)) summary.MemberGroup = semanticModel.GetMemberGroup(DirectCast(node, ExpressionSyntax)) summary.ConstantValue = semanticModel.GetConstantValue(DirectCast(node, ExpressionSyntax)) Dim typeInfo = semanticModel.GetTypeInfo(DirectCast(node, ExpressionSyntax)) summary.Type = DirectCast(typeInfo.Type, TypeSymbol) summary.ConvertedType = DirectCast(typeInfo.ConvertedType, TypeSymbol) summary.ImplicitConversion = semanticModel.GetConversion(DirectCast(node, ExpressionSyntax)) ElseIf TypeOf node Is AttributeSyntax Then symbolInfo = semanticModel.GetSymbolInfo(DirectCast(node, AttributeSyntax)) summary.MemberGroup = semanticModel.GetMemberGroup(DirectCast(node, AttributeSyntax)) Dim typeInfo = semanticModel.GetTypeInfo(DirectCast(node, AttributeSyntax)) summary.Type = DirectCast(typeInfo.Type, TypeSymbol) summary.ConvertedType = DirectCast(typeInfo.ConvertedType, TypeSymbol) summary.ImplicitConversion = semanticModel.GetConversion(DirectCast(node, AttributeSyntax)) ElseIf TypeOf node Is QueryClauseSyntax Then symbolInfo = semanticModel.GetSymbolInfo(DirectCast(node, QueryClauseSyntax)) Else Throw New NotSupportedException("Type of syntax node is not supported by GetSemanticInfo") End If Assert.NotNull(symbolInfo) summary.Symbol = DirectCast(symbolInfo.Symbol, Symbol) summary.CandidateReason = symbolInfo.CandidateReason summary.CandidateSymbols = symbolInfo.CandidateSymbols summary.AllSymbols = symbolInfo.GetAllSymbols() If TypeOf node Is IdentifierNameSyntax Then summary.Alias = semanticModel.GetAliasInfo(DirectCast(node, IdentifierNameSyntax)) End If Return summary End Function <Extension()> Public Function GetSpeculativeSemanticInfoSummary(model As SemanticModel, position As Integer, expression As ExpressionSyntax, bindingOption As SpeculativeBindingOption) As SemanticInfoSummary Dim summary As New SemanticInfoSummary ' The information that is available varies by the type of the syntax node. Dim semanticModel = DirectCast(model, VBSemanticModel) Dim symbolInfo As SymbolInfo symbolInfo = semanticModel.GetSpeculativeSymbolInfo(position, expression, bindingOption) summary.MemberGroup = semanticModel.GetSpeculativeMemberGroup(position, expression) summary.ConstantValue = semanticModel.GetSpeculativeConstantValue(position, expression) Dim typeInfo = semanticModel.GetSpeculativeTypeInfo(position, expression, bindingOption) summary.Type = DirectCast(typeInfo.Type, TypeSymbol) summary.ConvertedType = DirectCast(typeInfo.ConvertedType, TypeSymbol) summary.ImplicitConversion = semanticModel.GetSpeculativeConversion(position, expression, bindingOption) Assert.NotNull(symbolInfo) summary.Symbol = DirectCast(symbolInfo.Symbol, Symbol) summary.CandidateReason = symbolInfo.CandidateReason summary.CandidateSymbols = symbolInfo.CandidateSymbols summary.AllSymbols = symbolInfo.GetAllSymbols() If TypeOf expression Is IdentifierNameSyntax Then summary.Alias = semanticModel.GetSpeculativeAliasInfo(position, DirectCast(expression, IdentifierNameSyntax), bindingOption) End If Return summary End Function Public Function GetSemanticInfoSummary(compilation As Compilation, node As SyntaxNode) As SemanticInfoSummary Dim tree = node.SyntaxTree Dim semanticModel = DirectCast(compilation.GetSemanticModel(tree), VBSemanticModel) Return GetSemanticInfoSummary(semanticModel, node) End Function Public Function GetSemanticInfoSummary(Of TSyntax As SyntaxNode)(compilation As Compilation, fileName As String, Optional which As Integer = 0) As SemanticInfoSummary Dim node As TSyntax = CompilationUtils.FindBindingText(Of TSyntax)(compilation, fileName, which) Return GetSemanticInfoSummary(compilation, node) End Function Public Function GetPreprocessingSymbolInfo(compilation As Compilation, fileName As String, Optional which As Integer = 0) As VisualBasicPreprocessingSymbolInfo Dim node = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, fileName, which) Dim semanticModel = DirectCast(compilation.GetSemanticModel(node.SyntaxTree), VBSemanticModel) Return semanticModel.GetPreprocessingSymbolInfo(node) End Function Public Function GetSemanticModel(compilation As Compilation, fileName As String) As VBSemanticModel Dim tree = (From t In compilation.SyntaxTrees Where t.FilePath = fileName).Single() Return DirectCast(compilation.GetSemanticModel(tree), VBSemanticModel) End Function ''' <summary> ''' Create a parse tree from the data inside an XElement ''' </summary> ''' <param name="programElement">The program element to create the tree from according to the following schema ''' &lt;file name="filename.vb[optional]"&gt; ''' source ''' &lt;/file&gt; ''' </param> Public Function CreateParseTree(programElement As XElement) As SyntaxTree Return VisualBasicSyntaxTree.ParseText(FilterString(programElement.Value), path:=If(programElement.@name, ""), encoding:=Encoding.UTF8) End Function ''' <summary> ''' Create a parse tree from the data inside an XElement ''' </summary> ''' <param name="programElement">The program element to create the tree from according to the following schema ''' &lt;file name="filename.vb[optional]"&gt; ''' source ''' &lt;/file&gt; ''' </param> Public Function CreateParseTreeAndSpans(programElement As XElement, Optional parseOptions As VisualBasicParseOptions = Nothing) As (tree As SyntaxTree, spans As IList(Of TextSpan)) Dim codeWithMarker As String = FilterString(programElement.Value) Dim codeWithoutMarker As String = Nothing Dim spans As ImmutableArray(Of TextSpan) = Nothing MarkupTestFile.GetSpans(codeWithMarker, codeWithoutMarker, spans) Dim text = SourceText.From(codeWithoutMarker, Encoding.UTF8) Return (VisualBasicSyntaxTree.ParseText(text, parseOptions, If(programElement.@name, "")), spans) End Function ' Find a node inside a tree. Public Function FindTokenFromText(tree As SyntaxTree, textToFind As String) As SyntaxToken Dim text As String = tree.GetText().ToString() Dim position As Integer = text.IndexOf(textToFind, StringComparison.Ordinal) Dim node = tree.GetRoot().FindToken(position) Return node End Function ' Find a position inside a tree. Public Function FindPositionFromText(tree As SyntaxTree, textToFind As String) As Integer Dim text As String = tree.GetText().ToString() Dim position As Integer = text.IndexOf(textToFind, StringComparison.Ordinal) Return position End Function ' Find a node inside a tree. Public Function FindNodeFromText(tree As SyntaxTree, textToFind As String) As SyntaxNode Return FindTokenFromText(tree, textToFind).Parent End Function ' Find a node of a type inside a tree. Public Function FindNodeOfTypeFromText(Of TNode As SyntaxNode)(tree As SyntaxTree, textToFind As String) As TNode Dim node = FindNodeFromText(tree, textToFind) While node IsNot Nothing AndAlso Not TypeOf node Is TNode node = node.Parent End While Return DirectCast(node, TNode) End Function ' Get the syntax tree with a given name. Public Function GetTree(compilation As Compilation, name As String) As SyntaxTree Return (From t In compilation.SyntaxTrees Where t.FilePath = name).First() End Function ' Get the symbol with a given full name. It must be unambiguous. Public Function GetSymbolByFullName(compilation As VisualBasicCompilation, methodName As String) As Symbol Dim names = New List(Of String)() Dim offset = 0 While True ' Find the next "."c separator but skip the first character since ' the name may begin with "."c (in ".ctor" for instance). Dim separator = methodName.IndexOf("."c, offset + 1) If separator < 0 Then names.Add(methodName.Substring(offset)) Exit While End If names.Add(methodName.Substring(offset, separator - offset)) offset = separator + 1 End While Dim currentSymbol As Symbol = compilation.GlobalNamespace For Each name In names Assert.True(TypeOf currentSymbol Is NamespaceOrTypeSymbol, String.Format("{0} does not have members", currentSymbol.ToDisplayString(SymbolDisplayFormat.TestFormat))) Dim currentContainer = DirectCast(currentSymbol, NamespaceOrTypeSymbol) Dim members = currentContainer.GetMembers(name) Assert.True(members.Any(), String.Format("No members named {0} inside {1}", name, currentSymbol.ToDisplayString(SymbolDisplayFormat.TestFormat))) Assert.True(members.Length() <= 1, String.Format("Multiple members named {0} inside {1}", name, currentSymbol.ToDisplayString(SymbolDisplayFormat.TestFormat))) currentSymbol = members.First() Next Return currentSymbol End Function ' Check that the compilation has no parse or declaration errors. Public Sub AssertNoDeclarationDiagnostics(compilation As VisualBasicCompilation, Optional suppressInfos As Boolean = True) AssertNoDiagnostics(compilation.GetDeclarationDiagnostics(), suppressInfos) End Sub ''' <remarks> ''' Does not consider INFO diagnostics. ''' </remarks> <Extension()> Public Sub AssertNoDiagnostics(compilation As VisualBasicCompilation, Optional suppressInfos As Boolean = True) AssertNoDiagnostics(compilation.GetDiagnostics(), suppressInfos) End Sub ' Check that the compilation has no parse, declaration errors/warnings, or compilation errors/warnings. ''' <remarks> ''' Does not consider INFO and HIDDEN diagnostics. ''' </remarks> Private Sub AssertNoDiagnostics(diags As ImmutableArray(Of Diagnostic), suppressInfos As Boolean) If suppressInfos Then diags = diags.WhereAsArray(Function(d) d.Severity > DiagnosticSeverity.Info) End If If diags.Length > 0 Then Console.WriteLine("Unexpected diagnostics found:") For Each d In diags Console.WriteLine(ErrorText(d)) Next Assert.True(False, "Should not have any diagnostics") End If End Sub ' Check that the compilation has no parse, declaration errors, or compilation errors. <Extension()> Public Sub AssertNoErrors(compilation As Compilation) AssertNoErrors(compilation.GetDiagnostics()) End Sub ' Check that the compilation has no parse, declaration errors, or compilation errors. <Extension()> Public Sub AssertNoErrors(errors As ImmutableArray(Of Diagnostic)) Dim diags As ImmutableArray(Of Diagnostic) = errors.WhereAsArray(Function(e) e.Severity = DiagnosticSeverity.Error) If diags.Length > 0 Then Console.WriteLine("Unexpected errors found:") For Each d In diags Console.WriteLine(ErrorText(d)) Next Assert.True(False, "Should not have any errors") End If End Sub ''' <summary> ''' Check that a compilation has these declaration errors. ''' </summary> ''' <param name="compilation"></param> ''' <param name="errs">Expected errors according to this schema ''' &lt;error&gt;[full errors text]&lt;/error&gt;</param> ''' <param name="suppressInfos">True to ignore info-severity diagnostics.</param> ''' <remarks></remarks> <Extension()> Public Sub AssertTheseDeclarationDiagnostics(compilation As VisualBasicCompilation, errs As XElement, Optional suppressInfos As Boolean = True) AssertTheseDiagnostics(compilation.GetDeclarationDiagnostics(), errs, suppressInfos) End Sub <Extension()> Public Sub AssertTheseParseDiagnostics(compilation As VisualBasicCompilation, errs As XElement, Optional suppressInfos As Boolean = True) AssertTheseDiagnostics(compilation.GetParseDiagnostics(), errs, suppressInfos) End Sub ''' <summary> ''' Check that a compilation has these errors at Compile stage or before. ''' </summary> ''' <param name="compilation"></param> ''' <param name="errs">Expected errors according to this schema ''' &lt;error&gt;[full errors text]&lt;/error&gt;</param> ''' <param name="suppressInfos">True to ignore info-severity diagnostics.</param> ''' <remarks></remarks> <Extension()> Public Sub AssertTheseCompileDiagnostics(compilation As Compilation, Optional errs As XElement = Nothing, Optional suppressInfos As Boolean = True) If errs Is Nothing Then errs = <errors/> End If AssertTheseDiagnostics(DirectCast(compilation, VisualBasicCompilation).GetDiagnostics(CompilationStage.Compile), errs, suppressInfos) End Sub ''' <summary> ''' Check that a compilation has these errors during Emit. ''' </summary> ''' <param name="compilation"></param> ''' <param name="errs">Expected errors according to this schema ''' &lt;error&gt;[full errors text]&lt;/error&gt;</param> ''' <param name="suppressInfos">True to ignore info-severity diagnostics.</param> ''' <remarks></remarks> <Extension()> Public Sub AssertTheseEmitDiagnostics(compilation As Compilation, Optional errs As XElement = Nothing, Optional suppressInfos As Boolean = True) If errs Is Nothing Then errs = <errors/> End If Using assemblyStream As New MemoryStream() Using pdbStream As New MemoryStream() Dim diagnostics = compilation.Emit(assemblyStream, pdbStream:=pdbStream).Diagnostics AssertTheseDiagnostics(diagnostics, errs, suppressInfos) End Using End Using End Sub <Extension()> Public Sub AssertTheseDiagnostics(tree As SyntaxTree, errs As XElement, Optional suppressInfos As Boolean = True) AssertTheseDiagnostics(tree.GetDiagnostics().AsImmutable(), errs, suppressInfos) End Sub ''' <summary> ''' Check that a compilation has these declaration or compilation errors. ''' </summary> ''' <param name="compilation"></param> ''' <param name="errs">Expected errors according to this schema ''' &lt;error&gt;[full errors text]&lt;/error&gt;</param> ''' <param name="suppressInfos">True to ignore info-severity diagnostics.</param> ''' <remarks></remarks> <Extension()> Public Sub AssertTheseDiagnostics(compilation As Compilation, Optional errs As XElement = Nothing, Optional suppressInfos As Boolean = True) If errs Is Nothing Then errs = <errors/> End If AssertTheseDiagnostics(DirectCast(compilation, VisualBasicCompilation).GetDiagnostics(CompilationStage.Compile), errs, suppressInfos) End Sub <Extension()> Public Sub AssertTheseDiagnostics(compilation As Compilation, errs As XCData, Optional suppressInfos As Boolean = True) AssertTheseDiagnostics(DirectCast(compilation, VisualBasicCompilation).GetDiagnostics(CompilationStage.Compile), errs, suppressInfos) End Sub ' Check that a compilation has these declaration or compilation errors. <Extension()> Public Sub AssertTheseDiagnostics(compilation As Compilation, errs As String, Optional suppressInfos As Boolean = True) AssertTheseDiagnostics(DirectCast(compilation, VisualBasicCompilation).GetDiagnostics(CompilationStage.Compile), errs, suppressInfos) End Sub ''' <param name="errors"></param> ''' <param name="errs">Expected errors according to this schema ''' &lt;expected&gt;[full errors text]&lt;/expected&gt;</param> ''' <param name="suppressInfos">True to ignore info-severity diagnostics.</param> ''' <remarks></remarks> <Extension()> Public Sub AssertTheseDiagnostics(errors As ImmutableArray(Of Diagnostic), errs As XElement, Optional suppressInfos As Boolean = True) If errs Is Nothing Then errs = <errors/> End If Dim expectedText = FilterString(errs.Value) AssertTheseDiagnostics(errors, expectedText, suppressInfos) End Sub <Extension()> Public Sub AssertTheseDiagnostics(errors As ImmutableArray(Of Diagnostic), errs As XCData, Optional suppressInfos As Boolean = True) Dim expectedText = FilterString(errs.Value) AssertTheseDiagnostics(errors, expectedText, suppressInfos) End Sub Private Sub AssertTheseDiagnostics(errors As ImmutableArray(Of Diagnostic), expectedText As String, suppressInfos As Boolean) Dim actualText = DumpAllDiagnostics(errors.ToArray(), suppressInfos) If expectedText <> actualText Then Dim messages = ParserTestUtilities.PooledStringBuilderPool.Allocate() With messages.Builder .AppendLine() If actualText.StartsWith(expectedText, StringComparison.Ordinal) AndAlso actualText.Substring(expectedText.Length).Trim().Length > 0 Then .AppendLine("UNEXPECTED ERROR MESSAGES:") .AppendLine(actualText.Substring(expectedText.Length)) Assert.True(False, .ToString()) Else Dim expectedLines = expectedText.Split({vbCrLf, vbLf}, StringSplitOptions.RemoveEmptyEntries) Dim actualLines = actualText.Split({vbCrLf, vbLf}, StringSplitOptions.RemoveEmptyEntries) Dim appendedLines As Integer = 0 .AppendLine("MISSING ERROR MESSAGES:") For Each l In expectedLines If Not actualLines.Contains(l) Then .AppendLine(l) appendedLines += 1 End If Next .AppendLine("UNEXPECTED ERROR MESSAGES:") For Each l In actualLines If Not expectedLines.Contains(l) Then .AppendLine(l) appendedLines += 1 End If Next If appendedLines > 0 Then Assert.True(False, .ToString()) Else CompareLineByLine(expectedText, actualText) End If End If End With messages.Free() End If End Sub Private Sub CompareLineByLine(expected As String, actual As String) Dim expectedReader = New StringReader(expected) Dim actualReader = New StringReader(actual) Dim expectedPooledBuilder = PooledStringBuilderPool.Allocate() Dim actualPooledBuilder = PooledStringBuilderPool.Allocate() Dim expectedBuilder = expectedPooledBuilder.Builder Dim actualBuilder = actualPooledBuilder.Builder Dim expectedLine = expectedReader.ReadLine() Dim actualLine = actualReader.ReadLine() While expectedLine IsNot Nothing AndAlso actualLine IsNot Nothing If Not expectedLine.Equals(actualLine) Then expectedBuilder.AppendLine("<! " & expectedLine) actualBuilder.AppendLine("!> " & actualLine) Else expectedBuilder.AppendLine(expectedLine) actualBuilder.AppendLine(actualLine) End If expectedLine = expectedReader.ReadLine() actualLine = actualReader.ReadLine() End While While expectedLine IsNot Nothing expectedBuilder.AppendLine("<! " & expectedLine) expectedLine = expectedReader.ReadLine() End While While actualLine IsNot Nothing actualBuilder.AppendLine("!> " & actualLine) actualLine = actualReader.ReadLine() End While Assert.Equal(expectedPooledBuilder.ToStringAndFree(), actualPooledBuilder.ToStringAndFree()) End Sub ' There are certain cases where multiple distinct errors are ' reported where the error code and text span are the same. When ' sorting such cases, we should preserve the original order. Private Structure DiagnosticAndIndex Public Sub New(diagnostic As Diagnostic, index As Integer) Me.Diagnostic = diagnostic Me.Index = index End Sub Public ReadOnly Diagnostic As Diagnostic Public ReadOnly Index As Integer End Structure Private Function DumpAllDiagnostics(allDiagnostics As Diagnostic(), suppressInfos As Boolean) As String Return DumpAllDiagnostics(allDiagnostics.ToImmutableArray(), suppressInfos) End Function Friend Function DumpAllDiagnostics(allDiagnostics As ImmutableArray(Of Diagnostic), suppressInfos As Boolean) As String Dim diagnosticsAndIndices(allDiagnostics.Length - 1) As DiagnosticAndIndex For i = 0 To allDiagnostics.Length - 1 diagnosticsAndIndices(i) = New DiagnosticAndIndex(allDiagnostics(i), i) Next Array.Sort(diagnosticsAndIndices, Function(diag1, diag2) CompareErrors(diag1, diag2)) Dim builder = PooledStringBuilderPool.Allocate() With builder.Builder For Each e In diagnosticsAndIndices If Not suppressInfos OrElse e.Diagnostic.Severity > DiagnosticSeverity.Info Then .Append(ErrorText(e.Diagnostic)) End If Next End With Return builder.ToStringAndFree() End Function ' Get the text of a diagnostic. For source error, includes the text of the line itself, with the ' span underlined. Private Function ErrorText(e As Diagnostic) As String Dim message = e.Id + ": " + e.GetMessage(EnsureEnglishUICulture.PreferredOrNull) If e.Location.IsInSource Then Dim sourceLocation = e.Location Dim offsetInLine As Integer = 0 Dim lineText As String = GetLineText(sourceLocation.SourceTree.GetText(), sourceLocation.SourceSpan.Start, offsetInLine) Return message + Environment.NewLine + lineText + Environment.NewLine + New String(" "c, offsetInLine) + New String("~"c, Math.Max(Math.Min(sourceLocation.SourceSpan.Length, lineText.Length - offsetInLine + 1), 1)) + Environment.NewLine ElseIf e.Location.IsInMetadata Then Return message + Environment.NewLine + String.Format("in metadata assembly '{0}'" + Environment.NewLine, e.Location.MetadataModule.ContainingAssembly.Identity.Name) Else Return message + Environment.NewLine End If End Function ' Get the text of a line that contains the offset, and return the offset within that line. Private Function GetLineText(text As SourceText, position As Integer, ByRef offsetInLine As Integer) As String Dim textLine = text.Lines.GetLineFromPosition(position) offsetInLine = position - textLine.Start Return textLine.ToString() End Function Private Function CompareErrors(diagAndIndex1 As DiagnosticAndIndex, diagAndIndex2 As DiagnosticAndIndex) As Integer ' Sort by no location, then source, then metadata. Sort within each group. Dim diag1 = diagAndIndex1.Diagnostic Dim diag2 = diagAndIndex2.Diagnostic Dim loc1 = diag1.Location Dim loc2 = diag2.Location Dim comparer = StringComparer.Ordinal If Not (loc1.IsInSource Or loc1.IsInMetadata) Then If Not (loc2.IsInSource Or loc2.IsInMetadata) Then ' Both have no location. Sort by code, then by message. If diag1.Code < diag2.Code Then Return -1 If diag1.Code > diag2.Code Then Return 1 Return comparer.Compare(diag1.GetMessage(EnsureEnglishUICulture.PreferredOrNull), diag2.GetMessage(EnsureEnglishUICulture.PreferredOrNull)) Else Return -1 End If ElseIf Not (loc2.IsInSource Or loc2.IsInMetadata) Then Return 1 ElseIf loc1.IsInSource AndAlso loc2.IsInSource Then ' source by tree, then span start, then span end, then error code, then message Dim sourceTree1 = loc1.SourceTree Dim sourceTree2 = loc2.SourceTree If sourceTree1.FilePath <> sourceTree2.FilePath Then Return comparer.Compare(sourceTree1.FilePath, sourceTree2.FilePath) If loc1.SourceSpan.Start < loc2.SourceSpan.Start Then Return -1 If loc1.SourceSpan.Start > loc2.SourceSpan.Start Then Return 1 If loc1.SourceSpan.Length < loc2.SourceSpan.Length Then Return -1 If loc1.SourceSpan.Length > loc2.SourceSpan.Length Then Return 1 If diag1.Code < diag2.Code Then Return -1 If diag1.Code > diag2.Code Then Return 1 Return comparer.Compare(diag1.GetMessage(EnsureEnglishUICulture.PreferredOrNull), diag2.GetMessage(EnsureEnglishUICulture.PreferredOrNull)) ElseIf loc1.IsInMetadata AndAlso loc2.IsInMetadata Then ' sort by assembly name, then by error code Dim name1 = loc1.MetadataModule.ContainingAssembly.Name Dim name2 = loc2.MetadataModule.ContainingAssembly.Name If name1 <> name2 Then Return comparer.Compare(name1, name2) If diag1.Code < diag2.Code Then Return -1 If diag1.Code > diag2.Code Then Return 1 Return comparer.Compare(diag1.GetMessage(EnsureEnglishUICulture.PreferredOrNull), diag2.GetMessage(EnsureEnglishUICulture.PreferredOrNull)) ElseIf loc1.IsInSource Then Return -1 ElseIf loc2.IsInSource Then Return 1 End If ' Preserve original order. Return diagAndIndex1.Index - diagAndIndex2.Index End Function Public Function GetTypeSymbol(compilation As Compilation, semanticModel As SemanticModel, treeName As String, stringInDecl As String) As INamedTypeSymbol Dim tree = CompilationUtils.GetTree(compilation, treeName) Dim node = CompilationUtils.FindTokenFromText(tree, stringInDecl).Parent While Not (TypeOf node Is TypeStatementSyntax) node = node.Parent Assert.NotNull(node) End While Return DirectCast(semanticModel, VBSemanticModel).GetDeclaredSymbol(DirectCast(node, TypeStatementSyntax)) End Function Public Function GetEnumSymbol(compilation As Compilation, semanticModel As SemanticModel, treeName As String, stringInDecl As String) As INamedTypeSymbol Dim tree = CompilationUtils.GetTree(compilation, treeName) Dim node = CompilationUtils.FindTokenFromText(tree, stringInDecl).Parent While Not (TypeOf node Is EnumStatementSyntax) node = node.Parent Assert.NotNull(node) End While Return DirectCast(semanticModel, VBSemanticModel).GetDeclaredSymbol(DirectCast(node, EnumStatementSyntax)) End Function Public Function GetDelegateSymbol(compilation As Compilation, semanticModel As SemanticModel, treeName As String, stringInDecl As String) As NamedTypeSymbol Dim tree = CompilationUtils.GetTree(compilation, treeName) Dim node = CompilationUtils.FindTokenFromText(tree, stringInDecl).Parent While Not (TypeOf node Is MethodBaseSyntax) node = node.Parent Assert.NotNull(node) End While Return DirectCast(semanticModel.GetDeclaredSymbol(DirectCast(node, MethodBaseSyntax)), NamedTypeSymbol) End Function Public Function GetTypeSymbol(compilation As Compilation, treeName As String, stringInDecl As String, Optional isDistinct As Boolean = True) As List(Of INamedTypeSymbol) Dim tree = CompilationUtils.GetTree(compilation, treeName) Dim bindings = DirectCast(compilation.GetSemanticModel(tree), VBSemanticModel) Dim text As String = tree.GetText().ToString() Dim pos = 0 Dim node As SyntaxNode Dim symType = New List(Of INamedTypeSymbol) Do pos = text.IndexOf(stringInDecl, pos + 1, StringComparison.Ordinal) If pos >= 0 Then node = tree.GetRoot().FindToken(pos).Parent While Not (TypeOf node Is TypeStatementSyntax OrElse TypeOf node Is EnumStatementSyntax) If node Is Nothing Then Exit While End If node = node.Parent End While If Not node Is Nothing Then If TypeOf node Is TypeStatementSyntax Then Dim temp = bindings.GetDeclaredSymbol(DirectCast(node, TypeStatementSyntax)) symType.Add(temp) Else Dim temp = bindings.GetDeclaredSymbol(DirectCast(node, EnumStatementSyntax)) symType.Add(temp) End If End If Else Exit Do End If Loop If (isDistinct) Then symType = symType.Distinct().OrderBy(Function(x) x.ToDisplayString(), StringComparer.OrdinalIgnoreCase).ToList() Else symType = symType.OrderBy(Function(x) x.ToDisplayString(), StringComparer.OrdinalIgnoreCase).ToList() End If Return symType End Function Public Function VerifyGlobalNamespace(compilation As Compilation, treeName As String, symbolName As String, ExpectedDispName() As String, isDistinct As Boolean) As List(Of INamedTypeSymbol) Dim tree = CompilationUtils.GetTree(compilation, treeName) Dim bindings1 = compilation.GetSemanticModel(tree) Dim symbols = GetTypeSymbol(compilation, treeName, symbolName, isDistinct) Assert.Equal(ExpectedDispName.Count, symbols.Count) ExpectedDispName = ExpectedDispName.OrderBy(StringComparer.OrdinalIgnoreCase).ToArray() Dim count = 0 For Each item In symbols Assert.NotNull(item) Assert.Equal(ExpectedDispName(count), item.ToDisplayString()) count += 1 Next Return symbols End Function Public Function VerifyGlobalNamespace(compilation As VisualBasicCompilation, treeName As String, symbolName As String, ParamArray expectedDisplayNames() As String) As List(Of INamedTypeSymbol) Return VerifyGlobalNamespace(compilation, treeName, symbolName, expectedDisplayNames, True) End Function Public Function VerifyIsGlobal(globalNS1 As ISymbol, Optional expected As Boolean = True) As NamespaceSymbol Dim nsSymbol = DirectCast(globalNS1, NamespaceSymbol) Assert.NotNull(nsSymbol) If (expected) Then Assert.True(nsSymbol.IsGlobalNamespace) Else Assert.False(nsSymbol.IsGlobalNamespace) End If Return nsSymbol End Function Public Sub CheckSymbols(Of TSymbol As ISymbol)(symbols As ImmutableArray(Of TSymbol), ParamArray descriptions As String()) Assert.Equal(symbols.Length, descriptions.Length) Dim symbolDescriptions As String() = (From s In symbols Select s.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)).ToArray() Array.Sort(descriptions) Array.Sort(symbolDescriptions) For i = 0 To descriptions.Length - 1 Assert.Equal(symbolDescriptions(i), descriptions(i)) Next End Sub Public Sub CheckSymbols(Of TSymbol As ISymbol)(symbols As TSymbol(), ParamArray descriptions As String()) CheckSymbols(symbols.AsImmutableOrNull(), descriptions) End Sub Public Sub CheckSymbol(symbol As ISymbol, description As String) Assert.Equal(symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat), description) End Sub Public Function SortAndMergeStrings(ParamArray strings As String()) As String Array.Sort(strings) Dim builder = PooledStringBuilderPool.Allocate() With builder.Builder For Each item In strings If .Length > 0 Then .AppendLine() End If .Append(item) Next End With Return builder.ToStringAndFree() End Function Public Sub CheckSymbolsUnordered(Of TSymbol As ISymbol)(symbols As ImmutableArray(Of TSymbol), ParamArray descriptions As String()) Assert.Equal(symbols.Length, descriptions.Length) Assert.Equal(SortAndMergeStrings(descriptions), SortAndMergeStrings(symbols.Select(Function(s) s.ToDisplayString()).ToArray())) End Sub <Extension> Friend Function LookupNames(model As SemanticModel, position As Integer, Optional container As INamespaceOrTypeSymbol = Nothing, Optional namespacesAndTypesOnly As Boolean = False) As List(Of String) Dim result = If(namespacesAndTypesOnly, model.LookupNamespacesAndTypes(position, container), model.LookupSymbols(position, container)) Return result.Select(Function(s) s.Name).Distinct().ToList() End Function End Module
1
dotnet/roslyn
56,011
React to string comparison changing on .NET Core
The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
jaredpar
"2021-08-30T17:18:52Z"
"2021-08-30T20:20:04Z"
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
4d99cda6e446e77dbb302e26388c1093bd3ef569
React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
./src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenVBCore.vb
' 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.IO Imports System.Text Imports System.Text.RegularExpressions Imports System.Xml.Linq Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class CodeGenVBCore Inherits BasicTestBase ' The Embedded attribute should only be available ' if other embedded code is included. <Fact()> Public Sub EmbeddedAttributeRequiresOtherEmbeddedCode() Dim sources = <compilation> <file name="c.vb"><![CDATA[ Option Strict On <Microsoft.VisualBasic.Embedded()> Class C End Class ]]></file> </compilation> ' With InternalXmlHelper. Dim compilation = CreateCompilationWithMscorlib40AndReferences(sources, references:=NoVbRuntimeReferences.Concat(XmlReferences), options:=TestOptions.ReleaseDll.WithEmbedVbCoreRuntime(True)) compilation.AssertNoErrors() ' With VBCore. compilation = CreateCompilationWithMscorlib40AndReferences(sources, references:=NoVbRuntimeReferences, options:=TestOptions.ReleaseDll.WithEmbedVbCoreRuntime(True)) compilation.AssertNoErrors() ' No embedded code. compilation = CreateCompilationWithMscorlib40AndReferences(sources, references:=NoVbRuntimeReferences, options:=TestOptions.ReleaseDll) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC30002: Type 'Microsoft.VisualBasic.Embedded' is not defined. <Microsoft.VisualBasic.Embedded()> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></errors>) End Sub ' The Embedded attribute should only be available for ' user-define code if vb runtime is included. <WorkItem(546059, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546059")> <Fact()> Public Sub EmbeddedAttributeRequiresOtherEmbeddedCode2() Dim sources = <compilation> <file name="c.vb"><![CDATA[ Option Strict On <Microsoft.VisualBasic.Embedded()> Class C End Class ]]></file> </compilation> ' No embedded code. Dim compilation = CreateCompilationWithMscorlib40AndReferences(sources, references:=NoVbRuntimeReferences.Concat({MsvbRef, SystemXmlRef, SystemXmlLinqRef}), options:=TestOptions.ReleaseDll) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC30002: Type 'Microsoft.VisualBasic.Embedded' is not defined. <Microsoft.VisualBasic.Embedded()> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></errors>) End Sub ' The Embedded attribute should only be available for ' user-define code if vb runtime is included. <WorkItem(546059, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546059")> <Fact()> Public Sub EmbeddedAttributeRequiresOtherEmbeddedCode3() Dim sources = <compilation> <file name="c.vb"><![CDATA[ Option Strict On Class C Public x As Microsoft.VisualBasic.Embedded End Class ]]></file> </compilation> ' No embedded code. Dim compilation = CreateCompilationWithMscorlib40AndReferences(sources, references:=NoVbRuntimeReferences.Concat({MsvbRef, SystemXmlRef, SystemXmlLinqRef}), options:=TestOptions.ReleaseDll) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC30002: Type 'Microsoft.VisualBasic.Embedded' is not defined. Public x As Microsoft.VisualBasic.Embedded ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></errors>) End Sub <Fact()> Public Sub InternalXmlHelper_NoReferences() Dim compilationVerifier = MyBase.CompileAndVerify(source:= <compilation> <file name="c.vb"><![CDATA[ Option Strict On Class C End Class ]]></file> </compilation>, allReferences:=NoVbRuntimeReferences, sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class C > Sub C..ctor() End Class End Namespace </expected>.Value) End Sub, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal)) compilationVerifier.Compilation.AssertNoErrors() End Sub <Fact()> Public Sub InternalXmlHelper_NoSymbols() Dim compilationVerifier = MyBase.CompileAndVerify(source:= <compilation> <file name="c.vb"><![CDATA[ Option Strict On Class C End Class ]]></file> </compilation>, allReferences:=NoVbRuntimeReferences.Concat(XmlReferences), sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class C > Sub C..ctor() End Class End Namespace </expected>.Value) End Sub, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal)) compilationVerifier.Compilation.AssertNoErrors() End Sub <Fact()> Public Sub InternalXmlHelper_CreateNamespaceAttribute_NoDebug() Dim symbols = <expected> Namespace Global Class C > C.F As System.Object > Sub C..ctor() End Class Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class End Namespace End Namespace Namespace My [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class My.InternalXmlHelper [System.ComponentModel.EditorBrowsableAttribute] > Function My.InternalXmlHelper.CreateNamespaceAttribute(name As System.Xml.Linq.XName, ns As System.Xml.Linq.XNamespace) As System.Xml.Linq.XAttribute End Class End Namespace End Namespace </expected>.Value Dim compilationVerifier = MyBase.CompileAndVerify(source:= <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports <xmlns:p="http://roslyn/"> Class C Public Shared F As Object = <p:x/> End Class ]]></file> </compilation>, allReferences:=NoVbRuntimeReferences.Concat(XmlReferences), sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], symbols), options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal)) compilationVerifier.Compilation.AssertNoErrors() End Sub <WorkItem(545438, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545438"), WorkItem(546887, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546887")> <Fact()> Public Sub InternalXmlHelper_ValueProperty() Dim symbols = <expected> Namespace Global Class C > Sub C..ctor() > Sub C.M(x As System.Xml.Linq.XElement) End Class Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class End Namespace End Namespace Namespace My [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class My.InternalXmlHelper > Function My.InternalXmlHelper.get_AttributeValue(source As System.Xml.Linq.XElement, name As System.Xml.Linq.XName) As System.String > Function My.InternalXmlHelper.get_Value(source As System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)) As System.String > Property My.InternalXmlHelper.AttributeValue(source As System.Xml.Linq.XElement, name As System.Xml.Linq.XName) As System.String > Property My.InternalXmlHelper.Value(source As System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)) As System.String > Sub My.InternalXmlHelper.set_AttributeValue(source As System.Xml.Linq.XElement, name As System.Xml.Linq.XName, value As System.String) > Sub My.InternalXmlHelper.set_Value(source As System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement), value As System.String) End Class End Namespace End Namespace </expected>.Value Dim compilationVerifier = MyBase.CompileAndVerify(source:= <compilation> <file name="c.vb"><![CDATA[ Option Strict On Class C Shared Sub M(x As System.Xml.Linq.XElement) x.@a = x.<y>.Value End Sub End Class ]]></file> </compilation>, allReferences:=NoVbRuntimeReferences.Concat(XmlReferences), symbolValidator:=Sub([module]) ValidateSymbols([module], symbols), sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal)) compilationVerifier.Compilation.AssertNoErrors() End Sub <Fact()> Public Sub InternalXmlHelper_Locations() Dim compilation = CreateCompilationWithMscorlib40AndReferences( <compilation> <file name="c.vb"><![CDATA[ Class C Public Shared F As Object = <x xmlns:p="http://roslyn"/> End Class ]]></file> </compilation>, references:=NoVbRuntimeReferences.Concat(XmlReferences), options:=TestOptions.ReleaseDll.WithEmbedVbCoreRuntime(True)) compilation.AssertNoErrors() Dim globalNamespace = compilation.SourceModule.GlobalNamespace Assert.Equal(globalNamespace.Locations.Length, 4) Dim [namespace] = globalNamespace.GetMember(Of NamespaceSymbol)("My") Assert.Equal([namespace].Locations.Length, 1) Dim type = [namespace].GetMember(Of NamedTypeSymbol)("InternalXmlHelper") Assert.Equal(type.Locations.Length, 1) End Sub <Fact()> Public Sub VbCore_NoSymbols() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports Microsoft.VisualBasic Class Program Shared Sub Main(args As String()) End Sub End Class </file> </compilation>, expectedOutput:="", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_SingleSymbol_SymbolInGetType() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports System.Collections.Generic Imports Microsoft.VisualBasic Imports Microsoft.VisualBasic.CompilerServices Class Program Shared Sub Main(args As String()) Console.Write(GetType(List(Of List(Of StandardModuleAttribute))).ToString()) End Sub End Class </file> </compilation>, expectedOutput:="System.Collections.Generic.List`1[System.Collections.Generic.List`1[Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute]]", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute > Sub Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute..ctor() End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_SingleSymbol_Constants() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports Microsoft.VisualBasic Class Program Shared Sub Main(args As String()) Console.Write(GetType(Constants).ToString()) End Sub End Class </file> </compilation>, expectedOutput:="Microsoft.VisualBasic.Constants", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Module Microsoft.VisualBasic.Constants End Module [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute > Sub Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute..ctor() End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_SingleSymbol_Constants_WithVbRuntime() MyBase.CompileAndVerify(source:= <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports Microsoft.VisualBasic Class Program Shared Sub Main(args As String()) Console.Write(GetType(Constants).ToString()) End Sub End Class </file> </compilation>, allReferences:=NoVbRuntimeReferences.Concat(MsvbRef), expectedOutput:="Microsoft.VisualBasic.Constants", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Module Microsoft.VisualBasic.Constants End Module [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute > Sub Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute..ctor() End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub, options:=TestOptions.DebugExe.WithEmbedVbCoreRuntime(True).WithMetadataImportOptions(MetadataImportOptions.Internal)) End Sub <Fact()> Public Sub VbCore_SingleSymbol_Constants_All() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports Microsoft.VisualBasic Class Program Shared Sub Main(args As String()) Dim s = String.Format("|{0}|{1}|{2}|{3}|{4}|{5}|{6}|{7}|{8}|{9}|", vbCrLf, vbNewLine, vbCr, vbLf, vbBack, vbFormFeed, vbTab, vbVerticalTab, vbNullChar, vbNullString) s = s.Replace(vbCr, "vbCr") s = s.Replace(vbLf, "vbLf") s = s.Replace(vbBack, "vbBack") s = s.Replace(vbFormFeed, "vbFormFeed") s = s.Replace(vbTab, "vbTab") s = s.Replace(vbVerticalTab, "vbVerticalTab") s = s.Replace(vbNullChar, "vbNullChar") Console.Write(s) End Sub End Class </file> </compilation>, expectedOutput:="|vbCrvbLf|vbCrvbLf|vbCr|vbLf|vbBack|vbFormFeed|vbTab|vbVerticalTab|vbNullChar||", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_SingleSymbol_CompilerServices_EmbeddedOperators() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports Microsoft.VisualBasic Class Program Shared Sub Main(args As String()) Console.Write(GetType(CompilerServices.EmbeddedOperators).ToString()) End Sub End Class </file> </compilation>, expectedOutput:="Microsoft.VisualBasic.CompilerServices.EmbeddedOperators", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.EmbeddedOperators End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_SingleSymbol_CompilerServices_EmbeddedOperators_CompareString() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports Microsoft.VisualBasic Class Program Shared Sub Main(args As String()) Console.Write(CompilerServices.EmbeddedOperators.CompareString("a", "A", True)) End Sub End Class </file> </compilation>, expectedOutput:="0", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.Conversions > Function Microsoft.VisualBasic.CompilerServices.Conversions.GetCultureInfo() As System.Globalization.CultureInfo End Class [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.EmbeddedOperators > Function Microsoft.VisualBasic.CompilerServices.EmbeddedOperators.CompareString(Left As System.String, Right As System.String, TextCompare As System.Boolean) As System.Int32 End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_SingleSymbol_CompilerServices_EmbeddedOperators_CompareString2() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports Microsoft.VisualBasic Class Program Shared Sub Main(args As String()) Dim x As String = "Goo" Console.WriteLine(If(x = "Goo", "y", x)) End Sub End Class </file> </compilation>, expectedOutput:="y", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.Conversions > Function Microsoft.VisualBasic.CompilerServices.Conversions.GetCultureInfo() As System.Globalization.CultureInfo End Class [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.EmbeddedOperators > Function Microsoft.VisualBasic.CompilerServices.EmbeddedOperators.CompareString(Left As System.String, Right As System.String, TextCompare As System.Boolean) As System.Int32 End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_SingleSymbol_CompilerServices_Conversions() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports Microsoft.VisualBasic Class Program Shared Sub Main(args As String()) Console.Write(GetType(CompilerServices.Conversions).ToString()) End Sub End Class </file> </compilation>, expectedOutput:="Microsoft.VisualBasic.CompilerServices.Conversions", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.Conversions End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_SingleSymbol_CompilerServices_Conversions_ToBoolean_String() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports Microsoft.VisualBasic Class Program Shared Sub Main(args As String()) Console.Write(CompilerServices.Conversions.ToBoolean("True").ToString()) End Sub End Class </file> </compilation>, expectedOutput:="True", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.Conversions > Function Microsoft.VisualBasic.CompilerServices.Conversions.GetCultureInfo() As System.Globalization.CultureInfo > Function Microsoft.VisualBasic.CompilerServices.Conversions.IsHexOrOctValue(Value As System.String, ByRef i64Value As System.Int64) As System.Boolean > Function Microsoft.VisualBasic.CompilerServices.Conversions.ToBoolean(Value As System.String) As System.Boolean > Function Microsoft.VisualBasic.CompilerServices.Conversions.ToHalfwidthNumbers(s As System.String, culture As System.Globalization.CultureInfo) As System.String End Class [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.ProjectData > Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError() > Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(ex As System.Exception) End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_SingleSymbol_CompilerServices_Conversions_ToBoolean_Object() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports Microsoft.VisualBasic Class Program Shared Sub Main(args As String()) Console.Write(CompilerServices.Conversions.ToBoolean(directcast("True".ToString(), Object)).ToString()) End Sub End Class </file> </compilation>, expectedOutput:="True", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.Conversions > Function Microsoft.VisualBasic.CompilerServices.Conversions.GetCultureInfo() As System.Globalization.CultureInfo > Function Microsoft.VisualBasic.CompilerServices.Conversions.IsHexOrOctValue(Value As System.String, ByRef i64Value As System.Int64) As System.Boolean > Function Microsoft.VisualBasic.CompilerServices.Conversions.ToBoolean(Value As System.Object) As System.Boolean > Function Microsoft.VisualBasic.CompilerServices.Conversions.ToBoolean(Value As System.String) As System.Boolean > Function Microsoft.VisualBasic.CompilerServices.Conversions.ToHalfwidthNumbers(s As System.String, culture As System.Globalization.CultureInfo) As System.String End Class [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.ProjectData > Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError() > Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(ex As System.Exception) End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_SingleSymbol_CompilerServices_Conversions_ToSByte_String() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports Microsoft.VisualBasic Class Program Shared Sub Main(args As String()) Console.Write(CompilerServices.Conversions.ToSByte("77").ToString()) End Sub End Class </file> </compilation>, expectedOutput:="77", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.Conversions > Function Microsoft.VisualBasic.CompilerServices.Conversions.GetCultureInfo() As System.Globalization.CultureInfo > Function Microsoft.VisualBasic.CompilerServices.Conversions.IsHexOrOctValue(Value As System.String, ByRef i64Value As System.Int64) As System.Boolean > Function Microsoft.VisualBasic.CompilerServices.Conversions.ToHalfwidthNumbers(s As System.String, culture As System.Globalization.CultureInfo) As System.String [System.CLSCompliantAttribute] > Function Microsoft.VisualBasic.CompilerServices.Conversions.ToSByte(Value As System.String) As System.SByte End Class [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.ProjectData > Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError() > Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(ex As System.Exception) End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_SingleSymbol_CompilerServices_Conversions_ToSByte_Object() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports Microsoft.VisualBasic Class Program Shared Sub Main(args As String()) Console.Write(CompilerServices.Conversions.ToSByte(directcast("77", Object)).ToString()) End Sub End Class </file> </compilation>, expectedOutput:="77", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.Conversions > Function Microsoft.VisualBasic.CompilerServices.Conversions.GetCultureInfo() As System.Globalization.CultureInfo > Function Microsoft.VisualBasic.CompilerServices.Conversions.IsHexOrOctValue(Value As System.String, ByRef i64Value As System.Int64) As System.Boolean > Function Microsoft.VisualBasic.CompilerServices.Conversions.ToHalfwidthNumbers(s As System.String, culture As System.Globalization.CultureInfo) As System.String [System.CLSCompliantAttribute] > Function Microsoft.VisualBasic.CompilerServices.Conversions.ToSByte(Value As System.Object) As System.SByte [System.CLSCompliantAttribute] > Function Microsoft.VisualBasic.CompilerServices.Conversions.ToSByte(Value As System.String) As System.SByte End Class [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.ProjectData > Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError() > Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(ex As System.Exception) End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_SingleSymbol_CompilerServices_Utils_CopyArray() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports Microsoft.VisualBasic Class Program Shared Sub Main(args As String()) Dim a(10) As String Redim Preserve a(12) Console.Write(a.Length.ToString) End Sub End Class </file> </compilation>, expectedOutput:="13", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.Utils > Function Microsoft.VisualBasic.CompilerServices.Utils.CopyArray(arySrc As System.Array, aryDest As System.Array) As System.Array End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_SingleSymbol_CompilerServices_ObjectFlowControl() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports Microsoft.VisualBasic Class Program Shared Sub Main(args As String()) Console.Write(GetType(CompilerServices.ObjectFlowControl).ToString()) End Sub End Class </file> </compilation>, expectedOutput:="Microsoft.VisualBasic.CompilerServices.ObjectFlowControl", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.ObjectFlowControl > Sub Microsoft.VisualBasic.CompilerServices.ObjectFlowControl..ctor() End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_SingleSymbol_CompilerServices_ObjectFlowControl_ForLoopControl() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports Microsoft.VisualBasic Class Program Shared Sub Main(args As String()) Console.Write(GetType(CompilerServices.ObjectFlowControl.ForLoopControl).ToString()) End Sub End Class </file> </compilation>, expectedOutput:="Microsoft.VisualBasic.CompilerServices.ObjectFlowControl+ForLoopControl", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.ObjectFlowControl > Sub Microsoft.VisualBasic.CompilerServices.ObjectFlowControl..ctor() Class Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl > Sub Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl..ctor() End Class End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_SingleSymbol_CompilerServices_ObjectFlowControl_ForLoopControl_ForNextCheckR8() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports Microsoft.VisualBasic Class Program Shared Sub Main(args As String()) Console.Write(CompilerServices.ObjectFlowControl.ForLoopControl.ForNextCheckR8(CDbl(100), 1, 1)) End Sub End Class </file> </compilation>, expectedOutput:="False", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.ObjectFlowControl > Sub Microsoft.VisualBasic.CompilerServices.ObjectFlowControl..ctor() Class Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl > Function Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl.ForNextCheckR8(count As System.Double, limit As System.Double, StepValue As System.Double) As System.Boolean > Sub Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl..ctor() End Class End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_SingleSymbol_CompilerServices_StaticLocalInitFlag() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports Microsoft.VisualBasic Class Program Shared Sub Main(args As String()) Console.Write(GetType(CompilerServices.StaticLocalInitFlag).ToString()) End Sub End Class </file> </compilation>, expectedOutput:="Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag > Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag.State As System.Int16 > Sub Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag..ctor() End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_SingleSymbol_CompilerServices_StaticLocalInitFlag_State() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports Microsoft.VisualBasic Class Program Shared Sub Main(args As String()) Dim v As New CompilerServices.StaticLocalInitFlag v.State = 1 Console.Write(v.State.ToString()) End Sub End Class </file> </compilation>, expectedOutput:="1", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag > Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag.State As System.Int16 > Sub Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag..ctor() End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_SingleSymbol_CompilerServices_IncompleteInitialization() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports Microsoft.VisualBasic Class Program Shared Sub Main(args As String()) Console.Write(GetType(CompilerServices.IncompleteInitialization).ToString()) End Sub End Class </file> </compilation>, expectedOutput:="Microsoft.VisualBasic.CompilerServices.IncompleteInitialization", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.IncompleteInitialization > Sub Microsoft.VisualBasic.CompilerServices.IncompleteInitialization..ctor() End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_SingleSymbol_CompilerServices_IncompleteInitialization_Throw() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports Microsoft.VisualBasic Class Program Shared Sub Main(args As String()) Try Throw New CompilerServices.IncompleteInitialization() Catch ex As Exception Console.Write(ex.GetType().ToString()) End Try End Sub End Class </file> </compilation>, expectedOutput:="Microsoft.VisualBasic.CompilerServices.IncompleteInitialization", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.IncompleteInitialization > Sub Microsoft.VisualBasic.CompilerServices.IncompleteInitialization..ctor() End Class [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.ProjectData > Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError() > Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(ex As System.Exception) End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_SingleSymbol_CompilerServices_StandardModuleAttribute() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports Microsoft.VisualBasic Imports Microsoft.VisualBasic.CompilerServices &lt;StandardModuleAttribute()&gt; Class Program Shared Sub Main(args As String()) Console.Write("") End Sub End Class </file> </compilation>, expectedOutput:="", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Module Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Module Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute > Sub Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute..ctor() End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_SingleSymbol_CompilerServices_DesignerGeneratedAttribute() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports Microsoft.VisualBasic Imports Microsoft.VisualBasic.CompilerServices &lt;DesignerGeneratedAttribute()&gt; Class Program Shared Sub Main(args As String()) Console.Write("") End Sub End Class </file> </compilation>, expectedOutput:="", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global [Microsoft.VisualBasic.CompilerServices.DesignerGeneratedAttribute] Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.CompilerServices.DesignerGeneratedAttribute > Sub Microsoft.VisualBasic.CompilerServices.DesignerGeneratedAttribute..ctor() End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_SingleSymbol_CompilerServices_OptionCompareAttribute() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports Microsoft.VisualBasic Imports Microsoft.VisualBasic.CompilerServices Class Program Shared Sub Main(&lt;OptionCompareAttribute()&gt;args As String()) Console.Write("") End Sub End Class </file> </compilation>, expectedOutput:="", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.CompilerServices.OptionCompareAttribute > Sub Microsoft.VisualBasic.CompilerServices.OptionCompareAttribute..ctor() End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_SingleSymbol_CompilerServices_OptionTextAttribute() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports Microsoft.VisualBasic Imports Microsoft.VisualBasic.CompilerServices &lt;OptionTextAttribute()&gt; Class Program Shared Sub Main(args As String()) Console.Write("") End Sub End Class </file> </compilation>, expectedOutput:="", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global [Microsoft.VisualBasic.CompilerServices.OptionTextAttribute] Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.CompilerServices.OptionTextAttribute > Sub Microsoft.VisualBasic.CompilerServices.OptionTextAttribute..ctor() End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_SingleSymbol_HideModuleNameAttribute() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports Microsoft.VisualBasic Imports Microsoft.VisualBasic.CompilerServices &lt;HideModuleNameAttribute()&gt; Class Program Shared Sub Main(args As String()) Console.Write("") End Sub End Class </file> </compilation>, expectedOutput:="", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global [Microsoft.VisualBasic.HideModuleNameAttribute] Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.HideModuleNameAttribute > Sub Microsoft.VisualBasic.HideModuleNameAttribute..ctor() End Class End Namespace End Namespace End Namespace </expected>.Value) End Sub) End Sub <Fact()> <WorkItem(544511, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544511")> Public Sub VbCore_SingleSymbol_Strings_AscW_Char() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports Microsoft.VisualBasic Class Program Shared Sub Main(args As String()) Dim ch As Char = "A"c Console.Write(AscW(ch)) End Sub End Class </file> </compilation>, expectedOutput:="65", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_SingleSymbol_Strings_ChrW_Char() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports Microsoft.VisualBasic Class Program Shared Sub Main(args As String()) Dim ch As Integer = 65 Console.Write(ChrW(ch)) End Sub End Class </file> </compilation>, expectedOutput:="A", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Module Microsoft.VisualBasic.Strings > Function Microsoft.VisualBasic.Strings.ChrW(CharCode As System.Int32) As System.Char End Module Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute > Sub Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute..ctor() End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_SingleSymbol_Strings_ChrW_Char_MultipleEmits() Dim compilation = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports Microsoft.VisualBasic Class Program Shared Sub Main(args As String()) Dim ch As Integer = 65 Console.Write(ChrW(ch)) End Sub End Class </file> </compilation>, expectedOutput:="A", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Module Microsoft.VisualBasic.Strings > Function Microsoft.VisualBasic.Strings.ChrW(CharCode As System.Int32) As System.Char End Module Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute > Sub Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute..ctor() End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub).Compilation For i = 0 To 10 Using memory As New MemoryStream() compilation.Emit(memory) End Using Next End Sub <Fact()> Public Sub VbCore_TypesReferencedFromAttributes() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports Microsoft.VisualBasic Imports Microsoft.VisualBasic.CompilerServices &lt;AttributeUsage(AttributeTargets.All)&gt; Class Attr Inherits Attribute Public Sub New(_type As Type) End Sub Public Type As Type End Class &lt;Attr(GetType(Strings), Type:=GetType(Microsoft.VisualBasic.CompilerServices.Conversions))&gt; Module Program Sub Main(args As String()) End Sub End Module </file> </compilation>, expectedOutput:="", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global [System.AttributeUsageAttribute] Class Attr > Attr.Type As System.Type > Sub Attr..ctor(_type As System.Type) End Class [Attr] Module Program [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Module Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Module Microsoft.VisualBasic.Strings End Module Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.Conversions End Class [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute > Sub Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute..ctor() End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_TypesReferencedFromAttributes_Array() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports Microsoft.VisualBasic Imports Microsoft.VisualBasic.CompilerServices &lt;AttributeUsage(AttributeTargets.All)&gt; Class Attr Inherits Attribute Public Types() As Type End Class &lt;Attr(Types:= New Type() {GetType(Conversions), GetType(Strings)})&gt; Module Program Sub Main(args As String()) End Sub End Module </file> </compilation>, expectedOutput:="", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global [System.AttributeUsageAttribute] Class Attr > Attr.Types As System.Type() > Sub Attr..ctor() End Class [Attr] Module Program [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Module Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Module Microsoft.VisualBasic.Strings End Module Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.Conversions End Class [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute > Sub Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute..ctor() End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_EnsurePrivateConstructorsEmitted() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Reflection Imports Microsoft.VisualBasic Module Program Sub Main(args As String()) PrintConstructorInfo(GetType(CompilerServices.EmbeddedOperators)) PrintConstructorInfo(GetType(CompilerServices.Conversions)) PrintConstructorInfo(GetType(CompilerServices.ProjectData)) PrintConstructorInfo(GetType(CompilerServices.Utils)) End Sub Sub PrintConstructorInfo(type As Type) Dim constructor = type.GetConstructors(BindingFlags.Instance Or BindingFlags.NonPublic) Console.Write(type.ToString()) Console.Write(" ") Console.WriteLine(constructor(0).ToString()) End Sub End Module </file> </compilation>, expectedOutput:= <output> Microsoft.VisualBasic.CompilerServices.EmbeddedOperators Void .ctor() Microsoft.VisualBasic.CompilerServices.Conversions Void .ctor() Microsoft.VisualBasic.CompilerServices.ProjectData Void .ctor() Microsoft.VisualBasic.CompilerServices.Utils Void .ctor() </output>.Value.Replace(vbLf, Environment.NewLine), sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Module Program [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) > Sub Program.PrintConstructorInfo(type As System.Type) End Module Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.Conversions End Class [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.EmbeddedOperators End Class [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.ProjectData End Class [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute > Sub Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute..ctor() End Class [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.Utils End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_EmbeddedAttributeOnAssembly_NoReferences() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports Microsoft.VisualBasic Class Program Shared Sub Main(args As String()) For Each attr In GetType(Program).Assembly.GetCustomAttributes(True).ToArray() Dim name = attr.ToString() If name.IndexOf("Embedded") >= 0 Then Console.WriteLine(attr.GetType().ToString()) End If dim x = vbNewLine Next End Sub End Class </file> </compilation>, expectedOutput:="", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_EmbeddedAttributeOnAssembly_References_NoDebug() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports Microsoft.VisualBasic Class Program Shared Sub Main(args As String()) For Each attr In GetType(Program).Assembly.GetCustomAttributes(True).ToArray() Dim name = attr.ToString() If name.IndexOf("Embedded") >= 0 Then Console.WriteLine(attr.GetType().ToString()) End If dim x = GetType(Strings) Next End Sub End Class </file> </compilation>, expectedOutput:="Microsoft.VisualBasic.Embedded", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Module Microsoft.VisualBasic.Strings End Module Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute > Sub Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute..ctor() End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub) End Sub <ConditionalFact(GetType(NoUsedAssembliesValidation))> ' https://github.com/dotnet/roslyn/issues/40683: The test hook is blocked by this issue. <WorkItem(40683, "https://github.com/dotnet/roslyn/issues/40683")> Public Sub VbCore_InvisibleViaInternalsVisibleTo() Dim other As VisualBasicCompilation = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation name="HasIVTToCompilationVbCore"> <file name="a.vb"><![CDATA[ Imports System Imports Microsoft.VisualBasic Imports Microsoft.VisualBasic.CompilerServices <Assembly: System.Runtime.CompilerServices.InternalsVisibleTo("WantsIVTAccessVbCoreAndStillCannot")> Friend Class SourceLibrary Shared Sub Main(args As String()) Console.Write(ChrW(123)) ' Forces Microsoft.VisualBasic.Strings to be embedded into the assembly End Sub Public Shared U As Utils End Class ]]> </file> </compilation>, references:=NoVbRuntimeReferences, options:=TestOptions.ReleaseDll.WithEmbedVbCoreRuntime(True)) CompilationUtils.AssertNoErrors(other) Dim c As VisualBasicCompilation = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation name="WantsIVTAccessVbCoreButCantHave"> <file name="a.vb"><![CDATA[ Public Class A Friend Class B Protected Sub New() Dim a = GetType(Microsoft.VisualBasic.Strings) End Sub End Class End Class ]]> </file> </compilation>, references:=NoVbRuntimeReferences.Concat({New VisualBasicCompilationReference(other)}), options:=TestOptions.ReleaseDll) 'compilation should not succeed, and internals should not be imported. c.GetDiagnostics() CompilationUtils.AssertTheseDiagnostics(c, <error> BC30002: Type 'Microsoft.VisualBasic.Strings' is not defined. Dim a = GetType(Microsoft.VisualBasic.Strings) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </error>) Dim c2 As VisualBasicCompilation = CompilationUtils.CreateCompilationWithMscorlib40AndReferences( <compilation name="WantsIVTAccessVbCoreAndStillCannot"> <file name="a.vb"><![CDATA[ Public Class A Friend Class B Protected Sub New() Dim a = GetType(Microsoft.VisualBasic.Strings) End Sub End Class End Class ]]> </file> </compilation>, references:=NoVbRuntimeReferences.Concat({New VisualBasicCompilationReference(other)}), options:=TestOptions.ReleaseDll) CompilationUtils.AssertTheseDiagnostics(c2, <error> BC30002: Type 'Microsoft.VisualBasic.Strings' is not defined. Dim a = GetType(Microsoft.VisualBasic.Strings) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </error>) End Sub <Fact> Public Sub VbCore_InvisibleViaInternalsVisibleTo2() Dim other As VisualBasicCompilation = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation name="VbCore_InvisibleViaInternalsVisibleTo2"> <file name="a.vb"><![CDATA[ Imports System Imports Microsoft.VisualBasic Imports Microsoft.VisualBasic.CompilerServices <Assembly: System.Runtime.CompilerServices.InternalsVisibleTo("WantsIVTAccessVbCoreAndStillCannot2")> Friend Class SourceLibrary Shared Sub Main(args As String()) Dim a() As String Redim Preserve a(2) End Sub Public Shared U As Utils End Class ]]> </file> </compilation>, references:=NoVbRuntimeReferences, options:=TestOptions.ReleaseDll.WithEmbedVbCoreRuntime(True)) CompilationUtils.AssertNoErrors(other) Dim c As VisualBasicCompilation = CompilationUtils.CreateCompilationWithMscorlib40AndReferences( <compilation name="WantsIVTAccessVbCoreAndStillCannot2"> <file name="a.vb"><![CDATA[ Imports System Imports Microsoft.VisualBasic Imports Microsoft.VisualBasic.CompilerServices Class Program Shared Sub Main(args As String()) SourceLibrary.U.CopyArray(Nothing, Nothing) End Sub End Class ]]> </file> </compilation>, references:=NoVbRuntimeReferences.Concat({New VisualBasicCompilationReference(other)}), options:=TestOptions.ReleaseDll) CompilationUtils.AssertTheseDiagnostics(c, <error> BC30456: 'CopyArray' is not a member of 'Utils'. SourceLibrary.U.CopyArray(Nothing, Nothing) ~~~~~~~~~~~~~~~~~~~~~~~~~ </error>) End Sub <Fact> Public Sub VbCore_InvisibleViaInternalsVisibleTo3() Dim other As VisualBasicCompilation = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation name="VbCore_InvisibleViaInternalsVisibleTo3"> <file name="a.vb"><![CDATA[ Imports System Imports Microsoft.VisualBasic <Assembly: System.Runtime.CompilerServices.InternalsVisibleTo("WantsIVTAccessVbCoreAndStillCannot3")> Friend Class SourceLibrary Shared Sub Main(args As String()) Console.Write(ChrW(args.Length)) End Sub End Class ]]> </file> </compilation>, references:=NoVbRuntimeReferences, options:=TestOptions.ReleaseDll.WithEmbedVbCoreRuntime(True)) CompilationUtils.AssertNoErrors(other) Dim c As VisualBasicCompilation = CompilationUtils.CreateCompilationWithMscorlib40AndReferences( <compilation name="WantsIVTAccessVbCoreAndStillCannot3"> <file name="a.vb"><![CDATA[ Imports System Imports Microsoft.VisualBasic Imports Microsoft.VisualBasic.CompilerServices Class Program Shared Sub Main(args As String()) Console.Write(ChrW(123)) End Sub End Class ]]> </file> </compilation>, references:=NoVbRuntimeReferences.Concat({New VisualBasicCompilationReference(other)}), options:=TestOptions.ReleaseDll) CompilationUtils.AssertTheseDiagnostics(c, <error> BC30451: 'ChrW' is not declared. It may be inaccessible due to its protection level. Console.Write(ChrW(123)) ~~~~ </error>) End Sub <Fact> Public Sub VbCore_InvisibleViaInternalsVisibleTo3_ViaBinary() Dim other As VisualBasicCompilation = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation name="VbCore_InvisibleViaInternalsVisibleTo3"> <file name="a.vb"><![CDATA[ Imports System Imports Microsoft.VisualBasic <Assembly: System.Runtime.CompilerServices.InternalsVisibleTo("WantsIVTAccessVbCoreAndStillCannot3")> Friend Class SourceLibrary Shared Sub Main(args As String()) Console.Write(ChrW(args.Length)) End Sub End Class ]]> </file> </compilation>, references:=NoVbRuntimeReferences, options:=TestOptions.ReleaseDll.WithEmbedVbCoreRuntime(True)) CompilationUtils.AssertNoErrors(other) Dim memory As New MemoryStream() other.Emit(memory) Dim c As VisualBasicCompilation = CompilationUtils.CreateCompilationWithMscorlib40AndReferences( (<compilation name="WantsIVTAccessVbCoreAndStillCannot3"> <file name="a.vb"><![CDATA[ Imports System Imports Microsoft.VisualBasic Class Program Shared Sub Main(args As String()) Console.Write(ChrW(123)) End Sub End Class ]]> </file> </compilation>), references:=NoVbRuntimeReferences.Concat({MetadataReference.CreateFromImage(memory.ToImmutable())}), options:=TestOptions.ReleaseDll) CompilationUtils.AssertTheseDiagnostics(c, <error> BC30451: 'ChrW' is not declared. It may be inaccessible due to its protection level. Console.Write(ChrW(123)) ~~~~ </error>) End Sub <Fact> Public Sub VbCore_EmbeddedVbCoreWithIVToAndRuntime() Dim other As VisualBasicCompilation = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation name="VbCore_EmbeddedVbCoreWithIVToAndRuntime"> <file name="a.vb"><![CDATA[ <Assembly: System.Runtime.CompilerServices.InternalsVisibleTo("WantsIVTAccessVbCoreAndStillCannot3")> ]]> </file> </compilation>, references:=NoVbRuntimeReferences, options:=TestOptions.ReleaseDll.WithEmbedVbCoreRuntime(True)) CompilationUtils.AssertNoErrors(other) MyBase.CompileAndVerify(source:= <compilation> <file name="a.vb"> Imports System Imports Microsoft.VisualBasic Imports Microsoft.VisualBasic.CompilerServices Class Program Shared Sub Main(args As String()) Try Dim s As String = "123" Dim i As Integer = s ' This should use Conversions.ToInteger(String) Catch e As Exception ' This should use ProjectData.SetProjectError()/ClearProjectError() End Try End Sub End Class </file> </compilation>, allReferences:=NoVbRuntimeReferences.Concat(MsvbRef).Concat(New VisualBasicCompilationReference(other)), expectedOutput:="", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class End Namespace </expected>.Value) End Sub, options:=TestOptions.ReleaseExe.WithMetadataImportOptions(MetadataImportOptions.Internal)) End Sub <Fact()> Public Sub VbCore_CompilationOptions() Dim withoutVbCore As VisualBasicCompilation = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation name="VbCore_CompilationOptions1"> <file name="a.vb"><![CDATA[ Imports System Imports Microsoft.VisualBasic Friend Class SourceLibrary Shared Sub Main(args As String()) Console.Write(ChrW(123)) End Sub End Class ]]> </file> </compilation>, references:=NoVbRuntimeReferences, options:=TestOptions.ReleaseDll.WithEmbedVbCoreRuntime(False)) CompilationUtils.AssertTheseDiagnostics(withoutVbCore, <error> BC30451: 'ChrW' is not declared. It may be inaccessible due to its protection level. Console.Write(ChrW(123)) ~~~~ </error>) Dim withVbCore As VisualBasicCompilation = withoutVbCore.WithOptions(withoutVbCore.Options.WithEmbedVbCoreRuntime(True)) CompilationUtils.AssertNoErrors(withVbCore) Dim withoutVbCore2 As VisualBasicCompilation = withVbCore.WithOptions(withVbCore.Options.WithEmbedVbCoreRuntime(False)) CompilationUtils.AssertTheseDiagnostics(withoutVbCore2, <error> BC30451: 'ChrW' is not declared. It may be inaccessible due to its protection level. Console.Write(ChrW(123)) ~~~~ </error>) Dim withVbCore2 As VisualBasicCompilation = withoutVbCore.WithOptions(withoutVbCore2.Options.WithEmbedVbCoreRuntime(True)) CompilationUtils.AssertNoErrors(withVbCore2) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub NoDebugInfoForVbCoreSymbols() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports Microsoft.VisualBasic Class Program Shared Sub Main(args As String()) Dim ch As Integer = 65 Console.Write(ChrW(ch)) End Sub End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugExe.WithEmbedVbCoreRuntime(True)) compilation.VerifyPdb( <symbols> <files> <file id="1" name="a.vb" language="VB" checksumAlgorithm="SHA1" checksum="43-DF-02-C2-F5-5F-6A-CB-08-D3-1F-D2-8E-4F-FE-0A-8F-C2-76-D7"/> </files> <entryPoint declaringType="Program" methodName="Main" parameterNames="args"/> <methods> <method containingType="Program" name="Main" parameterNames="args"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="5" startColumn="5" endLine="5" endColumn="38" document="1"/> <entry offset="0x1" startLine="6" startColumn="13" endLine="6" endColumn="31" document="1"/> <entry offset="0x4" startLine="7" startColumn="9" endLine="7" endColumn="32" document="1"/> <entry offset="0x10" startLine="8" startColumn="5" endLine="8" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x11"> <namespace name="System" importlevel="file"/> <namespace name="Microsoft.VisualBasic" importlevel="file"/> <currentnamespace name=""/> <local name="ch" il_index="0" il_start="0x0" il_end="0x11" attributes="0"/> </scope> </method> </methods> </symbols>) End Sub <Fact> Public Sub VbCoreTypeAndUserPartialTypeConflict() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndReferences( <compilation> <file name="a.vb"> Imports System Imports Microsoft.VisualBasic Namespace Global.Microsoft.VisualBasic Partial Friend Class HideModuleNameAttribute Public Property A As String End Class End Namespace </file> </compilation>, references:={SystemRef, SystemCoreRef}, options:=TestOptions.ReleaseDll.WithEmbedVbCoreRuntime(True)) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC31210: class 'HideModuleNameAttribute' conflicts with a Visual Basic Runtime class 'HideModuleNameAttribute'. Partial Friend Class HideModuleNameAttribute ~~~~~~~~~~~~~~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub VbCoreTypeAndUserTypeConflict() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndReferences( <compilation> <file name="a.vb"> Imports System Imports Microsoft.VisualBasic Namespace Global.Microsoft.VisualBasic Friend Class HideModuleNameAttribute Public Property A As String End Class End Namespace </file> </compilation>, references:={SystemRef, SystemCoreRef}, options:=TestOptions.ReleaseDll.WithEmbedVbCoreRuntime(True)) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC31210: class 'HideModuleNameAttribute' conflicts with a Visual Basic Runtime class 'HideModuleNameAttribute'. Friend Class HideModuleNameAttribute ~~~~~~~~~~~~~~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub VbCoreNamespaceAndUserTypeConflict() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndReferences( <compilation> <file name="a.vb"> Imports System Imports Microsoft.VisualBasic Namespace Global.Microsoft Friend Class VisualBasic Public Property A As String End Class End Namespace </file> </compilation>, references:={SystemRef, SystemCoreRef}, options:=TestOptions.ReleaseDll.WithEmbedVbCoreRuntime(True)) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC31210: class 'VisualBasic' conflicts with a Visual Basic Runtime namespace 'VisualBasic'. Friend Class VisualBasic ~~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub VbCoreTypeAndUserNamespaceConflict() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndReferences( <compilation> <file name="a.vb"> Imports System Imports Microsoft.VisualBasic Namespace Global.Microsoft.VisualBasic.Strings Partial Friend Class VisualBasic Public Property A As String End Class End Namespace </file> </compilation>, references:={SystemRef, SystemCoreRef}, options:=TestOptions.ReleaseDll.WithEmbedVbCoreRuntime(True)) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC31210: namespace 'Strings' conflicts with a Visual Basic Runtime module 'Strings'. Namespace Global.Microsoft.VisualBasic.Strings ~~~~~~~ </errors>) End Sub <Fact> Public Sub VbCoreTypeAndUserNamespaceConflict2() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndReferences( <compilation> <file name="a.vb"> Imports System Imports Microsoft.VisualBasic Module Module1 Sub Main() Call Console.WriteLine(GetType(Strings).ToString()) End Sub End Module Namespace Global.Microsoft.VisualBasic.Strings Partial Friend Class VisualBasic Public Property A As String End Class End Namespace </file> </compilation>, references:={SystemRef, SystemCoreRef}, options:=TestOptions.ReleaseDll.WithEmbedVbCoreRuntime(True)) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC30560: 'Strings' is ambiguous in the namespace 'Microsoft.VisualBasic'. Call Console.WriteLine(GetType(Strings).ToString()) ~~~~~~~ BC31210: namespace 'Strings' conflicts with a Visual Basic Runtime module 'Strings'. Namespace Global.Microsoft.VisualBasic.Strings ~~~~~~~ </errors>) End Sub <Fact> Public Sub VbCoreTypeAndUserNamespaceConflict3() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndReferences( <compilation> <file name="a.vb"> Imports System Imports Microsoft.VisualBasic Module Module1 Sub Main() End Sub End Module Namespace Global.Microsoft.VisualBasic.Strings Partial Friend Class VisualBasic Public Property A As String End Class End Namespace </file> <file name="b.vb"> Imports System Namespace Global.Microsoft Namespace VisualBasic Namespace Strings Partial Friend Class Other End Class End Namespace End Namespace End Namespace </file> </compilation>, references:={SystemRef, SystemCoreRef}, options:=TestOptions.ReleaseDll.WithEmbedVbCoreRuntime(True)) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC31210: namespace 'Strings' conflicts with a Visual Basic Runtime module 'Strings'. Namespace Global.Microsoft.VisualBasic.Strings ~~~~~~~ </errors>) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:="https://github.com/dotnet/roslyn/issues/29531")> Public Sub VbRuntimeTypeAndUserNamespaceConflictOutsideOfVBCore() ' This verifies the diagnostic BC31210 scenario outsides of using VB Core which ' is triggered by the Embedded Attribute. This occurs on the command line compilers ' when the reference to system.xml.linq is added Dim compilationOptions = TestOptions.ReleaseExe.WithGlobalImports(GlobalImport.Parse({"System", "Microsoft.VisualBasic"})) Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="testa.vb"> Imports Microsoft.VisualBasic Module Module1 Sub Main() Dim x1 = Microsoft.VisualBasic.InStr("abcd", 1) Dim x2 = &lt;test/&gt; End Sub End Module Namespace global.Microsoft Public Module VisualBasic End Module End Namespace </file> </compilation>, options:=compilationOptions, references:={SystemCoreRef, SystemXmlLinqRef, SystemXmlRef}) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors>BC30560: Error in project-level import 'Microsoft.VisualBasic' at 'Microsoft.VisualBasic' : 'VisualBasic' is ambiguous in the namespace 'Microsoft'. BC30560: 'VisualBasic' is ambiguous in the namespace 'Microsoft'. BC30560: 'VisualBasic' is ambiguous in the namespace 'Microsoft'. BC30560: 'VisualBasic' is ambiguous in the namespace 'Microsoft'. Imports Microsoft.VisualBasic ~~~~~~~~~~~~~~~~~~~~~ BC30560: 'VisualBasic' is ambiguous in the namespace 'Microsoft'. Dim x1 = Microsoft.VisualBasic.InStr("abcd", 1) ~~~~~~~~~~~~~~~~~~~~~ BC31210: module 'VisualBasic' conflicts with a Visual Basic Runtime namespace 'VisualBasic'. Public Module VisualBasic ~~~~~~~~~~~ </errors>) ' Remove the reference to System.XML.Linq and verify compilation behavior that the ' diagnostic is not produced. compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="testa.vb"> Imports Microsoft.VisualBasic Module Module1 Sub Main() Dim x1 = Microsoft.VisualBasic.InStr("abcd", 1) End Sub End Module Namespace global.Microsoft Public Module VisualBasic End Module End Namespace </file> </compilation>, options:=compilationOptions) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors>BC30456: 'InStr' is not a member of 'VisualBasic'. Dim x1 = Microsoft.VisualBasic.InStr("abcd", 1) ~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub VbCore_IsImplicitlyDeclaredSymbols() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndReferences( <compilation> <file name="a.vb"> </file> </compilation>, references:={SystemRef, SystemCoreRef}, options:=TestOptions.ReleaseDll.WithEmbedVbCoreRuntime(True)) CompilationUtils.AssertTheseDiagnostics(compilation, <errors></errors>) Dim vbCoreType = compilation.GetTypeByMetadataName("Microsoft.VisualBasic.Embedded") Assert.NotNull(vbCoreType) Dim namespacesToCheck As New Queue(Of NamespaceSymbol)() namespacesToCheck.Enqueue(vbCoreType.ContainingNamespace) While namespacesToCheck.Count > 0 Dim ns = namespacesToCheck.Dequeue() For Each member In ns.GetMembers() Select Case member.Kind Case SymbolKind.NamedType AssertTypeAndItsMembersAreImplicitlyDeclared(DirectCast(member, NamedTypeSymbol)) Case SymbolKind.Namespace namespacesToCheck.Enqueue(DirectCast(member, NamespaceSymbol)) End Select Next End While End Sub <Fact()> Public Sub InternalXmlHelper_IsImplicitlyDeclaredSymbols() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Module M Dim x = <x/>.<y>.Value End Module ]]></file> </compilation>, references:=XmlReferences) compilation.AssertNoErrors() Dim type = compilation.GetTypeByMetadataName("My.InternalXmlHelper") AssertTypeAndItsMembersAreImplicitlyDeclared(type) End Sub Private Sub IsImplicitlyDeclaredSymbols([namespace] As NamespaceSymbol) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact> Public Sub VbCoreWithStaticLocals_UsingEmbedVBCore() 'Static Locals use types contained within VB Runtime so verify with VBCore option to ensure the feature works 'using VBCore which would be the case with platforms such as Phone. Dim compilation As VisualBasicCompilation = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation> <file name="a.vb"> Imports System Imports Microsoft.VisualBasic Module Module1 Sub Main() Goo() Goo() End Sub Sub Goo() Static x as integer = 1 x+=1 End Sub End Module </file> </compilation>, references:=NoVbRuntimeReferences, options:=TestOptions.ReleaseDll.WithEmbedVbCoreRuntime(True)) CompilationUtils.AssertNoErrors(compilation) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact> Public Sub VbCoreWithStaticLocals_NoRequiredTypes() 'Static Locals use types in VB Runtime so verify with no VBRuntime we generate applicable errors about missing types. 'This will include types for Module as well as static locals Dim compilation As VisualBasicCompilation = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation> <file name="a.vb"> Module Module1 Sub Main() Goo() Goo() End Sub Sub Goo() Static x as integer = 1 x+=1 End Sub End Module </file> </compilation>, references:=NoVbRuntimeReferences, options:=TestOptions.ReleaseDll.WithEmbedVbCoreRuntime(False)) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_MissingRuntimeHelper, "Module1").WithArguments("Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute..ctor")) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact> Public Sub VbCoreWithStaticLocals_CorrectDefinedTypes() 'Static Locals use types in VB Runtime so verify with no VBRuntime but appropriate types specified in Source the static 'local scenarios should work correctly. Dim compilation As VisualBasicCompilation = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation> <file name="a.vb"> Imports System Imports Microsoft.VisualBasic Public Class Module1 Public shared Sub Main() Goo() Goo() End Sub shared Sub Goo() Static x as integer = 1 x+=1 End Sub End Class Namespace Global.Microsoft.VisualBasic.CompilerServices Friend Class StaticLocalInitFlag Public State As Short End Class Friend Class IncompleteInitialization Inherits System.Exception Public Sub New() MyBase.New() End Sub End Class End Namespace </file> </compilation>, references:=NoVbRuntimeReferences, options:=TestOptions.ReleaseDll.WithEmbedVbCoreRuntime(False)) compilation.AssertNoDiagnostics() End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact> Public Sub VbCoreWithStaticLocals_IncorrectDefinedTypes() 'Static Locals use types in VB Runtime so verify with no VBRuntime but appropriate types specified in Source the static 'local scenarios should work correctly but if we define the types incorrectly we should generate errors although we 'should not crash. Dim compilation As VisualBasicCompilation = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation> <file name="a.vb"> Public Class Module1 Public shared Sub Main() Goo() Goo() End Sub shared Sub Goo() Static x as integer = 1 x+=1 End Sub End Class Namespace Global.Microsoft.VisualBasic.CompilerServices Friend Class StaticLocalInitFlag Public State As Short End Class Friend Structure IncompleteInitialization Inherits System.Exception Public Sub New() MyBase.New() End Sub End Structure End Namespace </file> </compilation>, references:=NoVbRuntimeReferences, options:=TestOptions.ReleaseDll.WithEmbedVbCoreRuntime(False)) compilation.VerifyDiagnostics( Diagnostic(ERRID.ERR_NewInStruct, "New").WithLocation(20, 24), Diagnostic(ERRID.ERR_StructCantInherit, "Inherits System.Exception").WithLocation(19, 13), Diagnostic(ERRID.ERR_UseOfKeywordFromStructure1, "MyBase").WithArguments("MyBase").WithLocation(21, 17) ) End Sub Private Sub AssertTypeAndItsMembersAreImplicitlyDeclared(type As NamedTypeSymbol) Assert.True(type.IsImplicitlyDeclared) Assert.True(type.IsEmbedded) For Each member In type.GetMembers() Assert.True(member.IsEmbedded) Assert.True(member.IsImplicitlyDeclared) Select Case member.Kind Case SymbolKind.Field, SymbolKind.Property Case SymbolKind.Method For Each param In DirectCast(member, MethodSymbol).Parameters Assert.True(param.IsEmbedded) Assert.True(param.IsImplicitlyDeclared) Next For Each typeParam In DirectCast(member, MethodSymbol).TypeParameters Assert.True(typeParam.IsEmbedded) Assert.True(typeParam.IsImplicitlyDeclared) Next Case SymbolKind.NamedType AssertTypeAndItsMembersAreImplicitlyDeclared(DirectCast(member, NamedTypeSymbol)) Case Else Assert.False(True) ' Unexpected member. End Select Next End Sub <Fact, WorkItem(544291, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544291")> Public Sub VbCoreSyncLockOnObject() CompileAndVerify( <compilation> <file name="a.vb"> Module Module1 Private SyncObj As Object = New Object() Sub Main() SyncLock SyncObj End SyncLock End Sub End Module </file> </compilation>).VerifyIL("Module1.Main", <![CDATA[ { // Code size 29 (0x1d) .maxstack 2 .locals init (Object V_0, Boolean V_1) IL_0000: ldsfld "Module1.SyncObj As Object" IL_0005: stloc.0 IL_0006: ldc.i4.0 IL_0007: stloc.1 .try { IL_0008: ldloc.0 IL_0009: ldloca.s V_1 IL_000b: call "Sub System.Threading.Monitor.Enter(Object, ByRef Boolean)" IL_0010: leave.s IL_001c } finally { IL_0012: ldloc.1 IL_0013: brfalse.s IL_001b IL_0015: ldloc.0 IL_0016: call "Sub System.Threading.Monitor.Exit(Object)" IL_001b: endfinally } IL_001c: ret } ]]>) End Sub <Fact(), WorkItem(545772, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545772")> Public Sub VbCoreNoStdLib() Dim source = <compilation> <file name="a.vb"> Module Class1 Public Sub Main() End Sub End Module </file> </compilation> CreateCompilationWithMscorlib40( source, options:=TestOptions.ReleaseExe.WithEmbedVbCoreRuntime(True)). VerifyDiagnostics( Diagnostic(ERRID.ERR_UndefinedType1).WithArguments("Global.System.ComponentModel.EditorBrowsable"), Diagnostic(ERRID.ERR_NameNotMember2).WithArguments("ComponentModel", "System"), Diagnostic(ERRID.ERR_UndefinedType1).WithArguments("Global.System.ComponentModel.EditorBrowsable"), Diagnostic(ERRID.ERR_NameNotMember2).WithArguments("ComponentModel", "System"), Diagnostic(ERRID.ERR_UndefinedType1).WithArguments("Global.System.ComponentModel.EditorBrowsable"), Diagnostic(ERRID.ERR_NameNotMember2).WithArguments("ComponentModel", "System"), Diagnostic(ERRID.ERR_UndefinedType1).WithArguments("Global.System.ComponentModel.EditorBrowsable"), Diagnostic(ERRID.ERR_NameNotMember2).WithArguments("ComponentModel", "System"), Diagnostic(ERRID.ERR_UndefinedType1).WithArguments("Global.System.ComponentModel.EditorBrowsable"), Diagnostic(ERRID.ERR_NameNotMember2).WithArguments("ComponentModel", "System"), Diagnostic(ERRID.ERR_UndefinedType1).WithArguments("Global.System.ComponentModel.EditorBrowsable"), Diagnostic(ERRID.ERR_NameNotMember2).WithArguments("ComponentModel", "System"), Diagnostic(ERRID.ERR_UndefinedType1).WithArguments("Global.System.ComponentModel.EditorBrowsable"), Diagnostic(ERRID.ERR_NameNotMember2).WithArguments("ComponentModel", "System"), Diagnostic(ERRID.ERR_UndefinedType1).WithArguments("Global.System.ComponentModel.EditorBrowsable"), Diagnostic(ERRID.ERR_NameNotMember2).WithArguments("ComponentModel", "System"), Diagnostic(ERRID.ERR_UndefinedType1).WithArguments("Global.System.ComponentModel.EditorBrowsable"), Diagnostic(ERRID.ERR_NameNotMember2).WithArguments("ComponentModel", "System"), Diagnostic(ERRID.ERR_UndefinedType1).WithArguments("Global.System.ComponentModel.EditorBrowsable"), Diagnostic(ERRID.ERR_NameNotMember2).WithArguments("ComponentModel", "System"), Diagnostic(ERRID.ERR_UndefinedType1).WithArguments("Global.System.ComponentModel.EditorBrowsable"), Diagnostic(ERRID.ERR_NameNotMember2).WithArguments("ComponentModel", "System"), Diagnostic(ERRID.ERR_UndefinedType1).WithArguments("Global.System.ComponentModel.EditorBrowsable"), Diagnostic(ERRID.ERR_NameNotMember2).WithArguments("ComponentModel", "System"), Diagnostic(ERRID.ERR_UndefinedType1).WithArguments("Global.System.ComponentModel.EditorBrowsable"), Diagnostic(ERRID.ERR_NameNotMember2).WithArguments("ComponentModel", "System")) End Sub #Region "Symbols Validator" Private Shared ReadOnly s_normalizeRegex As New Regex("^(\s*)", RegexOptions.Multiline) Private Sub ValidateSourceSymbols([module] As ModuleSymbol) ValidateSourceSymbol([module].GlobalNamespace) End Sub Private Sub ValidateSourceSymbol(symbol As Symbol) For Each reference In symbol.DeclaringSyntaxReferences Assert.False(reference.SyntaxTree.IsEmbeddedOrMyTemplateTree()) Next Select Case symbol.Kind Case SymbolKind.Namespace Dim [namespace] = DirectCast(symbol, NamespaceSymbol) For Each _type In From x In [namespace].GetTypeMembers() Select x Order By x.Name.ToLower() ValidateSourceSymbol(_type) Next For Each _ns In From x In [namespace].GetNamespaceMembers() Select x Order By x.Name.ToLower() ValidateSourceSymbol(_ns) Next Case SymbolKind.NamedType Dim type = DirectCast(symbol, NamedTypeSymbol) For Each _member In From x In type.GetMembers() Where x.Kind <> SymbolKind.NamedType Select x Order By x.ToTestDisplayString() ValidateSourceSymbol(_member) Next For Each _nested In From x In type.GetTypeMembers() Select x Order By x.Name.ToLower() ValidateSourceSymbol(_nested) Next End Select End Sub Private Sub ValidateSymbols([module] As ModuleSymbol, expected As String) Dim actualBuilder As New StringBuilder CollectAllTypesAndMembers([module].GlobalNamespace, actualBuilder, "") expected = expected.Trim() ' normalize Dim matches = s_normalizeRegex.Matches(expected) Dim captures = matches(matches.Count - 1).Groups(1).Captures Dim indent = captures(captures.Count - 1).Value If indent.Length > 0 Then expected = New Regex("^" + indent, RegexOptions.Multiline).Replace(expected, "") End If Dim actual = actualBuilder.ToString.Trim() If expected.Replace(vbLf, Environment.NewLine).CompareTo(actual) <> 0 Then Console.WriteLine("Actual:") Console.WriteLine(actual) Console.WriteLine() Console.WriteLine("Diff:") Console.WriteLine(DiffUtil.DiffReport(expected, actual)) Console.WriteLine() Assert.True(False) End If End Sub Private Sub AddSymbolAttributes(symbol As Symbol, builder As StringBuilder, indent As String) For Each attribute In symbol.GetAttributes() builder.AppendLine(indent + "[" + attribute.AttributeClass.ToTestDisplayString() + "]") Next End Sub Private Sub CollectAllTypesAndMembers(symbol As Symbol, builder As StringBuilder, indent As String) Const IndentStep = " " Select Case symbol.Kind Case SymbolKind.Namespace Dim [namespace] = DirectCast(symbol, NamespaceSymbol) builder.AppendLine(indent + "Namespace " + symbol.ToTestDisplayString) For Each _type In From x In [namespace].GetTypeMembers() Select x Order By x.Name.ToLower() CollectAllTypesAndMembers(_type, builder, indent + IndentStep) Next For Each _ns In From x In [namespace].GetNamespaceMembers() Select x Order By x.Name.ToLower() CollectAllTypesAndMembers(_ns, builder, indent + IndentStep) Next builder.AppendLine(indent + "End Namespace") Case SymbolKind.NamedType If symbol.Name <> "<Module>" Then AddSymbolAttributes(symbol, builder, indent) Dim type = DirectCast(symbol, NamedTypeSymbol) builder.AppendLine(indent + type.TypeKind.ToString() + " " + symbol.ToTestDisplayString) For Each _member In From x In type.GetMembers() Where x.Kind <> SymbolKind.NamedType Select x Order By x.ToTestDisplayString() AddSymbolAttributes(_member, builder, indent + IndentStep + " ") builder.AppendLine(indent + IndentStep + "> " + _member.ToTestDisplayString()) Next For Each _nested In From x In type.GetTypeMembers() Select x Order By x.Name.ToLower() CollectAllTypesAndMembers(_nested, builder, indent + IndentStep) Next builder.AppendLine(indent + "End " + type.TypeKind.ToString()) End If End Select End Sub #End Region #Region "Utilities" Protected NoVbRuntimeReferences As MetadataReference() = {MscorlibRef, SystemRef, SystemCoreRef} Friend Shadows Function CompileAndVerify( source As XElement, Optional expectedOutput As String = Nothing, Optional sourceSymbolValidator As Action(Of ModuleSymbol) = Nothing, Optional validator As Action(Of PEAssembly) = Nothing, Optional symbolValidator As Action(Of ModuleSymbol) = Nothing ) As CompilationVerifier Dim options = If(expectedOutput IsNot Nothing, TestOptions.ReleaseExe, TestOptions.ReleaseDll). WithMetadataImportOptions(MetadataImportOptions.Internal). WithEmbedVbCoreRuntime(True) Return MyBase.CompileAndVerify(source:=source, allReferences:=NoVbRuntimeReferences, expectedOutput:=expectedOutput, sourceSymbolValidator:=sourceSymbolValidator, validator:=validator, symbolValidator:=symbolValidator, options:=options) End Function #End Region End Class End Namespace
' 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.IO Imports System.Text Imports System.Text.RegularExpressions Imports System.Xml.Linq Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class CodeGenVBCore Inherits BasicTestBase ' The Embedded attribute should only be available ' if other embedded code is included. <Fact()> Public Sub EmbeddedAttributeRequiresOtherEmbeddedCode() Dim sources = <compilation> <file name="c.vb"><![CDATA[ Option Strict On <Microsoft.VisualBasic.Embedded()> Class C End Class ]]></file> </compilation> ' With InternalXmlHelper. Dim compilation = CreateCompilationWithMscorlib40AndReferences(sources, references:=NoVbRuntimeReferences.Concat(XmlReferences), options:=TestOptions.ReleaseDll.WithEmbedVbCoreRuntime(True)) compilation.AssertNoErrors() ' With VBCore. compilation = CreateCompilationWithMscorlib40AndReferences(sources, references:=NoVbRuntimeReferences, options:=TestOptions.ReleaseDll.WithEmbedVbCoreRuntime(True)) compilation.AssertNoErrors() ' No embedded code. compilation = CreateCompilationWithMscorlib40AndReferences(sources, references:=NoVbRuntimeReferences, options:=TestOptions.ReleaseDll) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC30002: Type 'Microsoft.VisualBasic.Embedded' is not defined. <Microsoft.VisualBasic.Embedded()> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></errors>) End Sub ' The Embedded attribute should only be available for ' user-define code if vb runtime is included. <WorkItem(546059, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546059")> <Fact()> Public Sub EmbeddedAttributeRequiresOtherEmbeddedCode2() Dim sources = <compilation> <file name="c.vb"><![CDATA[ Option Strict On <Microsoft.VisualBasic.Embedded()> Class C End Class ]]></file> </compilation> ' No embedded code. Dim compilation = CreateCompilationWithMscorlib40AndReferences(sources, references:=NoVbRuntimeReferences.Concat({MsvbRef, SystemXmlRef, SystemXmlLinqRef}), options:=TestOptions.ReleaseDll) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC30002: Type 'Microsoft.VisualBasic.Embedded' is not defined. <Microsoft.VisualBasic.Embedded()> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></errors>) End Sub ' The Embedded attribute should only be available for ' user-define code if vb runtime is included. <WorkItem(546059, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546059")> <Fact()> Public Sub EmbeddedAttributeRequiresOtherEmbeddedCode3() Dim sources = <compilation> <file name="c.vb"><![CDATA[ Option Strict On Class C Public x As Microsoft.VisualBasic.Embedded End Class ]]></file> </compilation> ' No embedded code. Dim compilation = CreateCompilationWithMscorlib40AndReferences(sources, references:=NoVbRuntimeReferences.Concat({MsvbRef, SystemXmlRef, SystemXmlLinqRef}), options:=TestOptions.ReleaseDll) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC30002: Type 'Microsoft.VisualBasic.Embedded' is not defined. Public x As Microsoft.VisualBasic.Embedded ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></errors>) End Sub <Fact()> Public Sub InternalXmlHelper_NoReferences() Dim compilationVerifier = MyBase.CompileAndVerify(source:= <compilation> <file name="c.vb"><![CDATA[ Option Strict On Class C End Class ]]></file> </compilation>, allReferences:=NoVbRuntimeReferences, sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class C > Sub C..ctor() End Class End Namespace </expected>.Value) End Sub, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal)) compilationVerifier.Compilation.AssertNoErrors() End Sub <Fact()> Public Sub InternalXmlHelper_NoSymbols() Dim compilationVerifier = MyBase.CompileAndVerify(source:= <compilation> <file name="c.vb"><![CDATA[ Option Strict On Class C End Class ]]></file> </compilation>, allReferences:=NoVbRuntimeReferences.Concat(XmlReferences), sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class C > Sub C..ctor() End Class End Namespace </expected>.Value) End Sub, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal)) compilationVerifier.Compilation.AssertNoErrors() End Sub <Fact()> Public Sub InternalXmlHelper_CreateNamespaceAttribute_NoDebug() Dim symbols = <expected> Namespace Global Class C > C.F As System.Object > Sub C..ctor() End Class Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class End Namespace End Namespace Namespace My [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class My.InternalXmlHelper [System.ComponentModel.EditorBrowsableAttribute] > Function My.InternalXmlHelper.CreateNamespaceAttribute(name As System.Xml.Linq.XName, ns As System.Xml.Linq.XNamespace) As System.Xml.Linq.XAttribute End Class End Namespace End Namespace </expected>.Value Dim compilationVerifier = MyBase.CompileAndVerify(source:= <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports <xmlns:p="http://roslyn/"> Class C Public Shared F As Object = <p:x/> End Class ]]></file> </compilation>, allReferences:=NoVbRuntimeReferences.Concat(XmlReferences), sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], symbols), options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal)) compilationVerifier.Compilation.AssertNoErrors() End Sub <WorkItem(545438, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545438"), WorkItem(546887, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546887")> <Fact()> Public Sub InternalXmlHelper_ValueProperty() Dim symbols = <expected> Namespace Global Class C > Sub C..ctor() > Sub C.M(x As System.Xml.Linq.XElement) End Class Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class End Namespace End Namespace Namespace My [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class My.InternalXmlHelper > Function My.InternalXmlHelper.get_AttributeValue(source As System.Xml.Linq.XElement, name As System.Xml.Linq.XName) As System.String > Function My.InternalXmlHelper.get_Value(source As System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)) As System.String > Property My.InternalXmlHelper.AttributeValue(source As System.Xml.Linq.XElement, name As System.Xml.Linq.XName) As System.String > Property My.InternalXmlHelper.Value(source As System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)) As System.String > Sub My.InternalXmlHelper.set_AttributeValue(source As System.Xml.Linq.XElement, name As System.Xml.Linq.XName, value As System.String) > Sub My.InternalXmlHelper.set_Value(source As System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement), value As System.String) End Class End Namespace End Namespace </expected>.Value Dim compilationVerifier = MyBase.CompileAndVerify(source:= <compilation> <file name="c.vb"><![CDATA[ Option Strict On Class C Shared Sub M(x As System.Xml.Linq.XElement) x.@a = x.<y>.Value End Sub End Class ]]></file> </compilation>, allReferences:=NoVbRuntimeReferences.Concat(XmlReferences), symbolValidator:=Sub([module]) ValidateSymbols([module], symbols), sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal)) compilationVerifier.Compilation.AssertNoErrors() End Sub <Fact()> Public Sub InternalXmlHelper_Locations() Dim compilation = CreateCompilationWithMscorlib40AndReferences( <compilation> <file name="c.vb"><![CDATA[ Class C Public Shared F As Object = <x xmlns:p="http://roslyn"/> End Class ]]></file> </compilation>, references:=NoVbRuntimeReferences.Concat(XmlReferences), options:=TestOptions.ReleaseDll.WithEmbedVbCoreRuntime(True)) compilation.AssertNoErrors() Dim globalNamespace = compilation.SourceModule.GlobalNamespace Assert.Equal(globalNamespace.Locations.Length, 4) Dim [namespace] = globalNamespace.GetMember(Of NamespaceSymbol)("My") Assert.Equal([namespace].Locations.Length, 1) Dim type = [namespace].GetMember(Of NamedTypeSymbol)("InternalXmlHelper") Assert.Equal(type.Locations.Length, 1) End Sub <Fact()> Public Sub VbCore_NoSymbols() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports Microsoft.VisualBasic Class Program Shared Sub Main(args As String()) End Sub End Class </file> </compilation>, expectedOutput:="", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_SingleSymbol_SymbolInGetType() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports System.Collections.Generic Imports Microsoft.VisualBasic Imports Microsoft.VisualBasic.CompilerServices Class Program Shared Sub Main(args As String()) Console.Write(GetType(List(Of List(Of StandardModuleAttribute))).ToString()) End Sub End Class </file> </compilation>, expectedOutput:="System.Collections.Generic.List`1[System.Collections.Generic.List`1[Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute]]", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute > Sub Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute..ctor() End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_SingleSymbol_Constants() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports Microsoft.VisualBasic Class Program Shared Sub Main(args As String()) Console.Write(GetType(Constants).ToString()) End Sub End Class </file> </compilation>, expectedOutput:="Microsoft.VisualBasic.Constants", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Module Microsoft.VisualBasic.Constants End Module [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute > Sub Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute..ctor() End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_SingleSymbol_Constants_WithVbRuntime() MyBase.CompileAndVerify(source:= <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports Microsoft.VisualBasic Class Program Shared Sub Main(args As String()) Console.Write(GetType(Constants).ToString()) End Sub End Class </file> </compilation>, allReferences:=NoVbRuntimeReferences.Concat(MsvbRef), expectedOutput:="Microsoft.VisualBasic.Constants", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Module Microsoft.VisualBasic.Constants End Module [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute > Sub Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute..ctor() End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub, options:=TestOptions.DebugExe.WithEmbedVbCoreRuntime(True).WithMetadataImportOptions(MetadataImportOptions.Internal)) End Sub <Fact()> Public Sub VbCore_SingleSymbol_Constants_All() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports Microsoft.VisualBasic Class Program Shared Sub Main(args As String()) Dim s = String.Format("|{0}|{1}|{2}|{3}|{4}|{5}|{6}|{7}|{8}|{9}|", vbCrLf, vbNewLine, vbCr, vbLf, vbBack, vbFormFeed, vbTab, vbVerticalTab, vbNullChar, vbNullString) s = s.Replace(vbCr, "vbCr") s = s.Replace(vbLf, "vbLf") s = s.Replace(vbBack, "vbBack") s = s.Replace(vbFormFeed, "vbFormFeed") s = s.Replace(vbTab, "vbTab") s = s.Replace(vbVerticalTab, "vbVerticalTab") s = s.Replace(vbNullChar, "vbNullChar") Console.Write(s) End Sub End Class </file> </compilation>, expectedOutput:="|vbCrvbLf|vbCrvbLf|vbCr|vbLf|vbBack|vbFormFeed|vbTab|vbVerticalTab|vbNullChar||", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_SingleSymbol_CompilerServices_EmbeddedOperators() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports Microsoft.VisualBasic Class Program Shared Sub Main(args As String()) Console.Write(GetType(CompilerServices.EmbeddedOperators).ToString()) End Sub End Class </file> </compilation>, expectedOutput:="Microsoft.VisualBasic.CompilerServices.EmbeddedOperators", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.EmbeddedOperators End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_SingleSymbol_CompilerServices_EmbeddedOperators_CompareString() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports Microsoft.VisualBasic Class Program Shared Sub Main(args As String()) Console.Write(CompilerServices.EmbeddedOperators.CompareString("a", "A", True)) End Sub End Class </file> </compilation>, expectedOutput:="0", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.Conversions > Function Microsoft.VisualBasic.CompilerServices.Conversions.GetCultureInfo() As System.Globalization.CultureInfo End Class [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.EmbeddedOperators > Function Microsoft.VisualBasic.CompilerServices.EmbeddedOperators.CompareString(Left As System.String, Right As System.String, TextCompare As System.Boolean) As System.Int32 End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_SingleSymbol_CompilerServices_EmbeddedOperators_CompareString2() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports Microsoft.VisualBasic Class Program Shared Sub Main(args As String()) Dim x As String = "Goo" Console.WriteLine(If(x = "Goo", "y", x)) End Sub End Class </file> </compilation>, expectedOutput:="y", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.Conversions > Function Microsoft.VisualBasic.CompilerServices.Conversions.GetCultureInfo() As System.Globalization.CultureInfo End Class [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.EmbeddedOperators > Function Microsoft.VisualBasic.CompilerServices.EmbeddedOperators.CompareString(Left As System.String, Right As System.String, TextCompare As System.Boolean) As System.Int32 End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_SingleSymbol_CompilerServices_Conversions() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports Microsoft.VisualBasic Class Program Shared Sub Main(args As String()) Console.Write(GetType(CompilerServices.Conversions).ToString()) End Sub End Class </file> </compilation>, expectedOutput:="Microsoft.VisualBasic.CompilerServices.Conversions", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.Conversions End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_SingleSymbol_CompilerServices_Conversions_ToBoolean_String() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports Microsoft.VisualBasic Class Program Shared Sub Main(args As String()) Console.Write(CompilerServices.Conversions.ToBoolean("True").ToString()) End Sub End Class </file> </compilation>, expectedOutput:="True", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.Conversions > Function Microsoft.VisualBasic.CompilerServices.Conversions.GetCultureInfo() As System.Globalization.CultureInfo > Function Microsoft.VisualBasic.CompilerServices.Conversions.IsHexOrOctValue(Value As System.String, ByRef i64Value As System.Int64) As System.Boolean > Function Microsoft.VisualBasic.CompilerServices.Conversions.ToBoolean(Value As System.String) As System.Boolean > Function Microsoft.VisualBasic.CompilerServices.Conversions.ToHalfwidthNumbers(s As System.String, culture As System.Globalization.CultureInfo) As System.String End Class [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.ProjectData > Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError() > Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(ex As System.Exception) End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_SingleSymbol_CompilerServices_Conversions_ToBoolean_Object() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports Microsoft.VisualBasic Class Program Shared Sub Main(args As String()) Console.Write(CompilerServices.Conversions.ToBoolean(directcast("True".ToString(), Object)).ToString()) End Sub End Class </file> </compilation>, expectedOutput:="True", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.Conversions > Function Microsoft.VisualBasic.CompilerServices.Conversions.GetCultureInfo() As System.Globalization.CultureInfo > Function Microsoft.VisualBasic.CompilerServices.Conversions.IsHexOrOctValue(Value As System.String, ByRef i64Value As System.Int64) As System.Boolean > Function Microsoft.VisualBasic.CompilerServices.Conversions.ToBoolean(Value As System.Object) As System.Boolean > Function Microsoft.VisualBasic.CompilerServices.Conversions.ToBoolean(Value As System.String) As System.Boolean > Function Microsoft.VisualBasic.CompilerServices.Conversions.ToHalfwidthNumbers(s As System.String, culture As System.Globalization.CultureInfo) As System.String End Class [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.ProjectData > Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError() > Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(ex As System.Exception) End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_SingleSymbol_CompilerServices_Conversions_ToSByte_String() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports Microsoft.VisualBasic Class Program Shared Sub Main(args As String()) Console.Write(CompilerServices.Conversions.ToSByte("77").ToString()) End Sub End Class </file> </compilation>, expectedOutput:="77", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.Conversions > Function Microsoft.VisualBasic.CompilerServices.Conversions.GetCultureInfo() As System.Globalization.CultureInfo > Function Microsoft.VisualBasic.CompilerServices.Conversions.IsHexOrOctValue(Value As System.String, ByRef i64Value As System.Int64) As System.Boolean > Function Microsoft.VisualBasic.CompilerServices.Conversions.ToHalfwidthNumbers(s As System.String, culture As System.Globalization.CultureInfo) As System.String [System.CLSCompliantAttribute] > Function Microsoft.VisualBasic.CompilerServices.Conversions.ToSByte(Value As System.String) As System.SByte End Class [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.ProjectData > Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError() > Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(ex As System.Exception) End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_SingleSymbol_CompilerServices_Conversions_ToSByte_Object() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports Microsoft.VisualBasic Class Program Shared Sub Main(args As String()) Console.Write(CompilerServices.Conversions.ToSByte(directcast("77", Object)).ToString()) End Sub End Class </file> </compilation>, expectedOutput:="77", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.Conversions > Function Microsoft.VisualBasic.CompilerServices.Conversions.GetCultureInfo() As System.Globalization.CultureInfo > Function Microsoft.VisualBasic.CompilerServices.Conversions.IsHexOrOctValue(Value As System.String, ByRef i64Value As System.Int64) As System.Boolean > Function Microsoft.VisualBasic.CompilerServices.Conversions.ToHalfwidthNumbers(s As System.String, culture As System.Globalization.CultureInfo) As System.String [System.CLSCompliantAttribute] > Function Microsoft.VisualBasic.CompilerServices.Conversions.ToSByte(Value As System.Object) As System.SByte [System.CLSCompliantAttribute] > Function Microsoft.VisualBasic.CompilerServices.Conversions.ToSByte(Value As System.String) As System.SByte End Class [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.ProjectData > Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError() > Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(ex As System.Exception) End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_SingleSymbol_CompilerServices_Utils_CopyArray() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports Microsoft.VisualBasic Class Program Shared Sub Main(args As String()) Dim a(10) As String Redim Preserve a(12) Console.Write(a.Length.ToString) End Sub End Class </file> </compilation>, expectedOutput:="13", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.Utils > Function Microsoft.VisualBasic.CompilerServices.Utils.CopyArray(arySrc As System.Array, aryDest As System.Array) As System.Array End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_SingleSymbol_CompilerServices_ObjectFlowControl() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports Microsoft.VisualBasic Class Program Shared Sub Main(args As String()) Console.Write(GetType(CompilerServices.ObjectFlowControl).ToString()) End Sub End Class </file> </compilation>, expectedOutput:="Microsoft.VisualBasic.CompilerServices.ObjectFlowControl", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.ObjectFlowControl > Sub Microsoft.VisualBasic.CompilerServices.ObjectFlowControl..ctor() End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_SingleSymbol_CompilerServices_ObjectFlowControl_ForLoopControl() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports Microsoft.VisualBasic Class Program Shared Sub Main(args As String()) Console.Write(GetType(CompilerServices.ObjectFlowControl.ForLoopControl).ToString()) End Sub End Class </file> </compilation>, expectedOutput:="Microsoft.VisualBasic.CompilerServices.ObjectFlowControl+ForLoopControl", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.ObjectFlowControl > Sub Microsoft.VisualBasic.CompilerServices.ObjectFlowControl..ctor() Class Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl > Sub Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl..ctor() End Class End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_SingleSymbol_CompilerServices_ObjectFlowControl_ForLoopControl_ForNextCheckR8() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports Microsoft.VisualBasic Class Program Shared Sub Main(args As String()) Console.Write(CompilerServices.ObjectFlowControl.ForLoopControl.ForNextCheckR8(CDbl(100), 1, 1)) End Sub End Class </file> </compilation>, expectedOutput:="False", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.ObjectFlowControl > Sub Microsoft.VisualBasic.CompilerServices.ObjectFlowControl..ctor() Class Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl > Function Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl.ForNextCheckR8(count As System.Double, limit As System.Double, StepValue As System.Double) As System.Boolean > Sub Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl..ctor() End Class End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_SingleSymbol_CompilerServices_StaticLocalInitFlag() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports Microsoft.VisualBasic Class Program Shared Sub Main(args As String()) Console.Write(GetType(CompilerServices.StaticLocalInitFlag).ToString()) End Sub End Class </file> </compilation>, expectedOutput:="Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag > Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag.State As System.Int16 > Sub Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag..ctor() End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_SingleSymbol_CompilerServices_StaticLocalInitFlag_State() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports Microsoft.VisualBasic Class Program Shared Sub Main(args As String()) Dim v As New CompilerServices.StaticLocalInitFlag v.State = 1 Console.Write(v.State.ToString()) End Sub End Class </file> </compilation>, expectedOutput:="1", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag > Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag.State As System.Int16 > Sub Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag..ctor() End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_SingleSymbol_CompilerServices_IncompleteInitialization() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports Microsoft.VisualBasic Class Program Shared Sub Main(args As String()) Console.Write(GetType(CompilerServices.IncompleteInitialization).ToString()) End Sub End Class </file> </compilation>, expectedOutput:="Microsoft.VisualBasic.CompilerServices.IncompleteInitialization", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.IncompleteInitialization > Sub Microsoft.VisualBasic.CompilerServices.IncompleteInitialization..ctor() End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_SingleSymbol_CompilerServices_IncompleteInitialization_Throw() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports Microsoft.VisualBasic Class Program Shared Sub Main(args As String()) Try Throw New CompilerServices.IncompleteInitialization() Catch ex As Exception Console.Write(ex.GetType().ToString()) End Try End Sub End Class </file> </compilation>, expectedOutput:="Microsoft.VisualBasic.CompilerServices.IncompleteInitialization", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.IncompleteInitialization > Sub Microsoft.VisualBasic.CompilerServices.IncompleteInitialization..ctor() End Class [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.ProjectData > Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError() > Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(ex As System.Exception) End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_SingleSymbol_CompilerServices_StandardModuleAttribute() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports Microsoft.VisualBasic Imports Microsoft.VisualBasic.CompilerServices &lt;StandardModuleAttribute()&gt; Class Program Shared Sub Main(args As String()) Console.Write("") End Sub End Class </file> </compilation>, expectedOutput:="", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Module Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Module Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute > Sub Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute..ctor() End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_SingleSymbol_CompilerServices_DesignerGeneratedAttribute() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports Microsoft.VisualBasic Imports Microsoft.VisualBasic.CompilerServices &lt;DesignerGeneratedAttribute()&gt; Class Program Shared Sub Main(args As String()) Console.Write("") End Sub End Class </file> </compilation>, expectedOutput:="", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global [Microsoft.VisualBasic.CompilerServices.DesignerGeneratedAttribute] Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.CompilerServices.DesignerGeneratedAttribute > Sub Microsoft.VisualBasic.CompilerServices.DesignerGeneratedAttribute..ctor() End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_SingleSymbol_CompilerServices_OptionCompareAttribute() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports Microsoft.VisualBasic Imports Microsoft.VisualBasic.CompilerServices Class Program Shared Sub Main(&lt;OptionCompareAttribute()&gt;args As String()) Console.Write("") End Sub End Class </file> </compilation>, expectedOutput:="", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.CompilerServices.OptionCompareAttribute > Sub Microsoft.VisualBasic.CompilerServices.OptionCompareAttribute..ctor() End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_SingleSymbol_CompilerServices_OptionTextAttribute() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports Microsoft.VisualBasic Imports Microsoft.VisualBasic.CompilerServices &lt;OptionTextAttribute()&gt; Class Program Shared Sub Main(args As String()) Console.Write("") End Sub End Class </file> </compilation>, expectedOutput:="", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global [Microsoft.VisualBasic.CompilerServices.OptionTextAttribute] Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.CompilerServices.OptionTextAttribute > Sub Microsoft.VisualBasic.CompilerServices.OptionTextAttribute..ctor() End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_SingleSymbol_HideModuleNameAttribute() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports Microsoft.VisualBasic Imports Microsoft.VisualBasic.CompilerServices &lt;HideModuleNameAttribute()&gt; Class Program Shared Sub Main(args As String()) Console.Write("") End Sub End Class </file> </compilation>, expectedOutput:="", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global [Microsoft.VisualBasic.HideModuleNameAttribute] Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.HideModuleNameAttribute > Sub Microsoft.VisualBasic.HideModuleNameAttribute..ctor() End Class End Namespace End Namespace End Namespace </expected>.Value) End Sub) End Sub <Fact()> <WorkItem(544511, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544511")> Public Sub VbCore_SingleSymbol_Strings_AscW_Char() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports Microsoft.VisualBasic Class Program Shared Sub Main(args As String()) Dim ch As Char = "A"c Console.Write(AscW(ch)) End Sub End Class </file> </compilation>, expectedOutput:="65", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_SingleSymbol_Strings_ChrW_Char() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports Microsoft.VisualBasic Class Program Shared Sub Main(args As String()) Dim ch As Integer = 65 Console.Write(ChrW(ch)) End Sub End Class </file> </compilation>, expectedOutput:="A", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Module Microsoft.VisualBasic.Strings > Function Microsoft.VisualBasic.Strings.ChrW(CharCode As System.Int32) As System.Char End Module Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute > Sub Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute..ctor() End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_SingleSymbol_Strings_ChrW_Char_MultipleEmits() Dim compilation = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports Microsoft.VisualBasic Class Program Shared Sub Main(args As String()) Dim ch As Integer = 65 Console.Write(ChrW(ch)) End Sub End Class </file> </compilation>, expectedOutput:="A", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Module Microsoft.VisualBasic.Strings > Function Microsoft.VisualBasic.Strings.ChrW(CharCode As System.Int32) As System.Char End Module Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute > Sub Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute..ctor() End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub).Compilation For i = 0 To 10 Using memory As New MemoryStream() compilation.Emit(memory) End Using Next End Sub <Fact()> Public Sub VbCore_TypesReferencedFromAttributes() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports Microsoft.VisualBasic Imports Microsoft.VisualBasic.CompilerServices &lt;AttributeUsage(AttributeTargets.All)&gt; Class Attr Inherits Attribute Public Sub New(_type As Type) End Sub Public Type As Type End Class &lt;Attr(GetType(Strings), Type:=GetType(Microsoft.VisualBasic.CompilerServices.Conversions))&gt; Module Program Sub Main(args As String()) End Sub End Module </file> </compilation>, expectedOutput:="", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global [System.AttributeUsageAttribute] Class Attr > Attr.Type As System.Type > Sub Attr..ctor(_type As System.Type) End Class [Attr] Module Program [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Module Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Module Microsoft.VisualBasic.Strings End Module Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.Conversions End Class [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute > Sub Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute..ctor() End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_TypesReferencedFromAttributes_Array() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports Microsoft.VisualBasic Imports Microsoft.VisualBasic.CompilerServices &lt;AttributeUsage(AttributeTargets.All)&gt; Class Attr Inherits Attribute Public Types() As Type End Class &lt;Attr(Types:= New Type() {GetType(Conversions), GetType(Strings)})&gt; Module Program Sub Main(args As String()) End Sub End Module </file> </compilation>, expectedOutput:="", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global [System.AttributeUsageAttribute] Class Attr > Attr.Types As System.Type() > Sub Attr..ctor() End Class [Attr] Module Program [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Module Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Module Microsoft.VisualBasic.Strings End Module Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.Conversions End Class [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute > Sub Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute..ctor() End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_EnsurePrivateConstructorsEmitted() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Reflection Imports Microsoft.VisualBasic Module Program Sub Main(args As String()) PrintConstructorInfo(GetType(CompilerServices.EmbeddedOperators)) PrintConstructorInfo(GetType(CompilerServices.Conversions)) PrintConstructorInfo(GetType(CompilerServices.ProjectData)) PrintConstructorInfo(GetType(CompilerServices.Utils)) End Sub Sub PrintConstructorInfo(type As Type) Dim constructor = type.GetConstructors(BindingFlags.Instance Or BindingFlags.NonPublic) Console.Write(type.ToString()) Console.Write(" ") Console.WriteLine(constructor(0).ToString()) End Sub End Module </file> </compilation>, expectedOutput:= <output> Microsoft.VisualBasic.CompilerServices.EmbeddedOperators Void .ctor() Microsoft.VisualBasic.CompilerServices.Conversions Void .ctor() Microsoft.VisualBasic.CompilerServices.ProjectData Void .ctor() Microsoft.VisualBasic.CompilerServices.Utils Void .ctor() </output>.Value.Replace(vbLf, Environment.NewLine), sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Module Program [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) > Sub Program.PrintConstructorInfo(type As System.Type) End Module Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.Conversions End Class [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.EmbeddedOperators End Class [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.ProjectData End Class [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute > Sub Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute..ctor() End Class [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.ComponentModel.EditorBrowsableAttribute] Class Microsoft.VisualBasic.CompilerServices.Utils End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_EmbeddedAttributeOnAssembly_NoReferences() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports Microsoft.VisualBasic Class Program Shared Sub Main(args As String()) For Each attr In GetType(Program).Assembly.GetCustomAttributes(True).ToArray() Dim name = attr.ToString() If name.IndexOf("Embedded") >= 0 Then Console.WriteLine(attr.GetType().ToString()) End If dim x = vbNewLine Next End Sub End Class </file> </compilation>, expectedOutput:="", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class End Namespace </expected>.Value) End Sub) End Sub <Fact()> Public Sub VbCore_EmbeddedAttributeOnAssembly_References_NoDebug() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports Microsoft.VisualBasic Class Program Shared Sub Main(args As String()) For Each attr In GetType(Program).Assembly.GetCustomAttributes(True).ToArray() Dim name = attr.ToString() If name.IndexOf("Embedded") >= 0 Then Console.WriteLine(attr.GetType().ToString()) End If dim x = GetType(Strings) Next End Sub End Class </file> </compilation>, expectedOutput:="Microsoft.VisualBasic.Embedded", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class Namespace Microsoft Namespace Microsoft.VisualBasic [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.Embedded > Sub Microsoft.VisualBasic.Embedded..ctor() End Class [Microsoft.VisualBasic.Embedded] [System.Diagnostics.DebuggerNonUserCodeAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Module Microsoft.VisualBasic.Strings End Module Namespace Microsoft.VisualBasic.CompilerServices [Microsoft.VisualBasic.Embedded] [System.AttributeUsageAttribute] [System.ComponentModel.EditorBrowsableAttribute] [System.Runtime.CompilerServices.CompilerGeneratedAttribute] Class Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute > Sub Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute..ctor() End Class End Namespace End Namespace End Namespace End Namespace </expected>.Value) End Sub) End Sub <ConditionalFact(GetType(NoUsedAssembliesValidation))> ' https://github.com/dotnet/roslyn/issues/40683: The test hook is blocked by this issue. <WorkItem(40683, "https://github.com/dotnet/roslyn/issues/40683")> Public Sub VbCore_InvisibleViaInternalsVisibleTo() Dim other As VisualBasicCompilation = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation name="HasIVTToCompilationVbCore"> <file name="a.vb"><![CDATA[ Imports System Imports Microsoft.VisualBasic Imports Microsoft.VisualBasic.CompilerServices <Assembly: System.Runtime.CompilerServices.InternalsVisibleTo("WantsIVTAccessVbCoreAndStillCannot")> Friend Class SourceLibrary Shared Sub Main(args As String()) Console.Write(ChrW(123)) ' Forces Microsoft.VisualBasic.Strings to be embedded into the assembly End Sub Public Shared U As Utils End Class ]]> </file> </compilation>, references:=NoVbRuntimeReferences, options:=TestOptions.ReleaseDll.WithEmbedVbCoreRuntime(True)) CompilationUtils.AssertNoErrors(other) Dim c As VisualBasicCompilation = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation name="WantsIVTAccessVbCoreButCantHave"> <file name="a.vb"><![CDATA[ Public Class A Friend Class B Protected Sub New() Dim a = GetType(Microsoft.VisualBasic.Strings) End Sub End Class End Class ]]> </file> </compilation>, references:=NoVbRuntimeReferences.Concat({New VisualBasicCompilationReference(other)}), options:=TestOptions.ReleaseDll) 'compilation should not succeed, and internals should not be imported. c.GetDiagnostics() CompilationUtils.AssertTheseDiagnostics(c, <error> BC30002: Type 'Microsoft.VisualBasic.Strings' is not defined. Dim a = GetType(Microsoft.VisualBasic.Strings) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </error>) Dim c2 As VisualBasicCompilation = CompilationUtils.CreateCompilationWithMscorlib40AndReferences( <compilation name="WantsIVTAccessVbCoreAndStillCannot"> <file name="a.vb"><![CDATA[ Public Class A Friend Class B Protected Sub New() Dim a = GetType(Microsoft.VisualBasic.Strings) End Sub End Class End Class ]]> </file> </compilation>, references:=NoVbRuntimeReferences.Concat({New VisualBasicCompilationReference(other)}), options:=TestOptions.ReleaseDll) CompilationUtils.AssertTheseDiagnostics(c2, <error> BC30002: Type 'Microsoft.VisualBasic.Strings' is not defined. Dim a = GetType(Microsoft.VisualBasic.Strings) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </error>) End Sub <Fact> Public Sub VbCore_InvisibleViaInternalsVisibleTo2() Dim other As VisualBasicCompilation = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation name="VbCore_InvisibleViaInternalsVisibleTo2"> <file name="a.vb"><![CDATA[ Imports System Imports Microsoft.VisualBasic Imports Microsoft.VisualBasic.CompilerServices <Assembly: System.Runtime.CompilerServices.InternalsVisibleTo("WantsIVTAccessVbCoreAndStillCannot2")> Friend Class SourceLibrary Shared Sub Main(args As String()) Dim a() As String Redim Preserve a(2) End Sub Public Shared U As Utils End Class ]]> </file> </compilation>, references:=NoVbRuntimeReferences, options:=TestOptions.ReleaseDll.WithEmbedVbCoreRuntime(True)) CompilationUtils.AssertNoErrors(other) Dim c As VisualBasicCompilation = CompilationUtils.CreateCompilationWithMscorlib40AndReferences( <compilation name="WantsIVTAccessVbCoreAndStillCannot2"> <file name="a.vb"><![CDATA[ Imports System Imports Microsoft.VisualBasic Imports Microsoft.VisualBasic.CompilerServices Class Program Shared Sub Main(args As String()) SourceLibrary.U.CopyArray(Nothing, Nothing) End Sub End Class ]]> </file> </compilation>, references:=NoVbRuntimeReferences.Concat({New VisualBasicCompilationReference(other)}), options:=TestOptions.ReleaseDll) CompilationUtils.AssertTheseDiagnostics(c, <error> BC30456: 'CopyArray' is not a member of 'Utils'. SourceLibrary.U.CopyArray(Nothing, Nothing) ~~~~~~~~~~~~~~~~~~~~~~~~~ </error>) End Sub <Fact> Public Sub VbCore_InvisibleViaInternalsVisibleTo3() Dim other As VisualBasicCompilation = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation name="VbCore_InvisibleViaInternalsVisibleTo3"> <file name="a.vb"><![CDATA[ Imports System Imports Microsoft.VisualBasic <Assembly: System.Runtime.CompilerServices.InternalsVisibleTo("WantsIVTAccessVbCoreAndStillCannot3")> Friend Class SourceLibrary Shared Sub Main(args As String()) Console.Write(ChrW(args.Length)) End Sub End Class ]]> </file> </compilation>, references:=NoVbRuntimeReferences, options:=TestOptions.ReleaseDll.WithEmbedVbCoreRuntime(True)) CompilationUtils.AssertNoErrors(other) Dim c As VisualBasicCompilation = CompilationUtils.CreateCompilationWithMscorlib40AndReferences( <compilation name="WantsIVTAccessVbCoreAndStillCannot3"> <file name="a.vb"><![CDATA[ Imports System Imports Microsoft.VisualBasic Imports Microsoft.VisualBasic.CompilerServices Class Program Shared Sub Main(args As String()) Console.Write(ChrW(123)) End Sub End Class ]]> </file> </compilation>, references:=NoVbRuntimeReferences.Concat({New VisualBasicCompilationReference(other)}), options:=TestOptions.ReleaseDll) CompilationUtils.AssertTheseDiagnostics(c, <error> BC30451: 'ChrW' is not declared. It may be inaccessible due to its protection level. Console.Write(ChrW(123)) ~~~~ </error>) End Sub <Fact> Public Sub VbCore_InvisibleViaInternalsVisibleTo3_ViaBinary() Dim other As VisualBasicCompilation = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation name="VbCore_InvisibleViaInternalsVisibleTo3"> <file name="a.vb"><![CDATA[ Imports System Imports Microsoft.VisualBasic <Assembly: System.Runtime.CompilerServices.InternalsVisibleTo("WantsIVTAccessVbCoreAndStillCannot3")> Friend Class SourceLibrary Shared Sub Main(args As String()) Console.Write(ChrW(args.Length)) End Sub End Class ]]> </file> </compilation>, references:=NoVbRuntimeReferences, options:=TestOptions.ReleaseDll.WithEmbedVbCoreRuntime(True)) CompilationUtils.AssertNoErrors(other) Dim memory As New MemoryStream() other.Emit(memory) Dim c As VisualBasicCompilation = CompilationUtils.CreateCompilationWithMscorlib40AndReferences( (<compilation name="WantsIVTAccessVbCoreAndStillCannot3"> <file name="a.vb"><![CDATA[ Imports System Imports Microsoft.VisualBasic Class Program Shared Sub Main(args As String()) Console.Write(ChrW(123)) End Sub End Class ]]> </file> </compilation>), references:=NoVbRuntimeReferences.Concat({MetadataReference.CreateFromImage(memory.ToImmutable())}), options:=TestOptions.ReleaseDll) CompilationUtils.AssertTheseDiagnostics(c, <error> BC30451: 'ChrW' is not declared. It may be inaccessible due to its protection level. Console.Write(ChrW(123)) ~~~~ </error>) End Sub <Fact> Public Sub VbCore_EmbeddedVbCoreWithIVToAndRuntime() Dim other As VisualBasicCompilation = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation name="VbCore_EmbeddedVbCoreWithIVToAndRuntime"> <file name="a.vb"><![CDATA[ <Assembly: System.Runtime.CompilerServices.InternalsVisibleTo("WantsIVTAccessVbCoreAndStillCannot3")> ]]> </file> </compilation>, references:=NoVbRuntimeReferences, options:=TestOptions.ReleaseDll.WithEmbedVbCoreRuntime(True)) CompilationUtils.AssertNoErrors(other) MyBase.CompileAndVerify(source:= <compilation> <file name="a.vb"> Imports System Imports Microsoft.VisualBasic Imports Microsoft.VisualBasic.CompilerServices Class Program Shared Sub Main(args As String()) Try Dim s As String = "123" Dim i As Integer = s ' This should use Conversions.ToInteger(String) Catch e As Exception ' This should use ProjectData.SetProjectError()/ClearProjectError() End Try End Sub End Class </file> </compilation>, allReferences:=NoVbRuntimeReferences.Concat(MsvbRef).Concat(New VisualBasicCompilationReference(other)), expectedOutput:="", sourceSymbolValidator:=Sub([module]) ValidateSourceSymbols([module]), symbolValidator:=Sub([module]) ValidateSymbols([module], <expected> Namespace Global Class Program > Sub Program..ctor() [System.STAThreadAttribute] > Sub Program.Main(args As System.String()) End Class End Namespace </expected>.Value) End Sub, options:=TestOptions.ReleaseExe.WithMetadataImportOptions(MetadataImportOptions.Internal)) End Sub <Fact()> Public Sub VbCore_CompilationOptions() Dim withoutVbCore As VisualBasicCompilation = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation name="VbCore_CompilationOptions1"> <file name="a.vb"><![CDATA[ Imports System Imports Microsoft.VisualBasic Friend Class SourceLibrary Shared Sub Main(args As String()) Console.Write(ChrW(123)) End Sub End Class ]]> </file> </compilation>, references:=NoVbRuntimeReferences, options:=TestOptions.ReleaseDll.WithEmbedVbCoreRuntime(False)) CompilationUtils.AssertTheseDiagnostics(withoutVbCore, <error> BC30451: 'ChrW' is not declared. It may be inaccessible due to its protection level. Console.Write(ChrW(123)) ~~~~ </error>) Dim withVbCore As VisualBasicCompilation = withoutVbCore.WithOptions(withoutVbCore.Options.WithEmbedVbCoreRuntime(True)) CompilationUtils.AssertNoErrors(withVbCore) Dim withoutVbCore2 As VisualBasicCompilation = withVbCore.WithOptions(withVbCore.Options.WithEmbedVbCoreRuntime(False)) CompilationUtils.AssertTheseDiagnostics(withoutVbCore2, <error> BC30451: 'ChrW' is not declared. It may be inaccessible due to its protection level. Console.Write(ChrW(123)) ~~~~ </error>) Dim withVbCore2 As VisualBasicCompilation = withoutVbCore.WithOptions(withoutVbCore2.Options.WithEmbedVbCoreRuntime(True)) CompilationUtils.AssertNoErrors(withVbCore2) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub NoDebugInfoForVbCoreSymbols() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports Microsoft.VisualBasic Class Program Shared Sub Main(args As String()) Dim ch As Integer = 65 Console.Write(ChrW(ch)) End Sub End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugExe.WithEmbedVbCoreRuntime(True)) compilation.VerifyPdb( <symbols> <files> <file id="1" name="a.vb" language="VB" checksumAlgorithm="SHA1" checksum="43-DF-02-C2-F5-5F-6A-CB-08-D3-1F-D2-8E-4F-FE-0A-8F-C2-76-D7"/> </files> <entryPoint declaringType="Program" methodName="Main" parameterNames="args"/> <methods> <method containingType="Program" name="Main" parameterNames="args"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="5" startColumn="5" endLine="5" endColumn="38" document="1"/> <entry offset="0x1" startLine="6" startColumn="13" endLine="6" endColumn="31" document="1"/> <entry offset="0x4" startLine="7" startColumn="9" endLine="7" endColumn="32" document="1"/> <entry offset="0x10" startLine="8" startColumn="5" endLine="8" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x11"> <namespace name="System" importlevel="file"/> <namespace name="Microsoft.VisualBasic" importlevel="file"/> <currentnamespace name=""/> <local name="ch" il_index="0" il_start="0x0" il_end="0x11" attributes="0"/> </scope> </method> </methods> </symbols>) End Sub <Fact> Public Sub VbCoreTypeAndUserPartialTypeConflict() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndReferences( <compilation> <file name="a.vb"> Imports System Imports Microsoft.VisualBasic Namespace Global.Microsoft.VisualBasic Partial Friend Class HideModuleNameAttribute Public Property A As String End Class End Namespace </file> </compilation>, references:={SystemRef, SystemCoreRef}, options:=TestOptions.ReleaseDll.WithEmbedVbCoreRuntime(True)) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC31210: class 'HideModuleNameAttribute' conflicts with a Visual Basic Runtime class 'HideModuleNameAttribute'. Partial Friend Class HideModuleNameAttribute ~~~~~~~~~~~~~~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub VbCoreTypeAndUserTypeConflict() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndReferences( <compilation> <file name="a.vb"> Imports System Imports Microsoft.VisualBasic Namespace Global.Microsoft.VisualBasic Friend Class HideModuleNameAttribute Public Property A As String End Class End Namespace </file> </compilation>, references:={SystemRef, SystemCoreRef}, options:=TestOptions.ReleaseDll.WithEmbedVbCoreRuntime(True)) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC31210: class 'HideModuleNameAttribute' conflicts with a Visual Basic Runtime class 'HideModuleNameAttribute'. Friend Class HideModuleNameAttribute ~~~~~~~~~~~~~~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub VbCoreNamespaceAndUserTypeConflict() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndReferences( <compilation> <file name="a.vb"> Imports System Imports Microsoft.VisualBasic Namespace Global.Microsoft Friend Class VisualBasic Public Property A As String End Class End Namespace </file> </compilation>, references:={SystemRef, SystemCoreRef}, options:=TestOptions.ReleaseDll.WithEmbedVbCoreRuntime(True)) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC31210: class 'VisualBasic' conflicts with a Visual Basic Runtime namespace 'VisualBasic'. Friend Class VisualBasic ~~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub VbCoreTypeAndUserNamespaceConflict() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndReferences( <compilation> <file name="a.vb"> Imports System Imports Microsoft.VisualBasic Namespace Global.Microsoft.VisualBasic.Strings Partial Friend Class VisualBasic Public Property A As String End Class End Namespace </file> </compilation>, references:={SystemRef, SystemCoreRef}, options:=TestOptions.ReleaseDll.WithEmbedVbCoreRuntime(True)) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC31210: namespace 'Strings' conflicts with a Visual Basic Runtime module 'Strings'. Namespace Global.Microsoft.VisualBasic.Strings ~~~~~~~ </errors>) End Sub <Fact> Public Sub VbCoreTypeAndUserNamespaceConflict2() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndReferences( <compilation> <file name="a.vb"> Imports System Imports Microsoft.VisualBasic Module Module1 Sub Main() Call Console.WriteLine(GetType(Strings).ToString()) End Sub End Module Namespace Global.Microsoft.VisualBasic.Strings Partial Friend Class VisualBasic Public Property A As String End Class End Namespace </file> </compilation>, references:={SystemRef, SystemCoreRef}, options:=TestOptions.ReleaseDll.WithEmbedVbCoreRuntime(True)) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC30560: 'Strings' is ambiguous in the namespace 'Microsoft.VisualBasic'. Call Console.WriteLine(GetType(Strings).ToString()) ~~~~~~~ BC31210: namespace 'Strings' conflicts with a Visual Basic Runtime module 'Strings'. Namespace Global.Microsoft.VisualBasic.Strings ~~~~~~~ </errors>) End Sub <Fact> Public Sub VbCoreTypeAndUserNamespaceConflict3() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndReferences( <compilation> <file name="a.vb"> Imports System Imports Microsoft.VisualBasic Module Module1 Sub Main() End Sub End Module Namespace Global.Microsoft.VisualBasic.Strings Partial Friend Class VisualBasic Public Property A As String End Class End Namespace </file> <file name="b.vb"> Imports System Namespace Global.Microsoft Namespace VisualBasic Namespace Strings Partial Friend Class Other End Class End Namespace End Namespace End Namespace </file> </compilation>, references:={SystemRef, SystemCoreRef}, options:=TestOptions.ReleaseDll.WithEmbedVbCoreRuntime(True)) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC31210: namespace 'Strings' conflicts with a Visual Basic Runtime module 'Strings'. Namespace Global.Microsoft.VisualBasic.Strings ~~~~~~~ </errors>) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:="https://github.com/dotnet/roslyn/issues/29531")> Public Sub VbRuntimeTypeAndUserNamespaceConflictOutsideOfVBCore() ' This verifies the diagnostic BC31210 scenario outsides of using VB Core which ' is triggered by the Embedded Attribute. This occurs on the command line compilers ' when the reference to system.xml.linq is added Dim compilationOptions = TestOptions.ReleaseExe.WithGlobalImports(GlobalImport.Parse({"System", "Microsoft.VisualBasic"})) Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="testa.vb"> Imports Microsoft.VisualBasic Module Module1 Sub Main() Dim x1 = Microsoft.VisualBasic.InStr("abcd", 1) Dim x2 = &lt;test/&gt; End Sub End Module Namespace global.Microsoft Public Module VisualBasic End Module End Namespace </file> </compilation>, options:=compilationOptions, references:={SystemCoreRef, SystemXmlLinqRef, SystemXmlRef}) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors>BC30560: 'VisualBasic' is ambiguous in the namespace 'Microsoft'. BC30560: 'VisualBasic' is ambiguous in the namespace 'Microsoft'. BC30560: Error in project-level import 'Microsoft.VisualBasic' at 'Microsoft.VisualBasic' : 'VisualBasic' is ambiguous in the namespace 'Microsoft'. BC30560: 'VisualBasic' is ambiguous in the namespace 'Microsoft'. Imports Microsoft.VisualBasic ~~~~~~~~~~~~~~~~~~~~~ BC30560: 'VisualBasic' is ambiguous in the namespace 'Microsoft'. Dim x1 = Microsoft.VisualBasic.InStr("abcd", 1) ~~~~~~~~~~~~~~~~~~~~~ BC31210: module 'VisualBasic' conflicts with a Visual Basic Runtime namespace 'VisualBasic'. Public Module VisualBasic ~~~~~~~~~~~ </errors>) ' Remove the reference to System.XML.Linq and verify compilation behavior that the ' diagnostic is not produced. compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="testa.vb"> Imports Microsoft.VisualBasic Module Module1 Sub Main() Dim x1 = Microsoft.VisualBasic.InStr("abcd", 1) End Sub End Module Namespace global.Microsoft Public Module VisualBasic End Module End Namespace </file> </compilation>, options:=compilationOptions) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors>BC30456: 'InStr' is not a member of 'VisualBasic'. Dim x1 = Microsoft.VisualBasic.InStr("abcd", 1) ~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub VbCore_IsImplicitlyDeclaredSymbols() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndReferences( <compilation> <file name="a.vb"> </file> </compilation>, references:={SystemRef, SystemCoreRef}, options:=TestOptions.ReleaseDll.WithEmbedVbCoreRuntime(True)) CompilationUtils.AssertTheseDiagnostics(compilation, <errors></errors>) Dim vbCoreType = compilation.GetTypeByMetadataName("Microsoft.VisualBasic.Embedded") Assert.NotNull(vbCoreType) Dim namespacesToCheck As New Queue(Of NamespaceSymbol)() namespacesToCheck.Enqueue(vbCoreType.ContainingNamespace) While namespacesToCheck.Count > 0 Dim ns = namespacesToCheck.Dequeue() For Each member In ns.GetMembers() Select Case member.Kind Case SymbolKind.NamedType AssertTypeAndItsMembersAreImplicitlyDeclared(DirectCast(member, NamedTypeSymbol)) Case SymbolKind.Namespace namespacesToCheck.Enqueue(DirectCast(member, NamespaceSymbol)) End Select Next End While End Sub <Fact()> Public Sub InternalXmlHelper_IsImplicitlyDeclaredSymbols() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Module M Dim x = <x/>.<y>.Value End Module ]]></file> </compilation>, references:=XmlReferences) compilation.AssertNoErrors() Dim type = compilation.GetTypeByMetadataName("My.InternalXmlHelper") AssertTypeAndItsMembersAreImplicitlyDeclared(type) End Sub Private Sub IsImplicitlyDeclaredSymbols([namespace] As NamespaceSymbol) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact> Public Sub VbCoreWithStaticLocals_UsingEmbedVBCore() 'Static Locals use types contained within VB Runtime so verify with VBCore option to ensure the feature works 'using VBCore which would be the case with platforms such as Phone. Dim compilation As VisualBasicCompilation = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation> <file name="a.vb"> Imports System Imports Microsoft.VisualBasic Module Module1 Sub Main() Goo() Goo() End Sub Sub Goo() Static x as integer = 1 x+=1 End Sub End Module </file> </compilation>, references:=NoVbRuntimeReferences, options:=TestOptions.ReleaseDll.WithEmbedVbCoreRuntime(True)) CompilationUtils.AssertNoErrors(compilation) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact> Public Sub VbCoreWithStaticLocals_NoRequiredTypes() 'Static Locals use types in VB Runtime so verify with no VBRuntime we generate applicable errors about missing types. 'This will include types for Module as well as static locals Dim compilation As VisualBasicCompilation = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation> <file name="a.vb"> Module Module1 Sub Main() Goo() Goo() End Sub Sub Goo() Static x as integer = 1 x+=1 End Sub End Module </file> </compilation>, references:=NoVbRuntimeReferences, options:=TestOptions.ReleaseDll.WithEmbedVbCoreRuntime(False)) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_MissingRuntimeHelper, "Module1").WithArguments("Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute..ctor")) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact> Public Sub VbCoreWithStaticLocals_CorrectDefinedTypes() 'Static Locals use types in VB Runtime so verify with no VBRuntime but appropriate types specified in Source the static 'local scenarios should work correctly. Dim compilation As VisualBasicCompilation = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation> <file name="a.vb"> Imports System Imports Microsoft.VisualBasic Public Class Module1 Public shared Sub Main() Goo() Goo() End Sub shared Sub Goo() Static x as integer = 1 x+=1 End Sub End Class Namespace Global.Microsoft.VisualBasic.CompilerServices Friend Class StaticLocalInitFlag Public State As Short End Class Friend Class IncompleteInitialization Inherits System.Exception Public Sub New() MyBase.New() End Sub End Class End Namespace </file> </compilation>, references:=NoVbRuntimeReferences, options:=TestOptions.ReleaseDll.WithEmbedVbCoreRuntime(False)) compilation.AssertNoDiagnostics() End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact> Public Sub VbCoreWithStaticLocals_IncorrectDefinedTypes() 'Static Locals use types in VB Runtime so verify with no VBRuntime but appropriate types specified in Source the static 'local scenarios should work correctly but if we define the types incorrectly we should generate errors although we 'should not crash. Dim compilation As VisualBasicCompilation = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation> <file name="a.vb"> Public Class Module1 Public shared Sub Main() Goo() Goo() End Sub shared Sub Goo() Static x as integer = 1 x+=1 End Sub End Class Namespace Global.Microsoft.VisualBasic.CompilerServices Friend Class StaticLocalInitFlag Public State As Short End Class Friend Structure IncompleteInitialization Inherits System.Exception Public Sub New() MyBase.New() End Sub End Structure End Namespace </file> </compilation>, references:=NoVbRuntimeReferences, options:=TestOptions.ReleaseDll.WithEmbedVbCoreRuntime(False)) compilation.VerifyDiagnostics( Diagnostic(ERRID.ERR_NewInStruct, "New").WithLocation(20, 24), Diagnostic(ERRID.ERR_StructCantInherit, "Inherits System.Exception").WithLocation(19, 13), Diagnostic(ERRID.ERR_UseOfKeywordFromStructure1, "MyBase").WithArguments("MyBase").WithLocation(21, 17) ) End Sub Private Sub AssertTypeAndItsMembersAreImplicitlyDeclared(type As NamedTypeSymbol) Assert.True(type.IsImplicitlyDeclared) Assert.True(type.IsEmbedded) For Each member In type.GetMembers() Assert.True(member.IsEmbedded) Assert.True(member.IsImplicitlyDeclared) Select Case member.Kind Case SymbolKind.Field, SymbolKind.Property Case SymbolKind.Method For Each param In DirectCast(member, MethodSymbol).Parameters Assert.True(param.IsEmbedded) Assert.True(param.IsImplicitlyDeclared) Next For Each typeParam In DirectCast(member, MethodSymbol).TypeParameters Assert.True(typeParam.IsEmbedded) Assert.True(typeParam.IsImplicitlyDeclared) Next Case SymbolKind.NamedType AssertTypeAndItsMembersAreImplicitlyDeclared(DirectCast(member, NamedTypeSymbol)) Case Else Assert.False(True) ' Unexpected member. End Select Next End Sub <Fact, WorkItem(544291, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544291")> Public Sub VbCoreSyncLockOnObject() CompileAndVerify( <compilation> <file name="a.vb"> Module Module1 Private SyncObj As Object = New Object() Sub Main() SyncLock SyncObj End SyncLock End Sub End Module </file> </compilation>).VerifyIL("Module1.Main", <![CDATA[ { // Code size 29 (0x1d) .maxstack 2 .locals init (Object V_0, Boolean V_1) IL_0000: ldsfld "Module1.SyncObj As Object" IL_0005: stloc.0 IL_0006: ldc.i4.0 IL_0007: stloc.1 .try { IL_0008: ldloc.0 IL_0009: ldloca.s V_1 IL_000b: call "Sub System.Threading.Monitor.Enter(Object, ByRef Boolean)" IL_0010: leave.s IL_001c } finally { IL_0012: ldloc.1 IL_0013: brfalse.s IL_001b IL_0015: ldloc.0 IL_0016: call "Sub System.Threading.Monitor.Exit(Object)" IL_001b: endfinally } IL_001c: ret } ]]>) End Sub <Fact(), WorkItem(545772, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545772")> Public Sub VbCoreNoStdLib() Dim source = <compilation> <file name="a.vb"> Module Class1 Public Sub Main() End Sub End Module </file> </compilation> CreateCompilationWithMscorlib40( source, options:=TestOptions.ReleaseExe.WithEmbedVbCoreRuntime(True)). VerifyDiagnostics( Diagnostic(ERRID.ERR_UndefinedType1).WithArguments("Global.System.ComponentModel.EditorBrowsable"), Diagnostic(ERRID.ERR_NameNotMember2).WithArguments("ComponentModel", "System"), Diagnostic(ERRID.ERR_UndefinedType1).WithArguments("Global.System.ComponentModel.EditorBrowsable"), Diagnostic(ERRID.ERR_NameNotMember2).WithArguments("ComponentModel", "System"), Diagnostic(ERRID.ERR_UndefinedType1).WithArguments("Global.System.ComponentModel.EditorBrowsable"), Diagnostic(ERRID.ERR_NameNotMember2).WithArguments("ComponentModel", "System"), Diagnostic(ERRID.ERR_UndefinedType1).WithArguments("Global.System.ComponentModel.EditorBrowsable"), Diagnostic(ERRID.ERR_NameNotMember2).WithArguments("ComponentModel", "System"), Diagnostic(ERRID.ERR_UndefinedType1).WithArguments("Global.System.ComponentModel.EditorBrowsable"), Diagnostic(ERRID.ERR_NameNotMember2).WithArguments("ComponentModel", "System"), Diagnostic(ERRID.ERR_UndefinedType1).WithArguments("Global.System.ComponentModel.EditorBrowsable"), Diagnostic(ERRID.ERR_NameNotMember2).WithArguments("ComponentModel", "System"), Diagnostic(ERRID.ERR_UndefinedType1).WithArguments("Global.System.ComponentModel.EditorBrowsable"), Diagnostic(ERRID.ERR_NameNotMember2).WithArguments("ComponentModel", "System"), Diagnostic(ERRID.ERR_UndefinedType1).WithArguments("Global.System.ComponentModel.EditorBrowsable"), Diagnostic(ERRID.ERR_NameNotMember2).WithArguments("ComponentModel", "System"), Diagnostic(ERRID.ERR_UndefinedType1).WithArguments("Global.System.ComponentModel.EditorBrowsable"), Diagnostic(ERRID.ERR_NameNotMember2).WithArguments("ComponentModel", "System"), Diagnostic(ERRID.ERR_UndefinedType1).WithArguments("Global.System.ComponentModel.EditorBrowsable"), Diagnostic(ERRID.ERR_NameNotMember2).WithArguments("ComponentModel", "System"), Diagnostic(ERRID.ERR_UndefinedType1).WithArguments("Global.System.ComponentModel.EditorBrowsable"), Diagnostic(ERRID.ERR_NameNotMember2).WithArguments("ComponentModel", "System"), Diagnostic(ERRID.ERR_UndefinedType1).WithArguments("Global.System.ComponentModel.EditorBrowsable"), Diagnostic(ERRID.ERR_NameNotMember2).WithArguments("ComponentModel", "System"), Diagnostic(ERRID.ERR_UndefinedType1).WithArguments("Global.System.ComponentModel.EditorBrowsable"), Diagnostic(ERRID.ERR_NameNotMember2).WithArguments("ComponentModel", "System")) End Sub #Region "Symbols Validator" Private Shared ReadOnly s_normalizeRegex As New Regex("^(\s*)", RegexOptions.Multiline) Private Sub ValidateSourceSymbols([module] As ModuleSymbol) ValidateSourceSymbol([module].GlobalNamespace) End Sub Private Sub ValidateSourceSymbol(symbol As Symbol) For Each reference In symbol.DeclaringSyntaxReferences Assert.False(reference.SyntaxTree.IsEmbeddedOrMyTemplateTree()) Next Select Case symbol.Kind Case SymbolKind.Namespace Dim [namespace] = DirectCast(symbol, NamespaceSymbol) For Each _type In From x In [namespace].GetTypeMembers() Select x Order By x.Name.ToLower() ValidateSourceSymbol(_type) Next For Each _ns In From x In [namespace].GetNamespaceMembers() Select x Order By x.Name.ToLower() ValidateSourceSymbol(_ns) Next Case SymbolKind.NamedType Dim type = DirectCast(symbol, NamedTypeSymbol) For Each _member In From x In type.GetMembers() Where x.Kind <> SymbolKind.NamedType Select x Order By x.ToTestDisplayString() ValidateSourceSymbol(_member) Next For Each _nested In From x In type.GetTypeMembers() Select x Order By x.Name.ToLower() ValidateSourceSymbol(_nested) Next End Select End Sub Private Sub ValidateSymbols([module] As ModuleSymbol, expected As String) Dim actualBuilder As New StringBuilder CollectAllTypesAndMembers([module].GlobalNamespace, actualBuilder, "") expected = expected.Trim() ' normalize Dim matches = s_normalizeRegex.Matches(expected) Dim captures = matches(matches.Count - 1).Groups(1).Captures Dim indent = captures(captures.Count - 1).Value If indent.Length > 0 Then expected = New Regex("^" + indent, RegexOptions.Multiline).Replace(expected, "") End If Dim actual = actualBuilder.ToString.Trim() If expected.Replace(vbLf, Environment.NewLine).CompareTo(actual) <> 0 Then Console.WriteLine("Actual:") Console.WriteLine(actual) Console.WriteLine() Console.WriteLine("Diff:") Console.WriteLine(DiffUtil.DiffReport(expected, actual)) Console.WriteLine() Assert.True(False) End If End Sub Private Sub AddSymbolAttributes(symbol As Symbol, builder As StringBuilder, indent As String) For Each attribute In symbol.GetAttributes() builder.AppendLine(indent + "[" + attribute.AttributeClass.ToTestDisplayString() + "]") Next End Sub Private Sub CollectAllTypesAndMembers(symbol As Symbol, builder As StringBuilder, indent As String) Const IndentStep = " " Select Case symbol.Kind Case SymbolKind.Namespace Dim [namespace] = DirectCast(symbol, NamespaceSymbol) builder.AppendLine(indent + "Namespace " + symbol.ToTestDisplayString) For Each _type In From x In [namespace].GetTypeMembers() Select x Order By x.Name.ToLower() CollectAllTypesAndMembers(_type, builder, indent + IndentStep) Next For Each _ns In From x In [namespace].GetNamespaceMembers() Select x Order By x.Name.ToLower() CollectAllTypesAndMembers(_ns, builder, indent + IndentStep) Next builder.AppendLine(indent + "End Namespace") Case SymbolKind.NamedType If symbol.Name <> "<Module>" Then AddSymbolAttributes(symbol, builder, indent) Dim type = DirectCast(symbol, NamedTypeSymbol) builder.AppendLine(indent + type.TypeKind.ToString() + " " + symbol.ToTestDisplayString) For Each _member In From x In type.GetMembers() Where x.Kind <> SymbolKind.NamedType Select x Order By x.ToTestDisplayString() AddSymbolAttributes(_member, builder, indent + IndentStep + " ") builder.AppendLine(indent + IndentStep + "> " + _member.ToTestDisplayString()) Next For Each _nested In From x In type.GetTypeMembers() Select x Order By x.Name.ToLower() CollectAllTypesAndMembers(_nested, builder, indent + IndentStep) Next builder.AppendLine(indent + "End " + type.TypeKind.ToString()) End If End Select End Sub #End Region #Region "Utilities" Protected NoVbRuntimeReferences As MetadataReference() = {MscorlibRef, SystemRef, SystemCoreRef} Friend Shadows Function CompileAndVerify( source As XElement, Optional expectedOutput As String = Nothing, Optional sourceSymbolValidator As Action(Of ModuleSymbol) = Nothing, Optional validator As Action(Of PEAssembly) = Nothing, Optional symbolValidator As Action(Of ModuleSymbol) = Nothing ) As CompilationVerifier Dim options = If(expectedOutput IsNot Nothing, TestOptions.ReleaseExe, TestOptions.ReleaseDll). WithMetadataImportOptions(MetadataImportOptions.Internal). WithEmbedVbCoreRuntime(True) Return MyBase.CompileAndVerify(source:=source, allReferences:=NoVbRuntimeReferences, expectedOutput:=expectedOutput, sourceSymbolValidator:=sourceSymbolValidator, validator:=validator, symbolValidator:=symbolValidator, options:=options) End Function #End Region End Class End Namespace
1
dotnet/roslyn
56,011
React to string comparison changing on .NET Core
The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
jaredpar
"2021-08-30T17:18:52Z"
"2021-08-30T20:20:04Z"
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
4d99cda6e446e77dbb302e26388c1093bd3ef569
React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
./src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IForLoopStatement.vb
' 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.Operations Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Partial Public Class IOperationTests Inherits SemanticModelTestBase <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")> Public Sub IForLoopStatement_SimpleForLoopsTest() Dim source = <![CDATA[ Public Class MyClass1 Public Shared Sub Main() Dim myarray As Integer() = New Integer(2) {1, 2, 3} For i As Integer = 0 To myarray.Length - 1'BIND:"For i As Integer = 0 To myarray.Length - 1" System.Console.WriteLine(myarray(i)) Next End Sub End Class ]]>.Value Dim expectedOperationTree = <![CDATA[ IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For i As In ... Next') Locals: Local_1: i As System.Int32 LoopControlVariable: IVariableDeclaratorOperation (Symbol: i As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i As Integer') Initializer: null InitialValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') LimitValue: IBinaryOperation (BinaryOperatorKind.Subtract, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: 'myarray.Length - 1') Left: IPropertyReferenceOperation: ReadOnly Property System.Array.Length As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'myarray.Length') Instance Receiver: ILocalReferenceOperation: myarray (OperationKind.LocalReference, Type: System.Int32()) (Syntax: 'myarray') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') StepValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For i As In ... Next') Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For i As In ... Next') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For i As In ... Next') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... myarray(i))') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Int32)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... myarray(i))') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'myarray(i)') IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.Int32) (Syntax: 'myarray(i)') Array reference: ILocalReferenceOperation: myarray (OperationKind.LocalReference, Type: System.Int32()) (Syntax: 'myarray') Indices(1): ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) NextVariables(0) ]]>.Value VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")> Public Sub IForLoopStatement_SimpleForLoopsTestConversion() Dim source = <![CDATA[ Option Strict Off Public Class MyClass1 Public Shared Sub Main() Dim myarray As Integer() = New Integer(1) {} myarray(0) = 1 myarray(1) = 2 Dim s As Double = 1.1 For i As Integer = 0 To "1" Step s'BIND:"For i As Integer = 0 To "1" Step s" System.Console.WriteLine(myarray(i)) Next End Sub End Class ]]>.Value Dim expectedOperationTree = <![CDATA[ IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'For i As In ... Next') Locals: Local_1: i As System.Int32 LoopControlVariable: IVariableDeclaratorOperation (Symbol: i As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i As Integer') Initializer: null InitialValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') LimitValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: '"1"') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "1") (Syntax: '"1"') StepValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: 's') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: s (OperationKind.LocalReference, Type: System.Double) (Syntax: 's') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For i As In ... Next') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... myarray(i))') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Int32)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... myarray(i))') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'myarray(i)') IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.Int32) (Syntax: 'myarray(i)') Array reference: ILocalReferenceOperation: myarray (OperationKind.LocalReference, Type: System.Int32()) (Syntax: 'myarray') Indices(1): ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) NextVariables(0) ]]>.Value VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree, TestOptions.ReleaseDll.WithOverflowChecks(False)) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")> Public Sub IForLoopStatement_ForLoopStepIsFloatNegativeVar() Dim source = <![CDATA[ Option Strict On Public Class MyClass1 Public Shared Sub Main() Dim s As Double = -1.1 For i As Double = 2 To 0 Step s'BIND:"For i As Double = 2 To 0 Step s" System.Console.WriteLine(i) Next End Sub End Class ]]>.Value Dim expectedOperationTree = <![CDATA[ IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For i As Do ... Next') Locals: Local_1: i As System.Double LoopControlVariable: IVariableDeclaratorOperation (Symbol: i As System.Double) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i As Double') Initializer: null InitialValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Double, Constant: 2, IsImplicit) (Syntax: '2') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') LimitValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Double, Constant: 0, IsImplicit) (Syntax: '0') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') StepValue: ILocalReferenceOperation: s (OperationKind.LocalReference, Type: System.Double) (Syntax: 's') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For i As Do ... Next') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... riteLine(i)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Double)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... riteLine(i)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'i') ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Double) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) NextVariables(0) ]]>.Value VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")> Public Sub IForLoopStatement_ForLoopObject() Dim source = <![CDATA[ Option Strict On Public Class MyClass1 Public Shared Sub Main() Dim ctrlVar As Object Dim initValue As Object = 0 Dim limit As Object = 2 Dim stp As Object = 1 For ctrlVar = initValue To limit Step stp'BIND:"For ctrlVar = initValue To limit Step stp" System.Console.WriteLine(ctrlVar) Next End Sub End Class ]]>.Value Dim expectedOperationTree = <![CDATA[ IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For ctrlVar ... Next') LoopControlVariable: ILocalReferenceOperation: ctrlVar (OperationKind.LocalReference, Type: System.Object) (Syntax: 'ctrlVar') InitialValue: ILocalReferenceOperation: initValue (OperationKind.LocalReference, Type: System.Object) (Syntax: 'initValue') LimitValue: ILocalReferenceOperation: limit (OperationKind.LocalReference, Type: System.Object) (Syntax: 'limit') StepValue: ILocalReferenceOperation: stp (OperationKind.LocalReference, Type: System.Object) (Syntax: 'stp') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For ctrlVar ... Next') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... ne(ctrlVar)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Object)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... ne(ctrlVar)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'ctrlVar') ILocalReferenceOperation: ctrlVar (OperationKind.LocalReference, Type: System.Object) (Syntax: 'ctrlVar') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) NextVariables(0) ]]>.Value VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")> Public Sub IForLoopStatement_ForLoopNested() Dim source = <![CDATA[ Option Strict On Option Infer On Public Class MyClass1 Public Shared Sub Main() For AVarName = 1 To 2'BIND:"For AVarName = 1 To 2" For B = 1 To 2 For C = 1 To 2 For D = 1 To 2 Next D Next C Next B Next AVarName End Sub End Class ]]>.Value Dim expectedOperationTree = <![CDATA[ IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For AVarNam ... xt AVarName') Locals: Local_1: AVarName As System.Int32 LoopControlVariable: IVariableDeclaratorOperation (Symbol: AVarName As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'AVarName') Initializer: null InitialValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') LimitValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') StepValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For AVarNam ... xt AVarName') Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For AVarNam ... xt AVarName') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For AVarNam ... xt AVarName') IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 2, Exit Label Id: 3, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For B = 1 T ... Next B') Locals: Local_1: B As System.Int32 LoopControlVariable: IVariableDeclaratorOperation (Symbol: B As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'B') Initializer: null InitialValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') LimitValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') StepValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For B = 1 T ... Next B') Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For B = 1 T ... Next B') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For B = 1 T ... Next B') IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 4, Exit Label Id: 5, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For C = 1 T ... Next C') Locals: Local_1: C As System.Int32 LoopControlVariable: IVariableDeclaratorOperation (Symbol: C As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'C') Initializer: null InitialValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') LimitValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') StepValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For C = 1 T ... Next C') Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For C = 1 T ... Next C') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For C = 1 T ... Next C') IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 6, Exit Label Id: 7, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For D = 1 T ... Next D') Locals: Local_1: D As System.Int32 LoopControlVariable: IVariableDeclaratorOperation (Symbol: D As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'D') Initializer: null InitialValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') LimitValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') StepValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For D = 1 T ... Next D') Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For D = 1 T ... Next D') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For D = 1 T ... Next D') NextVariables(1): ILocalReferenceOperation: D (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'D') NextVariables(1): ILocalReferenceOperation: C (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'C') NextVariables(1): ILocalReferenceOperation: B (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'B') NextVariables(1): ILocalReferenceOperation: AVarName (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'AVarName') ]]>.Value VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")> Public Sub IForLoopStatement_ChangeOuterVarInInnerFor() Dim source = <![CDATA[ Option Strict On Option Infer On Public Class MyClass1 Public Shared Sub Main() For I = 1 To 2'BIND:"For I = 1 To 2" For J = 1 To 2 I = 3 System.Console.WriteLine(I) Next Next End Sub End Class ]]>.Value Dim expectedOperationTree = <![CDATA[ IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For I = 1 T ... Next') Locals: Local_1: I As System.Int32 LoopControlVariable: IVariableDeclaratorOperation (Symbol: I As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'I') Initializer: null InitialValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') LimitValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') StepValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For I = 1 T ... Next') Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For I = 1 T ... Next') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For I = 1 T ... Next') IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 2, Exit Label Id: 3, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For J = 1 T ... Next') Locals: Local_1: J As System.Int32 LoopControlVariable: IVariableDeclaratorOperation (Symbol: J As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'J') Initializer: null InitialValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') LimitValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') StepValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For J = 1 T ... Next') Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For J = 1 T ... Next') Body: IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For J = 1 T ... Next') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'I = 3') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'I = 3') Left: ILocalReferenceOperation: I (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'I') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... riteLine(I)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Int32)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... riteLine(I)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'I') ILocalReferenceOperation: I (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'I') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) NextVariables(0) NextVariables(0) ]]>.Value VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")> Public Sub IForLoopStatement_InnerForRefOuterForVar() Dim source = <![CDATA[ Option Strict On Option Infer On Public Class MyClass1 Public Shared Sub Main() For I = 1 To 2'BIND:"For I = 1 To 2" For J = I + 1 To 2 System.Console.WriteLine(J) Next Next End Sub End Class ]]>.Value Dim expectedOperationTree = <![CDATA[ IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For I = 1 T ... Next') Locals: Local_1: I As System.Int32 LoopControlVariable: IVariableDeclaratorOperation (Symbol: I As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'I') Initializer: null InitialValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') LimitValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') StepValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For I = 1 T ... Next') Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For I = 1 T ... Next') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For I = 1 T ... Next') IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 2, Exit Label Id: 3, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For J = I + ... Next') Locals: Local_1: J As System.Int32 LoopControlVariable: IVariableDeclaratorOperation (Symbol: J As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'J') Initializer: null InitialValue: IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: 'I + 1') Left: ILocalReferenceOperation: I (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'I') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') LimitValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') StepValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For J = I + ... Next') Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For J = I + ... Next') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For J = I + ... Next') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... riteLine(J)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Int32)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... riteLine(J)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'J') ILocalReferenceOperation: J (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'J') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) NextVariables(0) NextVariables(0) ]]>.Value VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")> Public Sub IForLoopStatement_ExitNestedFor() Dim source = <![CDATA[ Option Strict On Option Infer On Public Class MyClass1 Public Shared Sub Main() For I = 1 To 2'BIND:"For I = 1 To 2" For J = 1 To 2 Exit For Next System.Console.WriteLine(I) Next End Sub End Class ]]>.Value Dim expectedOperationTree = <![CDATA[ IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For I = 1 T ... Next') Locals: Local_1: I As System.Int32 LoopControlVariable: IVariableDeclaratorOperation (Symbol: I As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'I') Initializer: null InitialValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') LimitValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') StepValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For I = 1 T ... Next') Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For I = 1 T ... Next') Body: IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For I = 1 T ... Next') IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 2, Exit Label Id: 3, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For J = 1 T ... Next') Locals: Local_1: J As System.Int32 LoopControlVariable: IVariableDeclaratorOperation (Symbol: J As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'J') Initializer: null InitialValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') LimitValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') StepValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For J = 1 T ... Next') Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For J = 1 T ... Next') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For J = 1 T ... Next') IBranchOperation (BranchKind.Break, Label Id: 3) (OperationKind.Branch, Type: null) (Syntax: 'Exit For') NextVariables(0) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... riteLine(I)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Int32)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... riteLine(I)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'I') ILocalReferenceOperation: I (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'I') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) NextVariables(0) ]]>.Value VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")> Public Sub IForLoopStatement_EnumAsStart() Dim source = <![CDATA[ Option Strict Off Option Infer Off Public Class MyClass1 Public Shared Sub Main() For x As e1 = e1.a To e1.c'BIND:"For x As e1 = e1.a To e1.c" Next End Sub End Class Enum e1 a b c End Enum ]]>.Value Dim expectedOperationTree = <![CDATA[ IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For x As e1 ... Next') Locals: Local_1: x As e1 LoopControlVariable: IVariableDeclaratorOperation (Symbol: x As e1) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x As e1') Initializer: null InitialValue: IFieldReferenceOperation: e1.a (Static) (OperationKind.FieldReference, Type: e1, Constant: 0) (Syntax: 'e1.a') Instance Receiver: null LimitValue: IFieldReferenceOperation: e1.c (Static) (OperationKind.FieldReference, Type: e1, Constant: 2) (Syntax: 'e1.c') Instance Receiver: null StepValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: e1, Constant: 1, IsImplicit) (Syntax: 'For x As e1 ... Next') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For x As e1 ... Next') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For x As e1 ... Next') NextVariables(0) ]]>.Value VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")> Public Sub IForLoopStatement_PropertyAsStart() Dim source = <![CDATA[ Option Strict Off Option Infer Off Public Class MyClass1 Property P1(ByVal x As Long) As Byte Get Return x - 10 End Get Set(ByVal Value As Byte) End Set End Property Public Shared Sub Main() End Sub Public Sub F() For i As Integer = P1(30 + i) To 30'BIND:"For i As Integer = P1(30 + i) To 30" Next End Sub End Class ]]>.Value Dim expectedOperationTree = <![CDATA[ IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For i As In ... Next') Locals: Local_1: i As System.Int32 LoopControlVariable: IVariableDeclaratorOperation (Symbol: i As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i As Integer') Initializer: null InitialValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: 'P1(30 + i)') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IPropertyReferenceOperation: Property MyClass1.P1(x As System.Int64) As System.Byte (OperationKind.PropertyReference, Type: System.Byte) (Syntax: 'P1(30 + i)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: MyClass1, IsImplicit) (Syntax: 'P1') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: '30 + i') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int64, IsImplicit) (Syntax: '30 + i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: '30 + i') Left: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 30) (Syntax: '30') Right: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) LimitValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 30) (Syntax: '30') StepValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For i As In ... Next') Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For i As In ... Next') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For i As In ... Next') NextVariables(0) ]]>.Value VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")> Public Sub IForLoopStatement_FieldNameAsIteration() Dim source = <![CDATA[ Option Strict Off Option Infer On Public Class MyClass1 Dim global_x As Integer = 10 Const global_y As Long = 20 Public Shared Sub Main() For global_x As Integer = global_y To 10'BIND:"For global_x As Integer = global_y To 10" Next End Sub End Class ]]>.Value Dim expectedOperationTree = <![CDATA[ IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For global_ ... Next') Locals: Local_1: global_x As System.Int32 LoopControlVariable: IVariableDeclaratorOperation (Symbol: global_x As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'global_x As Integer') Initializer: null InitialValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 20, IsImplicit) (Syntax: 'global_y') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IFieldReferenceOperation: MyClass1.global_y As System.Int64 (Static) (OperationKind.FieldReference, Type: System.Int64, Constant: 20) (Syntax: 'global_y') Instance Receiver: null LimitValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') StepValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For global_ ... Next') Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For global_ ... Next') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For global_ ... Next') NextVariables(0) ]]>.Value VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")> Public Sub IForLoopStatement_SingleLine() Dim source = <![CDATA[ Option Strict On Public Class MyClass1 Public Shared Sub Main() For x As Integer = 0 To 10 : Next'BIND:"For x As Integer = 0 To 10 : Next" End Sub End Class ]]>.Value Dim expectedOperationTree = <![CDATA[ IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For x As In ... o 10 : Next') Locals: Local_1: x As System.Int32 LoopControlVariable: IVariableDeclaratorOperation (Symbol: x As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x As Integer') Initializer: null InitialValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') LimitValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') StepValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For x As In ... o 10 : Next') Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For x As In ... o 10 : Next') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For x As In ... o 10 : Next') NextVariables(0) ]]>.Value VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")> Public Sub IForLoopStatement_VarDeclOutOfForeach() Dim source = <![CDATA[ Option Strict On Option Infer On Public Class MyClass1 Public Shared Sub Main() Dim Y As Integer For Y = 1 To 2'BIND:"For Y = 1 To 2" Next End Sub End Class ]]>.Value Dim expectedOperationTree = <![CDATA[ IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For Y = 1 T ... Next') LoopControlVariable: ILocalReferenceOperation: Y (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'Y') InitialValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') LimitValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') StepValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For Y = 1 T ... Next') Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For Y = 1 T ... Next') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Y = 1 T ... Next') NextVariables(0) ]]>.Value VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")> Public Sub IForLoopStatement_GetDeclaredSymbolOfForStatement() Dim source = <![CDATA[ Option Strict On Option Infer On Imports System Imports System.Collection Class C1 Public Shared Sub Main() For element1 = 23 To 42'BIND:"For element1 = 23 To 42" Next For element2 As Integer = 23 To 42 Next End Sub End Class ]]>.Value Dim expectedOperationTree = <![CDATA[ IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For element ... Next') Locals: Local_1: element1 As System.Int32 LoopControlVariable: IVariableDeclaratorOperation (Symbol: element1 As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'element1') Initializer: null InitialValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 23) (Syntax: '23') LimitValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 42) (Syntax: '42') StepValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For element ... Next') Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For element ... Next') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For element ... Next') NextVariables(0) ]]>.Value VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")> Public Sub IForLoopStatement_ForLoopContinue() Dim source = <![CDATA[ Option Strict On Option Infer On Imports System Imports System.Collection Class C1 Public Shared Sub Main() For i As Integer = 0 To 5'BIND:"For i As Integer = 0 To 5" If i Mod 2 = 0 Then Continue For End If Next End Sub End Class ]]>.Value Dim expectedOperationTree = <![CDATA[ IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For i As In ... Next') Locals: Local_1: i As System.Int32 LoopControlVariable: IVariableDeclaratorOperation (Symbol: i As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i As Integer') Initializer: null InitialValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') LimitValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') StepValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For i As In ... Next') Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For i As In ... Next') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For i As In ... Next') IConditionalOperation (OperationKind.Conditional, Type: null) (Syntax: 'If i Mod 2 ... End If') Condition: IBinaryOperation (BinaryOperatorKind.Equals, Checked) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'i Mod 2 = 0') Left: IBinaryOperation (BinaryOperatorKind.Remainder, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: 'i Mod 2') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') WhenTrue: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'If i Mod 2 ... End If') IBranchOperation (BranchKind.Continue, Label Id: 0) (OperationKind.Branch, Type: null) (Syntax: 'Continue For') WhenFalse: null NextVariables(0) ]]>.Value VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")> Public Sub IForLoopStatement_ForReverse() Dim source = <![CDATA[ Option Infer On Module Program Sub Main() For X = 10 To 0'BIND:"For X = 10 To 0" Next End Sub End Module Module M Public X As Integer End Module ]]>.Value Dim expectedOperationTree = <![CDATA[ IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For X = 10 ... Next') LoopControlVariable: IFieldReferenceOperation: M.X As System.Int32 (Static) (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'X') Instance Receiver: null InitialValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') LimitValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') StepValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For X = 10 ... Next') Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For X = 10 ... Next') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For X = 10 ... Next') NextVariables(0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of ForBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")> Public Sub IForLoopStatement_InValid() Dim source = <![CDATA[ Option Infer On Module Program Sub Main() For X = 10 To 0'BIND:"For X = 10 To 0" Next End Sub End Module Module M Public X As String End Module ]]>.Value Dim expectedOperationTree = <![CDATA[ IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null, IsInvalid) (Syntax: 'For X = 10 ... Next') LoopControlVariable: IFieldReferenceOperation: M.X As System.String (Static) (OperationKind.FieldReference, Type: System.String, IsInvalid) (Syntax: 'X') Instance Receiver: null InitialValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') LimitValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') StepValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid, IsImplicit) (Syntax: 'For X = 10 ... Next') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'For X = 10 ... Next') NextVariables(0) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30337: 'For' loop control variable cannot be of type 'String' because the type does not support the required operators. For X = 10 To 0'BIND:"For X = 10 To 0" ~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of ForBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")> Public Sub IForLoopStatement_ForCombined() Dim source = <![CDATA[ Option Infer On Module Program Sub Main(args As String()) For A = 1 To 2'BIND:"For A = 1 To 2" For B = A To 2 Next B, A End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For A = 1 T ... Next B, A') Locals: Local_1: A As System.Int32 LoopControlVariable: IVariableDeclaratorOperation (Symbol: A As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'A') Initializer: null InitialValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') LimitValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') StepValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For A = 1 T ... Next B, A') Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For A = 1 T ... Next B, A') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For A = 1 T ... Next B, A') IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 2, Exit Label Id: 3, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For B = A T ... Next B, A') Locals: Local_1: B As System.Int32 LoopControlVariable: IVariableDeclaratorOperation (Symbol: B As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'B') Initializer: null InitialValue: ILocalReferenceOperation: A (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'A') LimitValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') StepValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For B = A T ... Next B, A') Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For B = A T ... Next B, A') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For B = A T ... Next B, A') NextVariables(2): ILocalReferenceOperation: B (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'B') ILocalReferenceOperation: A (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'A') NextVariables(0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of ForBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub VerifyForToLoop1() Dim source = <![CDATA[ Structure C Sub F() Dim x As Integer Dim y As Integer = 16 For x = 12 To y 'BIND:"For x = 12 To y" Next End Sub End Structure ]]>.Value Dim expectedOperationTree = <![CDATA[ IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For x = 12 ... Next') LoopControlVariable: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x') InitialValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 12) (Syntax: '12') LimitValue: ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'y') StepValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For x = 12 ... Next') Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For x = 12 ... Next') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For x = 12 ... Next') NextVariables(0) ]]>.Value VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub VerifyForToLoop2() Dim source = <![CDATA[ Structure C Sub F() Dim x As Integer? Dim y As Integer = 16 For x = 12 To y 'BIND:"For x = 12 To y" Next End Sub End Structure ]]>.Value Dim expectedOperationTree = <![CDATA[ IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For x = 12 ... Next') LoopControlVariable: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'x') InitialValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: '12') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 12) (Syntax: '12') LimitValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'y') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'y') StepValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'For x = 12 ... Next') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For x = 12 ... Next') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For x = 12 ... Next') NextVariables(0) ]]>.Value VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub VerifyForToLoop3() Dim source = <![CDATA[ Structure C Sub F() Dim x As Integer Dim y As Integer? = 16 For x = 12 To y 'BIND:"For x = 12 To y" Next End Sub End Structure ]]>.Value Dim expectedOperationTree = <![CDATA[ IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For x = 12 ... Next') LoopControlVariable: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x') InitialValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 12) (Syntax: '12') LimitValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: 'y') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'y') StepValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For x = 12 ... Next') Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For x = 12 ... Next') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For x = 12 ... Next') NextVariables(0) ]]>.Value VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub VerifyForToLoop4() Dim source = <![CDATA[ Structure C Sub F() Dim x As Integer? Dim y As Integer? = 16 For x = 12 To y 'BIND:"For x = 12 To y" Next End Sub End Structure ]]>.Value Dim expectedOperationTree = <![CDATA[ IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For x = 12 ... Next') LoopControlVariable: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'x') InitialValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: '12') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 12) (Syntax: '12') LimitValue: ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'y') StepValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'For x = 12 ... Next') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For x = 12 ... Next') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For x = 12 ... Next') NextVariables(0) ]]>.Value VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub VerifyForToLoop5() Dim source = <![CDATA[ Structure C Sub F() Dim x As Integer Dim y As Integer = 16 Dim s As Integer? = nothing For x = 12 To y Step s 'BIND:"For x = 12 To y Step s" Next End Sub End Structure ]]>.Value Dim expectedOperationTree = <![CDATA[ IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For x = 12 ... Next') LoopControlVariable: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x') InitialValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 12) (Syntax: '12') LimitValue: ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'y') StepValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: 's') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: s (OperationKind.LocalReference, Type: System.Nullable(Of System.Int32)) (Syntax: 's') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For x = 12 ... Next') NextVariables(0) ]]>.Value VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub VerifyForToLoop6() Dim source = <![CDATA[ Structure C Sub F() Dim x As Integer? Dim y As Integer = 16 Dim s As Integer? = nothing For x = 12 To y Step s 'BIND:"For x = 12 To y Step s" Next End Sub End Structure ]]>.Value Dim expectedOperationTree = <![CDATA[ IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For x = 12 ... Next') LoopControlVariable: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'x') InitialValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: '12') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 12) (Syntax: '12') LimitValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'y') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'y') StepValue: ILocalReferenceOperation: s (OperationKind.LocalReference, Type: System.Nullable(Of System.Int32)) (Syntax: 's') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For x = 12 ... Next') NextVariables(0) ]]>.Value VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub VerifyForToLoop7() Dim source = <![CDATA[ Structure C Sub F() Dim x As Integer Dim y As Integer? = 16 Dim s As Integer? = nothing For x = 12 To y Step s 'BIND:"For x = 12 To y Step s" Next End Sub End Structure ]]>.Value Dim expectedOperationTree = <![CDATA[ IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For x = 12 ... Next') LoopControlVariable: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x') InitialValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 12) (Syntax: '12') LimitValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: 'y') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'y') StepValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: 's') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: s (OperationKind.LocalReference, Type: System.Nullable(Of System.Int32)) (Syntax: 's') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For x = 12 ... Next') NextVariables(0) ]]>.Value VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub VerifyForToLoop8() Dim source = <![CDATA[ Structure C Sub F() Dim x As Integer? Dim y As Integer? = 16 Dim s As Integer? = nothing For x = 12 To y Step s 'BIND:"For x = 12 To y Step s" Next End Sub End Structure ]]>.Value Dim expectedOperationTree = <![CDATA[ IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For x = 12 ... Next') LoopControlVariable: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'x') InitialValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: '12') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 12) (Syntax: '12') LimitValue: ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'y') StepValue: ILocalReferenceOperation: s (OperationKind.LocalReference, Type: System.Nullable(Of System.Int32)) (Syntax: 's') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For x = 12 ... Next') NextVariables(0) ]]>.Value VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub VerifyForToLoop_FieldAsIterationVariable() Dim source = <![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Class C Private X As Integer = 0 Sub M() For X = 0 To 10'BIND:"For X = 0 To 10" Next X End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For X = 0 T ... Next X') LoopControlVariable: IFieldReferenceOperation: C.X As System.Int32 (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'X') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'X') InitialValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') LimitValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') StepValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For X = 0 T ... Next X') Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For X = 0 T ... Next X') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For X = 0 T ... Next X') NextVariables(1): IFieldReferenceOperation: C.X As System.Int32 (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'X') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'X') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of ForBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub VerifyForToLoop_FieldWithExplicitReceiverAsIterationVariable() Dim source = <![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Class C Private X As Integer = 0 Sub M(c As C) For c.X = 0 To 10'BIND:"For c.X = 0 To 10" Next c.X End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For c.X = 0 ... Next c.X') LoopControlVariable: IFieldReferenceOperation: C.X As System.Int32 (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'c.X') Instance Receiver: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c') InitialValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') LimitValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') StepValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For c.X = 0 ... Next c.X') Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For c.X = 0 ... Next c.X') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For c.X = 0 ... Next c.X') NextVariables(1): IFieldReferenceOperation: C.X As System.Int32 (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'c.X') Instance Receiver: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of ForBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub VerifyForToLoop_InvalidLoopControlVariableDeclaration() Dim source = <![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Class C Sub M() Dim i as Integer = 0 For i as Integer = 0 To 10'BIND:"For i as Integer = 0 To 10" Next i End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null, IsInvalid) (Syntax: 'For i as In ... Next i') Locals: Local_1: i As System.Int32 LoopControlVariable: IVariableDeclaratorOperation (Symbol: i As System.Int32) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'i as Integer') Initializer: null InitialValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') LimitValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') StepValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsInvalid, IsImplicit) (Syntax: 'For i as In ... Next i') Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid, IsImplicit) (Syntax: 'For i as In ... Next i') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'For i as In ... Next i') NextVariables(1): ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30616: Variable 'i' hides a variable in an enclosing block. For i as Integer = 0 To 10'BIND:"For i as Integer = 0 To 10" ~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of ForBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForToFlow_01() Dim source = <![CDATA[ Imports System Public Class C Sub M(result As Integer) 'BIND:"Sub M" For i As UInteger = 0UI To 2UI result = if(i > 0UI, 3, 4) Next End Sub End Class]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [i As System.UInt32] CaptureIds: [2] [3] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (5) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i As UInteger') Value: ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.UInt32, IsImplicit) (Syntax: 'i As UInteger') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '0UI') Value: ILiteralOperation (OperationKind.Literal, Type: System.UInt32, Constant: 0) (Syntax: '0UI') IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '2UI') Value: ILiteralOperation (OperationKind.Literal, Type: System.UInt32, Constant: 2) (Syntax: '2UI') IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'For i As UI ... Next') Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.UInt32, Constant: 1, IsImplicit) (Syntax: 'For i As UI ... Next') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (WideningNumeric, InvolvesNarrowingFromNumericConstant) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For i As UI ... Next') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: '0UI') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.UInt32, IsImplicit) (Syntax: 'i As UInteger') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.UInt32, Constant: 0, IsImplicit) (Syntax: '0UI') Next (Regular) Block[B2] Leaving: {R2} } Block[B2] - Block Predecessors: [B1] [B7] Statements (0) Jump if False (Regular) to Block[B8] IBinaryOperation (BinaryOperatorKind.LessThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '2UI') Left: ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.UInt32, IsImplicit) (Syntax: 'i As UInteger') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.UInt32, Constant: 2, IsImplicit) (Syntax: '2UI') Leaving: {R1} Next (Regular) Block[B3] Entering: {R3} .locals {R3} { CaptureIds: [4] [5] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result') Value: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result') Jump if False (Regular) to Block[B5] IBinaryOperation (BinaryOperatorKind.GreaterThan, Checked) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'i > 0UI') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.UInt32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.UInt32, Constant: 0) (Syntax: '0UI') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B3] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '3') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') Next (Regular) Block[B6] Block[B5] - Block Predecessors: [B3] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '4') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4') Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B4] [B5] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = if ... 0UI, 3, 4)') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'result = if ... 0UI, 3, 4)') Left: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'result') Right: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'if(i > 0UI, 3, 4)') Next (Regular) Block[B7] Leaving: {R3} } Block[B7] - Block Predecessors: [B6] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'i As UInteger') Left: ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.UInt32, IsImplicit) (Syntax: 'i As UInteger') Right: IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.UInt32, IsImplicit) (Syntax: 'For i As UI ... Next') Left: ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.UInt32, IsImplicit) (Syntax: 'i As UInteger') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.UInt32, Constant: 1, IsImplicit) (Syntax: 'For i As UI ... Next') Next (Regular) Block[B2] } Block[B8] - Exit Predecessors: [B2] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForToFlow_02() Dim source = <![CDATA[ Imports System Public Class C Sub M(i As Integer, result As Integer) 'BIND:"Sub M" For i = 0 To 4 Step 2 result = i Next End Sub End Class]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [2] [3] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (5) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '0') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '4') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4') IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '2') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: '0') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: '0') Next (Regular) Block[B2] Leaving: {R2} } Block[B2] - Block Predecessors: [B1] [B3] Statements (0) Jump if False (Regular) to Block[B4] IBinaryOperation (BinaryOperatorKind.LessThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '4') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 4, IsImplicit) (Syntax: '4') Leaving: {R1} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'result = i') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result') Right: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'i') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32, IsImplicit) (Syntax: '2') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: '2') Next (Regular) Block[B2] } Block[B4] - Exit Predecessors: [B2] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics, TestOptions.ReleaseDll.WithOverflowChecks(False)) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForToFlow_03() Dim source = <![CDATA[ Imports System Public Class C Sub M(i As Decimal, result As Decimal) 'BIND:"Sub M" For i = 3D To 0D Step -1D result = i Next End Sub End Class]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [2] [3] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (5) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Decimal) (Syntax: 'i') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '3D') Value: ILiteralOperation (OperationKind.Literal, Type: System.Decimal, Constant: 3) (Syntax: '3D') IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '0D') Value: ILiteralOperation (OperationKind.Literal, Type: System.Decimal, Constant: 0) (Syntax: '0D') IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '-1D') Value: IUnaryOperation (UnaryOperatorKind.Minus, Checked) (OperationKind.Unary, Type: System.Decimal, Constant: -1) (Syntax: '-1D') Operand: ILiteralOperation (OperationKind.Literal, Type: System.Decimal, Constant: 1) (Syntax: '1D') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: '3D') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Decimal, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Decimal, Constant: 3, IsImplicit) (Syntax: '3D') Next (Regular) Block[B2] Leaving: {R2} } Block[B2] - Block Predecessors: [B1] [B3] Statements (0) Jump if False (Regular) to Block[B4] IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '0D') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Decimal, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Decimal, Constant: 0, IsImplicit) (Syntax: '0D') Leaving: {R1} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Decimal, IsImplicit) (Syntax: 'result = i') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Decimal) (Syntax: 'result') Right: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Decimal) (Syntax: 'i') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'i') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Decimal, IsImplicit) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Decimal, IsImplicit) (Syntax: '-1D') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Decimal, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Decimal, Constant: -1, IsImplicit) (Syntax: '-1D') Next (Regular) Block[B2] } Block[B4] - Exit Predecessors: [B2] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForToFlow_04() Dim source = <![CDATA[ Imports System Public Class C Sub M(i As Short, [step] As Short, result As Short) 'BIND:"Sub M" For i = 0S To 4S Step [step] result = i Next End Sub End Class]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [2] [3] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (5) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int16) (Syntax: 'i') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '0S') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int16, Constant: 0) (Syntax: '0S') IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '4S') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int16, Constant: 4) (Syntax: '4S') IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '[step]') Value: IParameterReferenceOperation: step (OperationKind.ParameterReference, Type: System.Int16) (Syntax: '[step]') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: '0S') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int16, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int16, Constant: 0, IsImplicit) (Syntax: '0S') Next (Regular) Block[B2] Leaving: {R2} } Block[B2] - Block Predecessors: [B1] [B3] Statements (0) Jump if False (Regular) to Block[B4] IBinaryOperation (BinaryOperatorKind.LessThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '4S') Left: IBinaryOperation (BinaryOperatorKind.ExclusiveOr) (OperationKind.Binary, Type: System.Int16, IsImplicit) (Syntax: 'i') Left: IBinaryOperation (BinaryOperatorKind.RightShift) (OperationKind.Binary, Type: System.Int16, IsImplicit) (Syntax: 'i') Left: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int16, IsImplicit) (Syntax: '[step]') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 15, IsImplicit) (Syntax: 'i') Right: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int16, IsImplicit) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.ExclusiveOr) (OperationKind.Binary, Type: System.Int16, IsImplicit) (Syntax: '4S') Left: IBinaryOperation (BinaryOperatorKind.RightShift) (OperationKind.Binary, Type: System.Int16, IsImplicit) (Syntax: '4S') Left: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int16, IsImplicit) (Syntax: '[step]') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 15, IsImplicit) (Syntax: '4S') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int16, Constant: 4, IsImplicit) (Syntax: '4S') Leaving: {R1} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int16, IsImplicit) (Syntax: 'result = i') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int16) (Syntax: 'result') Right: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int16) (Syntax: 'i') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'i') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int16, IsImplicit) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int16, IsImplicit) (Syntax: '[step]') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int16, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int16, IsImplicit) (Syntax: '[step]') Next (Regular) Block[B2] } Block[B4] - Exit Predecessors: [B2] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForToFlow_05() Dim source = <![CDATA[ Imports System Public Class C Sub M(i As Decimal, [step] As Decimal, result As Decimal) 'BIND:"Sub M" For i = 3D To 0D Step [step] result = i Next End Sub End Class]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [2] [3] [4] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (6) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Decimal) (Syntax: 'i') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '3D') Value: ILiteralOperation (OperationKind.Literal, Type: System.Decimal, Constant: 3) (Syntax: '3D') IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '0D') Value: ILiteralOperation (OperationKind.Literal, Type: System.Decimal, Constant: 0) (Syntax: '0D') IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '[step]') Value: IParameterReferenceOperation: step (OperationKind.ParameterReference, Type: System.Decimal) (Syntax: '[step]') IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '[step]') Value: IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '[step]') Left: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Decimal, IsImplicit) (Syntax: '[step]') Right: ILiteralOperation (OperationKind.Literal, Type: System.Decimal, Constant: 0, IsImplicit) (Syntax: '[step]') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: '3D') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Decimal, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Decimal, Constant: 3, IsImplicit) (Syntax: '3D') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} } .locals {R3} { CaptureIds: [5] Block[B2] - Block Predecessors: [B1] [B5] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Decimal, IsImplicit) (Syntax: 'i') Jump if False (Regular) to Block[B4] IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: '[step]') Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (0) Jump if False (Regular) to Block[B6] IBinaryOperation (BinaryOperatorKind.LessThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '0D') Left: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Decimal, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Decimal, Constant: 0, IsImplicit) (Syntax: '0D') Leaving: {R3} {R1} Next (Regular) Block[B5] Leaving: {R3} Block[B4] - Block Predecessors: [B2] Statements (0) Jump if False (Regular) to Block[B6] IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '0D') Left: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Decimal, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Decimal, Constant: 0, IsImplicit) (Syntax: '0D') Leaving: {R3} {R1} Next (Regular) Block[B5] Leaving: {R3} } Block[B5] - Block Predecessors: [B3] [B4] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Decimal, IsImplicit) (Syntax: 'result = i') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Decimal) (Syntax: 'result') Right: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Decimal) (Syntax: 'i') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'i') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Decimal, IsImplicit) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Decimal, IsImplicit) (Syntax: '[step]') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Decimal, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Decimal, IsImplicit) (Syntax: '[step]') Next (Regular) Block[B2] Entering: {R3} } Block[B6] - Exit Predecessors: [B3] [B4] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForToFlow_06() Dim source = <![CDATA[ Imports System Public Enum MyEnum As UShort One = 1 End Enum Public Class C Sub M(i as MyEnum, init As MyEnum, limit As MyEnum, [step] as MyEnum, result As MyEnum) 'BIND:"Sub M" For i = init To limit Step [step] result = i Next End Sub End Class]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [2] [3] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (5) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: MyEnum) (Syntax: 'i') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init') Value: IParameterReferenceOperation: init (OperationKind.ParameterReference, Type: MyEnum) (Syntax: 'init') IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit') Value: IParameterReferenceOperation: limit (OperationKind.ParameterReference, Type: MyEnum) (Syntax: 'limit') IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '[step]') Value: IParameterReferenceOperation: step (OperationKind.ParameterReference, Type: MyEnum) (Syntax: '[step]') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'init') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyEnum, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: MyEnum, IsImplicit) (Syntax: 'init') Next (Regular) Block[B2] Leaving: {R2} } Block[B2] - Block Predecessors: [B1] [B3] Statements (0) Jump if False (Regular) to Block[B4] IBinaryOperation (BinaryOperatorKind.LessThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'limit') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: MyEnum, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: MyEnum, IsImplicit) (Syntax: 'limit') Leaving: {R1} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: MyEnum, IsImplicit) (Syntax: 'result = i') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: MyEnum) (Syntax: 'result') Right: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: MyEnum) (Syntax: 'i') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'i') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: MyEnum, IsImplicit) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: MyEnum, IsImplicit) (Syntax: '[step]') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: MyEnum, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: MyEnum, IsImplicit) (Syntax: '[step]') Next (Regular) Block[B2] } Block[B4] - Exit Predecessors: [B2] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForToFlow_07() Dim source = <![CDATA[ Imports System Public Enum MyEnum As SByte One = 1 End Enum Public Class C Sub M(i as MyEnum, init As MyEnum, limit As MyEnum, [step] as MyEnum, result As MyEnum) 'BIND:"Sub M" For i = init To limit Step [step] result = i Next End Sub End Class]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [2] [3] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (5) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: MyEnum) (Syntax: 'i') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init') Value: IParameterReferenceOperation: init (OperationKind.ParameterReference, Type: MyEnum) (Syntax: 'init') IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit') Value: IParameterReferenceOperation: limit (OperationKind.ParameterReference, Type: MyEnum) (Syntax: 'limit') IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '[step]') Value: IParameterReferenceOperation: step (OperationKind.ParameterReference, Type: MyEnum) (Syntax: '[step]') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'init') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyEnum, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: MyEnum, IsImplicit) (Syntax: 'init') Next (Regular) Block[B2] Leaving: {R2} } Block[B2] - Block Predecessors: [B1] [B3] Statements (0) Jump if False (Regular) to Block[B4] IBinaryOperation (BinaryOperatorKind.LessThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'limit') Left: IBinaryOperation (BinaryOperatorKind.ExclusiveOr) (OperationKind.Binary, Type: MyEnum, IsImplicit) (Syntax: 'i') Left: IBinaryOperation (BinaryOperatorKind.RightShift) (OperationKind.Binary, Type: MyEnum, IsImplicit) (Syntax: 'i') Left: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: MyEnum, IsImplicit) (Syntax: '[step]') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 7, IsImplicit) (Syntax: 'i') Right: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: MyEnum, IsImplicit) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.ExclusiveOr) (OperationKind.Binary, Type: MyEnum, IsImplicit) (Syntax: 'limit') Left: IBinaryOperation (BinaryOperatorKind.RightShift) (OperationKind.Binary, Type: MyEnum, IsImplicit) (Syntax: 'limit') Left: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: MyEnum, IsImplicit) (Syntax: '[step]') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 7, IsImplicit) (Syntax: 'limit') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: MyEnum, IsImplicit) (Syntax: 'limit') Leaving: {R1} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: MyEnum, IsImplicit) (Syntax: 'result = i') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: MyEnum) (Syntax: 'result') Right: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: MyEnum) (Syntax: 'i') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'i') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: MyEnum, IsImplicit) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: MyEnum, IsImplicit) (Syntax: '[step]') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: MyEnum, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: MyEnum, IsImplicit) (Syntax: '[step]') Next (Regular) Block[B2] } Block[B4] - Exit Predecessors: [B2] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForToFlow_08() Dim source = <![CDATA[ Imports System Public Enum MyEnum As Long MinusOne = -1 End Enum Public Class C Sub M(i as MyEnum, init As MyEnum, limit As MyEnum, result As MyEnum) 'BIND:"Sub M" For i = init To limit Step MyEnum.MinusOne result = i Next End Sub End Class]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [2] [3] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (5) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: MyEnum) (Syntax: 'i') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init') Value: IParameterReferenceOperation: init (OperationKind.ParameterReference, Type: MyEnum) (Syntax: 'init') IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit') Value: IParameterReferenceOperation: limit (OperationKind.ParameterReference, Type: MyEnum) (Syntax: 'limit') IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'MyEnum.MinusOne') Value: IFieldReferenceOperation: MyEnum.MinusOne (Static) (OperationKind.FieldReference, Type: MyEnum, Constant: -1) (Syntax: 'MyEnum.MinusOne') Instance Receiver: null ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'init') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyEnum, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: MyEnum, IsImplicit) (Syntax: 'init') Next (Regular) Block[B2] Leaving: {R2} } Block[B2] - Block Predecessors: [B1] [B3] Statements (0) Jump if False (Regular) to Block[B4] IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'limit') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: MyEnum, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: MyEnum, IsImplicit) (Syntax: 'limit') Leaving: {R1} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: MyEnum, IsImplicit) (Syntax: 'result = i') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: MyEnum) (Syntax: 'result') Right: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: MyEnum) (Syntax: 'i') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'i') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: MyEnum, IsImplicit) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: MyEnum, IsImplicit) (Syntax: 'MyEnum.MinusOne') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: MyEnum, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: MyEnum, Constant: -1, IsImplicit) (Syntax: 'MyEnum.MinusOne') Next (Regular) Block[B2] } Block[B4] - Exit Predecessors: [B2] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForToFlow_09() Dim source = <![CDATA[ Imports System Public Class C Sub M(i As Integer?, init As Integer?, limit As Integer?, [step] As Integer?, result As Integer?) 'BIND:"Sub M" For i = init To limit Step [step] result = i Next End Sub End Class]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [2] [3] [4] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (4) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'i') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init') Value: IParameterReferenceOperation: init (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'init') IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit') Value: IParameterReferenceOperation: limit (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'limit') IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '[step]') Value: IParameterReferenceOperation: step (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: '[step]') Jump if False (Regular) to Block[B3] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: '[step]') Operand: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: '[step]') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '[step]') Value: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False, IsImplicit) (Syntax: '[step]') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '[step]') Value: IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '[step]') Left: IInvocationOperation ( Function System.Nullable(Of System.Int32).GetValueOrDefault() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: '[step]') Instance Receiver: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: '[step]') Arguments(0) Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: '[step]') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'init') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'init') Next (Regular) Block[B5] Leaving: {R2} } Block[B5] - Block Predecessors: [B4] [B11] [B12] Statements (0) Jump if False (Regular) to Block[B6] IBinaryOperation (BinaryOperatorKind.Or) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '[step]') Left: IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'limit') Operand: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'limit') Right: IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'i') Operand: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i') Entering: {R3} Next (Regular) Block[B13] Leaving: {R1} .locals {R3} { CaptureIds: [5] Block[B6] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IInvocationOperation ( Function System.Nullable(Of System.Int32).GetValueOrDefault() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'i') Instance Receiver: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i') Arguments(0) Jump if False (Regular) to Block[B8] IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: '[step]') Next (Regular) Block[B7] Block[B7] - Block Predecessors: [B6] Statements (0) Jump if False (Regular) to Block[B13] IBinaryOperation (BinaryOperatorKind.LessThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'limit') Left: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i') Right: IInvocationOperation ( Function System.Nullable(Of System.Int32).GetValueOrDefault() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'limit') Instance Receiver: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'limit') Arguments(0) Leaving: {R3} {R1} Next (Regular) Block[B9] Leaving: {R3} Block[B8] - Block Predecessors: [B6] Statements (0) Jump if False (Regular) to Block[B13] IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'limit') Left: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i') Right: IInvocationOperation ( Function System.Nullable(Of System.Int32).GetValueOrDefault() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'limit') Instance Receiver: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'limit') Arguments(0) Leaving: {R3} {R1} Next (Regular) Block[B9] Leaving: {R3} } Block[B9] - Block Predecessors: [B7] [B8] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'result = i') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'result') Right: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'i') Next (Regular) Block[B10] Entering: {R4} .locals {R4} { CaptureIds: [6] Block[B10] - Block Predecessors: [B9] Statements (1) IFlowCaptureOperation: 6 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i') Jump if False (Regular) to Block[B12] IBinaryOperation (BinaryOperatorKind.Or) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '[step]') Left: IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: '[step]') Operand: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: '[step]') Right: IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'i') Operand: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i') Next (Regular) Block[B11] Block[B11] - Block Predecessors: [B10] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'i') Left: IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i') Right: IDefaultValueOperation (OperationKind.DefaultValue, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i') Next (Regular) Block[B5] Leaving: {R4} Block[B12] - Block Predecessors: [B10] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'i') Left: IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: '[step]') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (WideningNullable) Operand: IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32, IsImplicit) (Syntax: '[step]') Left: IInvocationOperation ( Function System.Nullable(Of System.Int32).GetValueOrDefault() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'i') Instance Receiver: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i') Arguments(0) Right: IInvocationOperation ( Function System.Nullable(Of System.Int32).GetValueOrDefault() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: '[step]') Instance Receiver: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: '[step]') Arguments(0) Next (Regular) Block[B5] Leaving: {R4} } } Block[B13] - Exit Predecessors: [B5] [B7] [B8] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForToFlow_10() Dim source = <![CDATA[ Imports System Public Class C Sub M(i As C, init As C, limit As C, [step] As C, result As C) 'BIND:"Sub M" For i = init To limit Step [step] result = i Next End Sub End Class]]>.Value Dim expectedDiagnostics = <![CDATA[ BC33038: Type 'C' must define operator '-' to be used in a 'For' statement. For i = init To limit Step [step] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC33038: Type 'C' must define operator '+' to be used in a 'For' statement. For i = init To limit Step [step] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC33038: Type 'C' must define operator '<=' to be used in a 'For' statement. For i = init To limit Step [step] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC33038: Type 'C' must define operator '>=' to be used in a 'For' statement. For i = init To limit Step [step] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [2] [3] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (5) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'i') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'init') Value: IParameterReferenceOperation: init (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'init') IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'limit') Value: IParameterReferenceOperation: limit (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'limit') IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: '[step]') Value: IParameterReferenceOperation: step (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: '[step]') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsInvalid, IsImplicit) (Syntax: 'init') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'init') Next (Regular) Block[B2] Leaving: {R2} } Block[B2] - Block Predecessors: [B1] [B3] Statements (0) Jump if False (Regular) to Block[B4] IInvalidOperation (OperationKind.Invalid, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'limit') Children(2): IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i') IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'limit') Leaving: {R1} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'result = i') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: C) (Syntax: 'result') Right: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C) (Syntax: 'i') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsInvalid, IsImplicit) (Syntax: 'i') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: C, IsInvalid, IsImplicit) (Syntax: '[step]') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: '[step]') Next (Regular) Block[B2] } Block[B4] - Exit Predecessors: [B2] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForToFlow_11() Dim source = <![CDATA[ Imports System Public Structure C Sub M(i As C?, init As C?, limit As C?, [step] As C?, result As C?) 'BIND:"Sub M" For i = init To limit Step [step] result = i Next End Sub End Structure]]>.Value Dim expectedDiagnostics = <![CDATA[ BC33038: Type 'C?' must define operator '-' to be used in a 'For' statement. For i = init To limit Step [step] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC33038: Type 'C?' must define operator '+' to be used in a 'For' statement. For i = init To limit Step [step] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC33038: Type 'C?' must define operator '<=' to be used in a 'For' statement. For i = init To limit Step [step] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC33038: Type 'C?' must define operator '>=' to be used in a 'For' statement. For i = init To limit Step [step] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [2] [3] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (5) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of C), IsInvalid) (Syntax: 'i') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'init') Value: IParameterReferenceOperation: init (OperationKind.ParameterReference, Type: System.Nullable(Of C), IsInvalid) (Syntax: 'init') IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'limit') Value: IParameterReferenceOperation: limit (OperationKind.ParameterReference, Type: System.Nullable(Of C), IsInvalid) (Syntax: 'limit') IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: '[step]') Value: IParameterReferenceOperation: step (OperationKind.ParameterReference, Type: System.Nullable(Of C), IsInvalid) (Syntax: '[step]') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsInvalid, IsImplicit) (Syntax: 'init') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsInvalid, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsInvalid, IsImplicit) (Syntax: 'init') Next (Regular) Block[B2] Leaving: {R2} } Block[B2] - Block Predecessors: [B1] [B5] [B6] Statements (0) Jump if False (Regular) to Block[B7] IInvalidOperation (OperationKind.Invalid, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'limit') Children(2): IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of C), IsInvalid, IsImplicit) (Syntax: 'i') IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsInvalid, IsImplicit) (Syntax: 'limit') Leaving: {R1} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'result = i') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Nullable(Of C)) (Syntax: 'result') Right: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of C)) (Syntax: 'i') Next (Regular) Block[B4] Entering: {R3} .locals {R3} { CaptureIds: [4] Block[B4] - Block Predecessors: [B3] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of C), IsInvalid, IsImplicit) (Syntax: 'i') Jump if False (Regular) to Block[B6] IBinaryOperation (BinaryOperatorKind.Or) (OperationKind.Binary, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: '[step]') Left: IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: '[step]') Operand: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsInvalid, IsImplicit) (Syntax: '[step]') Right: IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'i') Operand: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of C), IsInvalid, IsImplicit) (Syntax: 'i') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B4] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsInvalid, IsImplicit) (Syntax: 'i') Left: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsInvalid, IsImplicit) (Syntax: 'i') Right: IDefaultValueOperation (OperationKind.DefaultValue, Type: System.Nullable(Of C), IsInvalid, IsImplicit) (Syntax: 'i') Next (Regular) Block[B2] Leaving: {R3} Block[B6] - Block Predecessors: [B4] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsInvalid, IsImplicit) (Syntax: 'i') Left: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsInvalid, IsImplicit) (Syntax: 'i') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Nullable(Of C), IsInvalid, IsImplicit) (Syntax: '[step]') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (WideningNullable) Operand: IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: C, IsInvalid, IsImplicit) (Syntax: '[step]') Left: IInvocationOperation ( Function System.Nullable(Of C).GetValueOrDefault() As C) (OperationKind.Invocation, Type: C, IsInvalid, IsImplicit) (Syntax: 'i') Instance Receiver: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of C), IsInvalid, IsImplicit) (Syntax: 'i') Arguments(0) Right: IInvocationOperation ( Function System.Nullable(Of C).GetValueOrDefault() As C) (OperationKind.Invocation, Type: C, IsInvalid, IsImplicit) (Syntax: '[step]') Instance Receiver: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsInvalid, IsImplicit) (Syntax: '[step]') Arguments(0) Next (Regular) Block[B2] Leaving: {R3} } } Block[B7] - Exit Predecessors: [B2] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForToFlow_12() Dim source = <![CDATA[ Imports System Public Class C1 Sub M(i As C1, init As C2, limit As C3, [step] As C4, result As C1) 'BIND:"Sub M" For i = init To limit Step [step] result = i Next End Sub End Class Public Class C2 End Class Public Class C3 End Class Public Class C4 End Class ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30311: Value of type 'C2' cannot be converted to 'C1'. For i = init To limit Step [step] ~~~~ BC30311: Value of type 'C3' cannot be converted to 'C1'. For i = init To limit Step [step] ~~~~~ BC30311: Value of type 'C4' cannot be converted to 'C1'. For i = init To limit Step [step] ~~~~~~ ]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [2] [3] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (5) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C1) (Syntax: 'i') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'init') Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: C1, IsInvalid, IsImplicit) (Syntax: 'init') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (DelegateRelaxationLevelNone) Operand: IParameterReferenceOperation: init (OperationKind.ParameterReference, Type: C2, IsInvalid) (Syntax: 'init') IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'limit') Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: C1, IsInvalid, IsImplicit) (Syntax: 'limit') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (DelegateRelaxationLevelNone) Operand: IParameterReferenceOperation: limit (OperationKind.ParameterReference, Type: C3, IsInvalid) (Syntax: 'limit') IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: '[step]') Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: C1, IsInvalid, IsImplicit) (Syntax: '[step]') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (DelegateRelaxationLevelNone) Operand: IParameterReferenceOperation: step (OperationKind.ParameterReference, Type: C4, IsInvalid) (Syntax: '[step]') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsInvalid, IsImplicit) (Syntax: 'init') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C1, IsInvalid, IsImplicit) (Syntax: 'init') Next (Regular) Block[B2] Leaving: {R2} } Block[B2] - Block Predecessors: [B1] [B3] Statements (0) Jump if False (Regular) to Block[B4] IInvalidOperation (OperationKind.Invalid, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'limit') Children(2): IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C1, IsImplicit) (Syntax: 'i') IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: C1, IsInvalid, IsImplicit) (Syntax: 'limit') Leaving: {R1} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C1, IsImplicit) (Syntax: 'result = i') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: C1) (Syntax: 'result') Right: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C1) (Syntax: 'i') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'i') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C1, IsImplicit) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: C1, IsInvalid, IsImplicit) (Syntax: '[step]') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C1, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: C1, IsInvalid, IsImplicit) (Syntax: '[step]') Next (Regular) Block[B2] } Block[B4] - Exit Predecessors: [B2] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForToFlow_13() Dim source = <![CDATA[ Imports System Public Enum MyEnum As Integer MinusOne = -1 End Enum Public Class C Sub M(i As MyEnum?, init As MyEnum?, limit As MyEnum?, [step] As MyEnum?, result As MyEnum?) 'BIND:"Sub M" For i = init To limit Step [step] result = i Next End Sub End Class]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [2] [3] [4] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (4) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of MyEnum)) (Syntax: 'i') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init') Value: IParameterReferenceOperation: init (OperationKind.ParameterReference, Type: System.Nullable(Of MyEnum)) (Syntax: 'init') IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit') Value: IParameterReferenceOperation: limit (OperationKind.ParameterReference, Type: System.Nullable(Of MyEnum)) (Syntax: 'limit') IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '[step]') Value: IParameterReferenceOperation: step (OperationKind.ParameterReference, Type: System.Nullable(Of MyEnum)) (Syntax: '[step]') Jump if False (Regular) to Block[B3] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: '[step]') Operand: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of MyEnum), IsImplicit) (Syntax: '[step]') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '[step]') Value: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False, IsImplicit) (Syntax: '[step]') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '[step]') Value: IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '[step]') Left: IInvocationOperation ( Function System.Nullable(Of MyEnum).GetValueOrDefault() As MyEnum) (OperationKind.Invocation, Type: MyEnum, IsImplicit) (Syntax: '[step]') Instance Receiver: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of MyEnum), IsImplicit) (Syntax: '[step]') Arguments(0) Right: ILiteralOperation (OperationKind.Literal, Type: MyEnum, Constant: 0, IsImplicit) (Syntax: '[step]') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'init') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of MyEnum), IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of MyEnum), IsImplicit) (Syntax: 'init') Next (Regular) Block[B5] Leaving: {R2} } Block[B5] - Block Predecessors: [B4] [B11] [B12] Statements (0) Jump if False (Regular) to Block[B6] IBinaryOperation (BinaryOperatorKind.Or) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '[step]') Left: IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'limit') Operand: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of MyEnum), IsImplicit) (Syntax: 'limit') Right: IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'i') Operand: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of MyEnum), IsImplicit) (Syntax: 'i') Entering: {R3} Next (Regular) Block[B13] Leaving: {R1} .locals {R3} { CaptureIds: [5] Block[B6] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IInvocationOperation ( Function System.Nullable(Of MyEnum).GetValueOrDefault() As MyEnum) (OperationKind.Invocation, Type: MyEnum, IsImplicit) (Syntax: 'i') Instance Receiver: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of MyEnum), IsImplicit) (Syntax: 'i') Arguments(0) Jump if False (Regular) to Block[B8] IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: '[step]') Next (Regular) Block[B7] Block[B7] - Block Predecessors: [B6] Statements (0) Jump if False (Regular) to Block[B13] IBinaryOperation (BinaryOperatorKind.LessThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'limit') Left: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: MyEnum, IsImplicit) (Syntax: 'i') Right: IInvocationOperation ( Function System.Nullable(Of MyEnum).GetValueOrDefault() As MyEnum) (OperationKind.Invocation, Type: MyEnum, IsImplicit) (Syntax: 'limit') Instance Receiver: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of MyEnum), IsImplicit) (Syntax: 'limit') Arguments(0) Leaving: {R3} {R1} Next (Regular) Block[B9] Leaving: {R3} Block[B8] - Block Predecessors: [B6] Statements (0) Jump if False (Regular) to Block[B13] IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'limit') Left: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: MyEnum, IsImplicit) (Syntax: 'i') Right: IInvocationOperation ( Function System.Nullable(Of MyEnum).GetValueOrDefault() As MyEnum) (OperationKind.Invocation, Type: MyEnum, IsImplicit) (Syntax: 'limit') Instance Receiver: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of MyEnum), IsImplicit) (Syntax: 'limit') Arguments(0) Leaving: {R3} {R1} Next (Regular) Block[B9] Leaving: {R3} } Block[B9] - Block Predecessors: [B7] [B8] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Nullable(Of MyEnum), IsImplicit) (Syntax: 'result = i') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Nullable(Of MyEnum)) (Syntax: 'result') Right: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of MyEnum)) (Syntax: 'i') Next (Regular) Block[B10] Entering: {R4} .locals {R4} { CaptureIds: [6] Block[B10] - Block Predecessors: [B9] Statements (1) IFlowCaptureOperation: 6 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of MyEnum), IsImplicit) (Syntax: 'i') Jump if False (Regular) to Block[B12] IBinaryOperation (BinaryOperatorKind.Or) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '[step]') Left: IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: '[step]') Operand: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of MyEnum), IsImplicit) (Syntax: '[step]') Right: IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'i') Operand: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of MyEnum), IsImplicit) (Syntax: 'i') Next (Regular) Block[B11] Block[B11] - Block Predecessors: [B10] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'i') Left: IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of MyEnum), IsImplicit) (Syntax: 'i') Right: IDefaultValueOperation (OperationKind.DefaultValue, Type: System.Nullable(Of MyEnum), IsImplicit) (Syntax: 'i') Next (Regular) Block[B5] Leaving: {R4} Block[B12] - Block Predecessors: [B10] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'i') Left: IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of MyEnum), IsImplicit) (Syntax: 'i') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Nullable(Of MyEnum), IsImplicit) (Syntax: '[step]') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (WideningNullable) Operand: IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: MyEnum, IsImplicit) (Syntax: '[step]') Left: IInvocationOperation ( Function System.Nullable(Of MyEnum).GetValueOrDefault() As MyEnum) (OperationKind.Invocation, Type: MyEnum, IsImplicit) (Syntax: 'i') Instance Receiver: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of MyEnum), IsImplicit) (Syntax: 'i') Arguments(0) Right: IInvocationOperation ( Function System.Nullable(Of MyEnum).GetValueOrDefault() As MyEnum) (OperationKind.Invocation, Type: MyEnum, IsImplicit) (Syntax: '[step]') Instance Receiver: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of MyEnum), IsImplicit) (Syntax: '[step]') Arguments(0) Next (Regular) Block[B5] Leaving: {R4} } } Block[B13] - Exit Predecessors: [B5] [B7] [B8] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact> Public Sub ForToFlow_14() Dim source = <![CDATA[ Imports System Public Class C Sub M(c1 As C, c2 As C, bInit As Boolean, init1 As Integer, init2 As Integer, bLimit As Boolean, limit1 As Integer, limit2 As Integer, result As Boolean) 'BIND:"Sub M" For If(c1, c2).i = If(bInit, init1, init2) To If(bLimit, limit1, limit2) Step 2 result = true Next End Sub Public i As Integer End Class]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} {R3} {R4} .locals {R1} { CaptureIds: [4] [5] .locals {R2} { CaptureIds: [2] [3] .locals {R3} { CaptureIds: [1] .locals {R4} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C) (Syntax: 'c1') Jump if True (Regular) to Block[B3] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Leaving: {R4} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B4] Leaving: {R4} } Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C) (Syntax: 'c2') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i') Value: IFieldReferenceOperation: C.i As System.Int32 (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'If(c1, c2).i') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)') Next (Regular) Block[B5] Leaving: {R3} } Block[B5] - Block Predecessors: [B4] Statements (0) Jump if False (Regular) to Block[B7] IParameterReferenceOperation: bInit (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bInit') Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init1') Value: IParameterReferenceOperation: init1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'init1') Next (Regular) Block[B8] Block[B7] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init2') Value: IParameterReferenceOperation: init2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'init2') Next (Regular) Block[B8] Block[B8] - Block Predecessors: [B6] [B7] Statements (0) Jump if False (Regular) to Block[B10] IParameterReferenceOperation: bLimit (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bLimit') Next (Regular) Block[B9] Block[B9] - Block Predecessors: [B8] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit1') Value: IParameterReferenceOperation: limit1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'limit1') Next (Regular) Block[B11] Block[B10] - Block Predecessors: [B8] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit2') Value: IParameterReferenceOperation: limit2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'limit2') Next (Regular) Block[B11] Block[B11] - Block Predecessors: [B9] [B10] Statements (2) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '2') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'If(bInit, init1, init2)') Left: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(c1, c2).i') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(bInit, init1, init2)') Next (Regular) Block[B12] Leaving: {R2} Entering: {R5} {R6} } .locals {R5} { CaptureIds: [7] .locals {R6} { CaptureIds: [6] Block[B12] - Block Predecessors: [B11] [B24] Statements (1) IFlowCaptureOperation: 6 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1') Jump if True (Regular) to Block[B14] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Leaving: {R6} Next (Regular) Block[B13] Block[B13] - Block Predecessors: [B12] Statements (1) IFlowCaptureOperation: 7 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B15] Leaving: {R6} } Block[B14] - Block Predecessors: [B12] Statements (1) IFlowCaptureOperation: 7 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2') Next (Regular) Block[B15] Block[B15] - Block Predecessors: [B13] [B14] Statements (0) Jump if False (Regular) to Block[B25] IBinaryOperation (BinaryOperatorKind.LessThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)') Left: IFieldReferenceOperation: C.i As System.Int32 (OperationKind.FieldReference, Type: System.Int32, IsImplicit) (Syntax: 'If(c1, c2).i') Instance Receiver: IFlowCaptureReferenceOperation: 7 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)') Right: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)') Leaving: {R5} {R1} Next (Regular) Block[B16] Leaving: {R5} } Block[B16] - Block Predecessors: [B15] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = true') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsImplicit) (Syntax: 'result = true') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B17] Entering: {R7} {R8} {R9} .locals {R7} { CaptureIds: [10] [12] .locals {R8} { CaptureIds: [9] .locals {R9} { CaptureIds: [8] Block[B17] - Block Predecessors: [B16] Statements (1) IFlowCaptureOperation: 8 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1') Jump if True (Regular) to Block[B19] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 8 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Leaving: {R9} Next (Regular) Block[B18] Block[B18] - Block Predecessors: [B17] Statements (1) IFlowCaptureOperation: 9 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 8 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B20] Leaving: {R9} } Block[B19] - Block Predecessors: [B17] Statements (1) IFlowCaptureOperation: 9 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2') Next (Regular) Block[B20] Block[B20] - Block Predecessors: [B18] [B19] Statements (1) IFlowCaptureOperation: 10 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i') Value: IFieldReferenceOperation: C.i As System.Int32 (OperationKind.FieldReference, Type: System.Int32, IsImplicit) (Syntax: 'If(c1, c2).i') Instance Receiver: IFlowCaptureReferenceOperation: 9 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)') Next (Regular) Block[B21] Leaving: {R8} Entering: {R10} } .locals {R10} { CaptureIds: [11] Block[B21] - Block Predecessors: [B20] Statements (1) IFlowCaptureOperation: 11 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1') Jump if True (Regular) to Block[B23] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 11 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Leaving: {R10} Next (Regular) Block[B22] Block[B22] - Block Predecessors: [B21] Statements (1) IFlowCaptureOperation: 12 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 11 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B24] Leaving: {R10} } Block[B23] - Block Predecessors: [B21] Statements (1) IFlowCaptureOperation: 12 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2') Next (Regular) Block[B24] Block[B24] - Block Predecessors: [B22] [B23] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i') Left: IFlowCaptureReferenceOperation: 10 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(c1, c2).i') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32, IsImplicit) (Syntax: '2') Left: IFieldReferenceOperation: C.i As System.Int32 (OperationKind.FieldReference, Type: System.Int32, IsImplicit) (Syntax: 'If(c1, c2).i') Instance Receiver: IFlowCaptureReferenceOperation: 12 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)') Right: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: '2') Next (Regular) Block[B12] Leaving: {R7} Entering: {R5} {R6} } } Block[B25] - Exit Predecessors: [B15] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics, TestOptions.ReleaseDll.WithOverflowChecks(False)) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact> Public Sub ForToFlow_15() Dim source = <![CDATA[ Imports System Public Class C Sub M(c1 As C, c2 As C, bInit As Boolean, init1 As Integer, init2 As Integer, bLimit As Boolean, limit1 As Integer, limit2 As Integer, result As Boolean) 'BIND:"Sub M" For If(c1, c2).i = If(bInit, init1, init2) To If(bLimit, limit1, limit2) Step -2 result = true Next End Sub Public i As Integer End Class]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} {R3} {R4} .locals {R1} { CaptureIds: [4] [5] .locals {R2} { CaptureIds: [2] [3] .locals {R3} { CaptureIds: [1] .locals {R4} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C) (Syntax: 'c1') Jump if True (Regular) to Block[B3] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Leaving: {R4} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B4] Leaving: {R4} } Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C) (Syntax: 'c2') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i') Value: IFieldReferenceOperation: C.i As System.Int32 (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'If(c1, c2).i') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)') Next (Regular) Block[B5] Leaving: {R3} } Block[B5] - Block Predecessors: [B4] Statements (0) Jump if False (Regular) to Block[B7] IParameterReferenceOperation: bInit (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bInit') Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init1') Value: IParameterReferenceOperation: init1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'init1') Next (Regular) Block[B8] Block[B7] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init2') Value: IParameterReferenceOperation: init2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'init2') Next (Regular) Block[B8] Block[B8] - Block Predecessors: [B6] [B7] Statements (0) Jump if False (Regular) to Block[B10] IParameterReferenceOperation: bLimit (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bLimit') Next (Regular) Block[B9] Block[B9] - Block Predecessors: [B8] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit1') Value: IParameterReferenceOperation: limit1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'limit1') Next (Regular) Block[B11] Block[B10] - Block Predecessors: [B8] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit2') Value: IParameterReferenceOperation: limit2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'limit2') Next (Regular) Block[B11] Block[B11] - Block Predecessors: [B9] [B10] Statements (2) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '-2') Value: IUnaryOperation (UnaryOperatorKind.Minus, Checked) (OperationKind.Unary, Type: System.Int32, Constant: -2) (Syntax: '-2') Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'If(bInit, init1, init2)') Left: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(c1, c2).i') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(bInit, init1, init2)') Next (Regular) Block[B12] Leaving: {R2} Entering: {R5} {R6} } .locals {R5} { CaptureIds: [7] .locals {R6} { CaptureIds: [6] Block[B12] - Block Predecessors: [B11] [B24] Statements (1) IFlowCaptureOperation: 6 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1') Jump if True (Regular) to Block[B14] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Leaving: {R6} Next (Regular) Block[B13] Block[B13] - Block Predecessors: [B12] Statements (1) IFlowCaptureOperation: 7 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B15] Leaving: {R6} } Block[B14] - Block Predecessors: [B12] Statements (1) IFlowCaptureOperation: 7 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2') Next (Regular) Block[B15] Block[B15] - Block Predecessors: [B13] [B14] Statements (0) Jump if False (Regular) to Block[B25] IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)') Left: IFieldReferenceOperation: C.i As System.Int32 (OperationKind.FieldReference, Type: System.Int32, IsImplicit) (Syntax: 'If(c1, c2).i') Instance Receiver: IFlowCaptureReferenceOperation: 7 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)') Right: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)') Leaving: {R5} {R1} Next (Regular) Block[B16] Leaving: {R5} } Block[B16] - Block Predecessors: [B15] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = true') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsImplicit) (Syntax: 'result = true') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B17] Entering: {R7} {R8} {R9} .locals {R7} { CaptureIds: [10] [12] .locals {R8} { CaptureIds: [9] .locals {R9} { CaptureIds: [8] Block[B17] - Block Predecessors: [B16] Statements (1) IFlowCaptureOperation: 8 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1') Jump if True (Regular) to Block[B19] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 8 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Leaving: {R9} Next (Regular) Block[B18] Block[B18] - Block Predecessors: [B17] Statements (1) IFlowCaptureOperation: 9 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 8 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B20] Leaving: {R9} } Block[B19] - Block Predecessors: [B17] Statements (1) IFlowCaptureOperation: 9 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2') Next (Regular) Block[B20] Block[B20] - Block Predecessors: [B18] [B19] Statements (1) IFlowCaptureOperation: 10 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i') Value: IFieldReferenceOperation: C.i As System.Int32 (OperationKind.FieldReference, Type: System.Int32, IsImplicit) (Syntax: 'If(c1, c2).i') Instance Receiver: IFlowCaptureReferenceOperation: 9 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)') Next (Regular) Block[B21] Leaving: {R8} Entering: {R10} } .locals {R10} { CaptureIds: [11] Block[B21] - Block Predecessors: [B20] Statements (1) IFlowCaptureOperation: 11 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1') Jump if True (Regular) to Block[B23] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 11 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Leaving: {R10} Next (Regular) Block[B22] Block[B22] - Block Predecessors: [B21] Statements (1) IFlowCaptureOperation: 12 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 11 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B24] Leaving: {R10} } Block[B23] - Block Predecessors: [B21] Statements (1) IFlowCaptureOperation: 12 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2') Next (Regular) Block[B24] Block[B24] - Block Predecessors: [B22] [B23] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i') Left: IFlowCaptureReferenceOperation: 10 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(c1, c2).i') Right: IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32, IsImplicit) (Syntax: '-2') Left: IFieldReferenceOperation: C.i As System.Int32 (OperationKind.FieldReference, Type: System.Int32, IsImplicit) (Syntax: 'If(c1, c2).i') Instance Receiver: IFlowCaptureReferenceOperation: 12 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)') Right: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: -2, IsImplicit) (Syntax: '-2') Next (Regular) Block[B12] Leaving: {R7} Entering: {R5} {R6} } } Block[B25] - Exit Predecessors: [B15] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact> Public Sub ForToFlow_16() Dim source = <![CDATA[ Imports System Public Class C Sub M(c1 As C, c2 As C, bInit As Boolean, init1 As Integer, init2 As Integer, bLimit As Boolean, limit1 As Integer, limit2 As Integer, bStep As Boolean, step1 As Integer, step2 As Integer, result As Boolean) 'BIND:"Sub M" For If(c1, c2).i = If(bInit, init1, init2) To If(bLimit, limit1, limit2) Step If(bStep, step1, step2) result = true Next End Sub Public i As Integer End Class]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} {R3} {R4} .locals {R1} { CaptureIds: [4] [5] .locals {R2} { CaptureIds: [2] [3] .locals {R3} { CaptureIds: [1] .locals {R4} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C) (Syntax: 'c1') Jump if True (Regular) to Block[B3] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Leaving: {R4} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B4] Leaving: {R4} } Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C) (Syntax: 'c2') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i') Value: IFieldReferenceOperation: C.i As System.Int32 (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'If(c1, c2).i') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)') Next (Regular) Block[B5] Leaving: {R3} } Block[B5] - Block Predecessors: [B4] Statements (0) Jump if False (Regular) to Block[B7] IParameterReferenceOperation: bInit (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bInit') Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init1') Value: IParameterReferenceOperation: init1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'init1') Next (Regular) Block[B8] Block[B7] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init2') Value: IParameterReferenceOperation: init2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'init2') Next (Regular) Block[B8] Block[B8] - Block Predecessors: [B6] [B7] Statements (0) Jump if False (Regular) to Block[B10] IParameterReferenceOperation: bLimit (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bLimit') Next (Regular) Block[B9] Block[B9] - Block Predecessors: [B8] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit1') Value: IParameterReferenceOperation: limit1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'limit1') Next (Regular) Block[B11] Block[B10] - Block Predecessors: [B8] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit2') Value: IParameterReferenceOperation: limit2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'limit2') Next (Regular) Block[B11] Block[B11] - Block Predecessors: [B9] [B10] Statements (0) Jump if False (Regular) to Block[B13] IParameterReferenceOperation: bStep (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bStep') Next (Regular) Block[B12] Block[B12] - Block Predecessors: [B11] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'step1') Value: IParameterReferenceOperation: step1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'step1') Next (Regular) Block[B14] Block[B13] - Block Predecessors: [B11] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'step2') Value: IParameterReferenceOperation: step2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'step2') Next (Regular) Block[B14] Block[B14] - Block Predecessors: [B12] [B13] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'If(bInit, init1, init2)') Left: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(c1, c2).i') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(bInit, init1, init2)') Next (Regular) Block[B15] Leaving: {R2} Entering: {R5} {R6} } .locals {R5} { CaptureIds: [7] .locals {R6} { CaptureIds: [6] Block[B15] - Block Predecessors: [B14] [B27] Statements (1) IFlowCaptureOperation: 6 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1') Jump if True (Regular) to Block[B17] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Leaving: {R6} Next (Regular) Block[B16] Block[B16] - Block Predecessors: [B15] Statements (1) IFlowCaptureOperation: 7 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B18] Leaving: {R6} } Block[B17] - Block Predecessors: [B15] Statements (1) IFlowCaptureOperation: 7 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2') Next (Regular) Block[B18] Block[B18] - Block Predecessors: [B16] [B17] Statements (0) Jump if False (Regular) to Block[B28] IBinaryOperation (BinaryOperatorKind.LessThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)') Left: IBinaryOperation (BinaryOperatorKind.ExclusiveOr) (OperationKind.Binary, Type: System.Int32, IsImplicit) (Syntax: 'If(c1, c2).i') Left: IBinaryOperation (BinaryOperatorKind.RightShift) (OperationKind.Binary, Type: System.Int32, IsImplicit) (Syntax: 'If(c1, c2).i') Left: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(bStep, step1, step2)') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 31, IsImplicit) (Syntax: 'If(c1, c2).i') Right: IFieldReferenceOperation: C.i As System.Int32 (OperationKind.FieldReference, Type: System.Int32, IsImplicit) (Syntax: 'If(c1, c2).i') Instance Receiver: IFlowCaptureReferenceOperation: 7 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)') Right: IBinaryOperation (BinaryOperatorKind.ExclusiveOr) (OperationKind.Binary, Type: System.Int32, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)') Left: IBinaryOperation (BinaryOperatorKind.RightShift) (OperationKind.Binary, Type: System.Int32, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)') Left: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(bStep, step1, step2)') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 31, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)') Right: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)') Leaving: {R5} {R1} Next (Regular) Block[B19] Leaving: {R5} } Block[B19] - Block Predecessors: [B18] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = true') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsImplicit) (Syntax: 'result = true') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B20] Entering: {R7} {R8} {R9} .locals {R7} { CaptureIds: [10] [12] .locals {R8} { CaptureIds: [9] .locals {R9} { CaptureIds: [8] Block[B20] - Block Predecessors: [B19] Statements (1) IFlowCaptureOperation: 8 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1') Jump if True (Regular) to Block[B22] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 8 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Leaving: {R9} Next (Regular) Block[B21] Block[B21] - Block Predecessors: [B20] Statements (1) IFlowCaptureOperation: 9 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 8 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B23] Leaving: {R9} } Block[B22] - Block Predecessors: [B20] Statements (1) IFlowCaptureOperation: 9 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2') Next (Regular) Block[B23] Block[B23] - Block Predecessors: [B21] [B22] Statements (1) IFlowCaptureOperation: 10 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i') Value: IFieldReferenceOperation: C.i As System.Int32 (OperationKind.FieldReference, Type: System.Int32, IsImplicit) (Syntax: 'If(c1, c2).i') Instance Receiver: IFlowCaptureReferenceOperation: 9 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)') Next (Regular) Block[B24] Leaving: {R8} Entering: {R10} } .locals {R10} { CaptureIds: [11] Block[B24] - Block Predecessors: [B23] Statements (1) IFlowCaptureOperation: 11 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1') Jump if True (Regular) to Block[B26] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 11 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Leaving: {R10} Next (Regular) Block[B25] Block[B25] - Block Predecessors: [B24] Statements (1) IFlowCaptureOperation: 12 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 11 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B27] Leaving: {R10} } Block[B26] - Block Predecessors: [B24] Statements (1) IFlowCaptureOperation: 12 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2') Next (Regular) Block[B27] Block[B27] - Block Predecessors: [B25] [B26] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i') Left: IFlowCaptureReferenceOperation: 10 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(c1, c2).i') Right: IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32, IsImplicit) (Syntax: 'If(bStep, step1, step2)') Left: IFieldReferenceOperation: C.i As System.Int32 (OperationKind.FieldReference, Type: System.Int32, IsImplicit) (Syntax: 'If(c1, c2).i') Instance Receiver: IFlowCaptureReferenceOperation: 12 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)') Right: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(bStep, step1, step2)') Next (Regular) Block[B15] Leaving: {R7} Entering: {R5} {R6} } } Block[B28] - Exit Predecessors: [B18] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact> Public Sub ForToFlow_17() Dim source = <![CDATA[ Imports System Public Class C Sub M(c1 As C, c2 As C, bInit As Boolean, init1 As Double, init2 As Double, bLimit As Boolean, limit1 As Double, limit2 As Double, bStep As Boolean, step1 As Double, step2 As Double, result As Boolean) 'BIND:"Sub M" For If(c1, c2).i = If(bInit, init1, init2) To If(bLimit, limit1, limit2) Step If(bStep, step1, step2) result = true Next End Sub Public i As Double End Class]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} {R3} {R4} .locals {R1} { CaptureIds: [4] [5] [6] .locals {R2} { CaptureIds: [2] [3] .locals {R3} { CaptureIds: [1] .locals {R4} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C) (Syntax: 'c1') Jump if True (Regular) to Block[B3] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Leaving: {R4} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B4] Leaving: {R4} } Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C) (Syntax: 'c2') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i') Value: IFieldReferenceOperation: C.i As System.Double (OperationKind.FieldReference, Type: System.Double) (Syntax: 'If(c1, c2).i') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)') Next (Regular) Block[B5] Leaving: {R3} } Block[B5] - Block Predecessors: [B4] Statements (0) Jump if False (Regular) to Block[B7] IParameterReferenceOperation: bInit (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bInit') Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init1') Value: IParameterReferenceOperation: init1 (OperationKind.ParameterReference, Type: System.Double) (Syntax: 'init1') Next (Regular) Block[B8] Block[B7] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init2') Value: IParameterReferenceOperation: init2 (OperationKind.ParameterReference, Type: System.Double) (Syntax: 'init2') Next (Regular) Block[B8] Block[B8] - Block Predecessors: [B6] [B7] Statements (0) Jump if False (Regular) to Block[B10] IParameterReferenceOperation: bLimit (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bLimit') Next (Regular) Block[B9] Block[B9] - Block Predecessors: [B8] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit1') Value: IParameterReferenceOperation: limit1 (OperationKind.ParameterReference, Type: System.Double) (Syntax: 'limit1') Next (Regular) Block[B11] Block[B10] - Block Predecessors: [B8] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit2') Value: IParameterReferenceOperation: limit2 (OperationKind.ParameterReference, Type: System.Double) (Syntax: 'limit2') Next (Regular) Block[B11] Block[B11] - Block Predecessors: [B9] [B10] Statements (0) Jump if False (Regular) to Block[B13] IParameterReferenceOperation: bStep (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bStep') Next (Regular) Block[B12] Block[B12] - Block Predecessors: [B11] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'step1') Value: IParameterReferenceOperation: step1 (OperationKind.ParameterReference, Type: System.Double) (Syntax: 'step1') Next (Regular) Block[B14] Block[B13] - Block Predecessors: [B11] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'step2') Value: IParameterReferenceOperation: step2 (OperationKind.ParameterReference, Type: System.Double) (Syntax: 'step2') Next (Regular) Block[B14] Block[B14] - Block Predecessors: [B12] [B13] Statements (2) IFlowCaptureOperation: 6 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(bStep, step1, step2)') Value: IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'If(bStep, step1, step2)') Left: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Double, IsImplicit) (Syntax: 'If(bStep, step1, step2)') Right: ILiteralOperation (OperationKind.Literal, Type: System.Double, Constant: 0, IsImplicit) (Syntax: 'If(bStep, step1, step2)') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'If(bInit, init1, init2)') Left: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Double, IsImplicit) (Syntax: 'If(c1, c2).i') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Double, IsImplicit) (Syntax: 'If(bInit, init1, init2)') Next (Regular) Block[B15] Leaving: {R2} Entering: {R5} {R6} {R7} } .locals {R5} { CaptureIds: [9] .locals {R6} { CaptureIds: [8] .locals {R7} { CaptureIds: [7] Block[B15] - Block Predecessors: [B14] [B30] Statements (1) IFlowCaptureOperation: 7 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1') Jump if True (Regular) to Block[B17] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 7 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Leaving: {R7} Next (Regular) Block[B16] Block[B16] - Block Predecessors: [B15] Statements (1) IFlowCaptureOperation: 8 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 7 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B18] Leaving: {R7} } Block[B17] - Block Predecessors: [B15] Statements (1) IFlowCaptureOperation: 8 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2') Next (Regular) Block[B18] Block[B18] - Block Predecessors: [B16] [B17] Statements (1) IFlowCaptureOperation: 9 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i') Value: IFieldReferenceOperation: C.i As System.Double (OperationKind.FieldReference, Type: System.Double, IsImplicit) (Syntax: 'If(c1, c2).i') Instance Receiver: IFlowCaptureReferenceOperation: 8 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)') Next (Regular) Block[B19] Leaving: {R6} } Block[B19] - Block Predecessors: [B18] Statements (0) Jump if False (Regular) to Block[B21] IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: 'If(bStep, step1, step2)') Next (Regular) Block[B20] Block[B20] - Block Predecessors: [B19] Statements (0) Jump if False (Regular) to Block[B31] IBinaryOperation (BinaryOperatorKind.LessThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)') Left: IFlowCaptureReferenceOperation: 9 (OperationKind.FlowCaptureReference, Type: System.Double, IsImplicit) (Syntax: 'If(c1, c2).i') Right: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Double, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)') Leaving: {R5} {R1} Next (Regular) Block[B22] Leaving: {R5} Block[B21] - Block Predecessors: [B19] Statements (0) Jump if False (Regular) to Block[B31] IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)') Left: IFlowCaptureReferenceOperation: 9 (OperationKind.FlowCaptureReference, Type: System.Double, IsImplicit) (Syntax: 'If(c1, c2).i') Right: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Double, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)') Leaving: {R5} {R1} Next (Regular) Block[B22] Leaving: {R5} } Block[B22] - Block Predecessors: [B20] [B21] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = true') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsImplicit) (Syntax: 'result = true') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B23] Entering: {R8} {R9} {R10} .locals {R8} { CaptureIds: [12] [14] .locals {R9} { CaptureIds: [11] .locals {R10} { CaptureIds: [10] Block[B23] - Block Predecessors: [B22] Statements (1) IFlowCaptureOperation: 10 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1') Jump if True (Regular) to Block[B25] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 10 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Leaving: {R10} Next (Regular) Block[B24] Block[B24] - Block Predecessors: [B23] Statements (1) IFlowCaptureOperation: 11 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 10 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B26] Leaving: {R10} } Block[B25] - Block Predecessors: [B23] Statements (1) IFlowCaptureOperation: 11 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2') Next (Regular) Block[B26] Block[B26] - Block Predecessors: [B24] [B25] Statements (1) IFlowCaptureOperation: 12 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i') Value: IFieldReferenceOperation: C.i As System.Double (OperationKind.FieldReference, Type: System.Double, IsImplicit) (Syntax: 'If(c1, c2).i') Instance Receiver: IFlowCaptureReferenceOperation: 11 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)') Next (Regular) Block[B27] Leaving: {R9} Entering: {R11} } .locals {R11} { CaptureIds: [13] Block[B27] - Block Predecessors: [B26] Statements (1) IFlowCaptureOperation: 13 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1') Jump if True (Regular) to Block[B29] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 13 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Leaving: {R11} Next (Regular) Block[B28] Block[B28] - Block Predecessors: [B27] Statements (1) IFlowCaptureOperation: 14 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 13 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B30] Leaving: {R11} } Block[B29] - Block Predecessors: [B27] Statements (1) IFlowCaptureOperation: 14 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2') Next (Regular) Block[B30] Block[B30] - Block Predecessors: [B28] [B29] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i') Left: IFlowCaptureReferenceOperation: 12 (OperationKind.FlowCaptureReference, Type: System.Double, IsImplicit) (Syntax: 'If(c1, c2).i') Right: IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Double, IsImplicit) (Syntax: 'If(bStep, step1, step2)') Left: IFieldReferenceOperation: C.i As System.Double (OperationKind.FieldReference, Type: System.Double, IsImplicit) (Syntax: 'If(c1, c2).i') Instance Receiver: IFlowCaptureReferenceOperation: 14 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)') Right: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Double, IsImplicit) (Syntax: 'If(bStep, step1, step2)') Next (Regular) Block[B15] Leaving: {R8} Entering: {R5} {R6} {R7} } } Block[B31] - Exit Predecessors: [B20] [B21] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact> Public Sub ForToFlow_18() Dim source = <![CDATA[ Imports System Public Class C Sub M(c1 As C, c2 As C, bInit As Boolean, init1 As Double?, init2 As Double?, bLimit As Boolean, limit1 As Double?, limit2 As Double?, bStep As Boolean, step1 As Double?, step2 As Double?, result As Boolean) 'BIND:"Sub M" For If(c1, c2).i = If(bInit, init1, init2) To If(bLimit, limit1, limit2) Step If(bStep, step1, step2) result = true Next End Sub Public i As Double? End Class]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} {R3} {R4} .locals {R1} { CaptureIds: [4] [5] [6] .locals {R2} { CaptureIds: [2] [3] .locals {R3} { CaptureIds: [1] .locals {R4} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C) (Syntax: 'c1') Jump if True (Regular) to Block[B3] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Leaving: {R4} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B4] Leaving: {R4} } Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C) (Syntax: 'c2') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i') Value: IFieldReferenceOperation: C.i As System.Nullable(Of System.Double) (OperationKind.FieldReference, Type: System.Nullable(Of System.Double)) (Syntax: 'If(c1, c2).i') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)') Next (Regular) Block[B5] Leaving: {R3} } Block[B5] - Block Predecessors: [B4] Statements (0) Jump if False (Regular) to Block[B7] IParameterReferenceOperation: bInit (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bInit') Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init1') Value: IParameterReferenceOperation: init1 (OperationKind.ParameterReference, Type: System.Nullable(Of System.Double)) (Syntax: 'init1') Next (Regular) Block[B8] Block[B7] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init2') Value: IParameterReferenceOperation: init2 (OperationKind.ParameterReference, Type: System.Nullable(Of System.Double)) (Syntax: 'init2') Next (Regular) Block[B8] Block[B8] - Block Predecessors: [B6] [B7] Statements (0) Jump if False (Regular) to Block[B10] IParameterReferenceOperation: bLimit (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bLimit') Next (Regular) Block[B9] Block[B9] - Block Predecessors: [B8] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit1') Value: IParameterReferenceOperation: limit1 (OperationKind.ParameterReference, Type: System.Nullable(Of System.Double)) (Syntax: 'limit1') Next (Regular) Block[B11] Block[B10] - Block Predecessors: [B8] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit2') Value: IParameterReferenceOperation: limit2 (OperationKind.ParameterReference, Type: System.Nullable(Of System.Double)) (Syntax: 'limit2') Next (Regular) Block[B11] Block[B11] - Block Predecessors: [B9] [B10] Statements (0) Jump if False (Regular) to Block[B13] IParameterReferenceOperation: bStep (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bStep') Next (Regular) Block[B12] Block[B12] - Block Predecessors: [B11] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'step1') Value: IParameterReferenceOperation: step1 (OperationKind.ParameterReference, Type: System.Nullable(Of System.Double)) (Syntax: 'step1') Next (Regular) Block[B14] Block[B13] - Block Predecessors: [B11] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'step2') Value: IParameterReferenceOperation: step2 (OperationKind.ParameterReference, Type: System.Nullable(Of System.Double)) (Syntax: 'step2') Next (Regular) Block[B14] Block[B14] - Block Predecessors: [B12] [B13] Statements (0) Jump if False (Regular) to Block[B16] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'If(bStep, step1, step2)') Operand: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Double), IsImplicit) (Syntax: 'If(bStep, step1, step2)') Next (Regular) Block[B15] Block[B15] - Block Predecessors: [B14] Statements (1) IFlowCaptureOperation: 6 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(bStep, step1, step2)') Value: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False, IsImplicit) (Syntax: 'If(bStep, step1, step2)') Next (Regular) Block[B17] Block[B16] - Block Predecessors: [B14] Statements (1) IFlowCaptureOperation: 6 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(bStep, step1, step2)') Value: IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'If(bStep, step1, step2)') Left: IInvocationOperation ( Function System.Nullable(Of System.Double).GetValueOrDefault() As System.Double) (OperationKind.Invocation, Type: System.Double, IsImplicit) (Syntax: 'If(bStep, step1, step2)') Instance Receiver: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Double), IsImplicit) (Syntax: 'If(bStep, step1, step2)') Arguments(0) Right: ILiteralOperation (OperationKind.Literal, Type: System.Double, Constant: 0, IsImplicit) (Syntax: 'If(bStep, step1, step2)') Next (Regular) Block[B17] Block[B17] - Block Predecessors: [B15] [B16] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'If(bInit, init1, init2)') Left: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Double), IsImplicit) (Syntax: 'If(c1, c2).i') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Double), IsImplicit) (Syntax: 'If(bInit, init1, init2)') Next (Regular) Block[B18] Leaving: {R2} Entering: {R5} {R6} } .locals {R5} { CaptureIds: [8] .locals {R6} { CaptureIds: [7] Block[B18] - Block Predecessors: [B17] [B38] [B42] Statements (1) IFlowCaptureOperation: 7 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1') Jump if True (Regular) to Block[B20] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 7 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Leaving: {R6} Next (Regular) Block[B19] Block[B19] - Block Predecessors: [B18] Statements (1) IFlowCaptureOperation: 8 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 7 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B21] Leaving: {R6} } Block[B20] - Block Predecessors: [B18] Statements (1) IFlowCaptureOperation: 8 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2') Next (Regular) Block[B21] Block[B21] - Block Predecessors: [B19] [B20] Statements (0) Jump if False (Regular) to Block[B22] IBinaryOperation (BinaryOperatorKind.Or) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'If(bStep, step1, step2)') Left: IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)') Operand: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Double), IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)') Right: IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'If(c1, c2).i') Operand: IFieldReferenceOperation: C.i As System.Nullable(Of System.Double) (OperationKind.FieldReference, Type: System.Nullable(Of System.Double), IsImplicit) (Syntax: 'If(c1, c2).i') Instance Receiver: IFlowCaptureReferenceOperation: 8 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)') Leaving: {R5} Entering: {R7} {R8} {R9} Next (Regular) Block[B43] Leaving: {R5} {R1} } .locals {R7} { CaptureIds: [11] .locals {R8} { CaptureIds: [10] .locals {R9} { CaptureIds: [9] Block[B22] - Block Predecessors: [B21] Statements (1) IFlowCaptureOperation: 9 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1') Jump if True (Regular) to Block[B24] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 9 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Leaving: {R9} Next (Regular) Block[B23] Block[B23] - Block Predecessors: [B22] Statements (1) IFlowCaptureOperation: 10 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 9 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B25] Leaving: {R9} } Block[B24] - Block Predecessors: [B22] Statements (1) IFlowCaptureOperation: 10 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2') Next (Regular) Block[B25] Block[B25] - Block Predecessors: [B23] [B24] Statements (1) IFlowCaptureOperation: 11 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i') Value: IInvocationOperation ( Function System.Nullable(Of System.Double).GetValueOrDefault() As System.Double) (OperationKind.Invocation, Type: System.Double, IsImplicit) (Syntax: 'If(c1, c2).i') Instance Receiver: IFieldReferenceOperation: C.i As System.Nullable(Of System.Double) (OperationKind.FieldReference, Type: System.Nullable(Of System.Double), IsImplicit) (Syntax: 'If(c1, c2).i') Instance Receiver: IFlowCaptureReferenceOperation: 10 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)') Arguments(0) Next (Regular) Block[B26] Leaving: {R8} } Block[B26] - Block Predecessors: [B25] Statements (0) Jump if False (Regular) to Block[B28] IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: 'If(bStep, step1, step2)') Next (Regular) Block[B27] Block[B27] - Block Predecessors: [B26] Statements (0) Jump if False (Regular) to Block[B43] IBinaryOperation (BinaryOperatorKind.LessThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)') Left: IFlowCaptureReferenceOperation: 11 (OperationKind.FlowCaptureReference, Type: System.Double, IsImplicit) (Syntax: 'If(c1, c2).i') Right: IInvocationOperation ( Function System.Nullable(Of System.Double).GetValueOrDefault() As System.Double) (OperationKind.Invocation, Type: System.Double, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)') Instance Receiver: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Double), IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)') Arguments(0) Leaving: {R7} {R1} Next (Regular) Block[B29] Leaving: {R7} Block[B28] - Block Predecessors: [B26] Statements (0) Jump if False (Regular) to Block[B43] IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)') Left: IFlowCaptureReferenceOperation: 11 (OperationKind.FlowCaptureReference, Type: System.Double, IsImplicit) (Syntax: 'If(c1, c2).i') Right: IInvocationOperation ( Function System.Nullable(Of System.Double).GetValueOrDefault() As System.Double) (OperationKind.Invocation, Type: System.Double, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)') Instance Receiver: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Double), IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)') Arguments(0) Leaving: {R7} {R1} Next (Regular) Block[B29] Leaving: {R7} } Block[B29] - Block Predecessors: [B27] [B28] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = true') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsImplicit) (Syntax: 'result = true') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B30] Entering: {R10} {R11} {R12} .locals {R10} { CaptureIds: [14] .locals {R11} { CaptureIds: [13] .locals {R12} { CaptureIds: [12] Block[B30] - Block Predecessors: [B29] Statements (1) IFlowCaptureOperation: 12 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1') Jump if True (Regular) to Block[B32] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 12 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Leaving: {R12} Next (Regular) Block[B31] Block[B31] - Block Predecessors: [B30] Statements (1) IFlowCaptureOperation: 13 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 12 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B33] Leaving: {R12} } Block[B32] - Block Predecessors: [B30] Statements (1) IFlowCaptureOperation: 13 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2') Next (Regular) Block[B33] Block[B33] - Block Predecessors: [B31] [B32] Statements (1) IFlowCaptureOperation: 14 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i') Value: IFieldReferenceOperation: C.i As System.Nullable(Of System.Double) (OperationKind.FieldReference, Type: System.Nullable(Of System.Double), IsImplicit) (Syntax: 'If(c1, c2).i') Instance Receiver: IFlowCaptureReferenceOperation: 13 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)') Next (Regular) Block[B34] Leaving: {R11} Entering: {R13} {R14} } .locals {R13} { CaptureIds: [16] .locals {R14} { CaptureIds: [15] Block[B34] - Block Predecessors: [B33] Statements (1) IFlowCaptureOperation: 15 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1') Jump if True (Regular) to Block[B36] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 15 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Leaving: {R14} Next (Regular) Block[B35] Block[B35] - Block Predecessors: [B34] Statements (1) IFlowCaptureOperation: 16 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 15 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B37] Leaving: {R14} } Block[B36] - Block Predecessors: [B34] Statements (1) IFlowCaptureOperation: 16 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2') Next (Regular) Block[B37] Block[B37] - Block Predecessors: [B35] [B36] Statements (0) Jump if False (Regular) to Block[B39] IBinaryOperation (BinaryOperatorKind.Or) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'If(bStep, step1, step2)') Left: IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'If(bStep, step1, step2)') Operand: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Double), IsImplicit) (Syntax: 'If(bStep, step1, step2)') Right: IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'If(c1, c2).i') Operand: IFieldReferenceOperation: C.i As System.Nullable(Of System.Double) (OperationKind.FieldReference, Type: System.Nullable(Of System.Double), IsImplicit) (Syntax: 'If(c1, c2).i') Instance Receiver: IFlowCaptureReferenceOperation: 16 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)') Leaving: {R13} Entering: {R15} {R16} Next (Regular) Block[B38] Leaving: {R13} } Block[B38] - Block Predecessors: [B37] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i') Left: IFlowCaptureReferenceOperation: 14 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Double), IsImplicit) (Syntax: 'If(c1, c2).i') Right: IDefaultValueOperation (OperationKind.DefaultValue, Type: System.Nullable(Of System.Double), IsImplicit) (Syntax: 'If(c1, c2).i') Next (Regular) Block[B18] Leaving: {R10} Entering: {R5} {R6} .locals {R15} { CaptureIds: [18] .locals {R16} { CaptureIds: [17] Block[B39] - Block Predecessors: [B37] Statements (1) IFlowCaptureOperation: 17 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1') Jump if True (Regular) to Block[B41] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 17 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Leaving: {R16} Next (Regular) Block[B40] Block[B40] - Block Predecessors: [B39] Statements (1) IFlowCaptureOperation: 18 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 17 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B42] Leaving: {R16} } Block[B41] - Block Predecessors: [B39] Statements (1) IFlowCaptureOperation: 18 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2') Next (Regular) Block[B42] Block[B42] - Block Predecessors: [B40] [B41] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i') Left: IFlowCaptureReferenceOperation: 14 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Double), IsImplicit) (Syntax: 'If(c1, c2).i') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Nullable(Of System.Double), IsImplicit) (Syntax: 'If(bStep, step1, step2)') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (WideningNullable) Operand: IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Double, IsImplicit) (Syntax: 'If(bStep, step1, step2)') Left: IInvocationOperation ( Function System.Nullable(Of System.Double).GetValueOrDefault() As System.Double) (OperationKind.Invocation, Type: System.Double, IsImplicit) (Syntax: 'If(c1, c2).i') Instance Receiver: IFieldReferenceOperation: C.i As System.Nullable(Of System.Double) (OperationKind.FieldReference, Type: System.Nullable(Of System.Double), IsImplicit) (Syntax: 'If(c1, c2).i') Instance Receiver: IFlowCaptureReferenceOperation: 18 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)') Arguments(0) Right: IInvocationOperation ( Function System.Nullable(Of System.Double).GetValueOrDefault() As System.Double) (OperationKind.Invocation, Type: System.Double, IsImplicit) (Syntax: 'If(bStep, step1, step2)') Instance Receiver: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Double), IsImplicit) (Syntax: 'If(bStep, step1, step2)') Arguments(0) Next (Regular) Block[B18] Leaving: {R15} {R10} Entering: {R5} {R6} } } } Block[B43] - Exit Predecessors: [B21] [B27] [B28] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForToFlow_19() Dim source = <![CDATA[ Imports System Public Class C Sub M(i As Integer, result As Integer) 'BIND:"Sub M" For i = 0 To 4 Step 2 if result = i Exit For End If Next End Sub End Class]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [2] [3] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (5) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '0') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '4') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4') IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '2') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: '0') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: '0') Next (Regular) Block[B2] Leaving: {R2} } Block[B2] - Block Predecessors: [B1] [B4] Statements (0) Jump if False (Regular) to Block[B5] IBinaryOperation (BinaryOperatorKind.LessThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '4') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 4, IsImplicit) (Syntax: '4') Leaving: {R1} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (0) Jump if False (Regular) to Block[B4] IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'result = i') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result') Right: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') Next (Regular) Block[B5] Leaving: {R1} Block[B4] - Block Predecessors: [B3] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'i') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32, IsImplicit) (Syntax: '2') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: '2') Next (Regular) Block[B2] } Block[B5] - Exit Predecessors: [B2] [B3] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics, TestOptions.ReleaseDll.WithOverflowChecks(False)) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForToFlow_20() Dim source = <![CDATA[ Imports System Public Class C Sub M(i As Integer, result As Integer) 'BIND:"Sub M" For i = 0 To 4 Step 2 if result = i Continue For End If result = i Next End Sub End Class]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [2] [3] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (5) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '0') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '4') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4') IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '2') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: '0') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: '0') Next (Regular) Block[B2] Leaving: {R2} } Block[B2] - Block Predecessors: [B1] [B5] Statements (0) Jump if False (Regular) to Block[B6] IBinaryOperation (BinaryOperatorKind.LessThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '4') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 4, IsImplicit) (Syntax: '4') Leaving: {R1} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (0) Jump if False (Regular) to Block[B4] IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'result = i') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result') Right: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') Next (Regular) Block[B5] Block[B4] - Block Predecessors: [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'result = i') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result') Right: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'i') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32, IsImplicit) (Syntax: '2') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: '2') Next (Regular) Block[B2] } Block[B6] - Exit Predecessors: [B2] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics, TestOptions.ReleaseDll.WithOverflowChecks(False)) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForToFlow_21() Dim source = <![CDATA[ Imports System Public Class C Sub M(i As C, init As C, limit As C, [step] As C, result As C) 'BIND:"Sub M" For i = init To limit Step [step] result = i Next End Sub Public Shared Operator <=(x As C, y As C) As Boolean Return False End Operator Public Shared Operator -(x As C, y As C) As C Return Nothing End Operator Public Shared Operator +(x As C, y As C) As C Return Nothing End Operator End Class ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC33038: Type 'C' must define operator '>=' to be used in a 'For' statement. For i = init To limit Step [step] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC33033: Matching '>=' operator is required for 'Public Shared Operator <=(x As C, y As C) As Boolean'. Public Shared Operator <=(x As C, y As C) As Boolean ~~ ]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [2] [3] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (5) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'i') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'init') Value: IParameterReferenceOperation: init (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'init') IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'limit') Value: IParameterReferenceOperation: limit (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'limit') IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: '[step]') Value: IParameterReferenceOperation: step (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: '[step]') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsInvalid, IsImplicit) (Syntax: 'init') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'init') Next (Regular) Block[B2] Leaving: {R2} } Block[B2] - Block Predecessors: [B1] [B3] Statements (0) Jump if False (Regular) to Block[B4] IInvalidOperation (OperationKind.Invalid, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'limit') Children(2): IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i') IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'limit') Leaving: {R1} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'result = i') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: C) (Syntax: 'result') Right: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C) (Syntax: 'i') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsInvalid, IsImplicit) (Syntax: 'i') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: C, IsInvalid, IsImplicit) (Syntax: '[step]') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: '[step]') Next (Regular) Block[B2] } Block[B4] - Exit Predecessors: [B2] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForToFlow_22() Dim source = <![CDATA[ Imports System Public Class C Sub M(i As C, init As C, limit As C, [step] As C, result As C) 'BIND:"Sub M" For i = init To limit Step [step] result = i Next End Sub Public Shared Operator >=(x As C, y As C) As Boolean Return False End Operator Public Shared Operator -(x As C, y As C) As C Return Nothing End Operator Public Shared Operator +(x As C, y As C) As C Return Nothing End Operator End Class ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC33038: Type 'C' must define operator '<=' to be used in a 'For' statement. For i = init To limit Step [step] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC33033: Matching '<=' operator is required for 'Public Shared Operator >=(x As C, y As C) As Boolean'. Public Shared Operator >=(x As C, y As C) As Boolean ~~ ]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [2] [3] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (5) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'i') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'init') Value: IParameterReferenceOperation: init (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'init') IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'limit') Value: IParameterReferenceOperation: limit (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'limit') IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: '[step]') Value: IParameterReferenceOperation: step (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: '[step]') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsInvalid, IsImplicit) (Syntax: 'init') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'init') Next (Regular) Block[B2] Leaving: {R2} } Block[B2] - Block Predecessors: [B1] [B3] Statements (0) Jump if False (Regular) to Block[B4] IInvalidOperation (OperationKind.Invalid, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'limit') Children(2): IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i') IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'limit') Leaving: {R1} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'result = i') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: C) (Syntax: 'result') Right: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C) (Syntax: 'i') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsInvalid, IsImplicit) (Syntax: 'i') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: C, IsInvalid, IsImplicit) (Syntax: '[step]') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: '[step]') Next (Regular) Block[B2] } Block[B4] - Exit Predecessors: [B2] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForToFlow_23() Dim source = <![CDATA[ Imports System Public Class C Sub M(i As C, init As C, limit As C, [step] As C, result As C) 'BIND:"Sub M" For i = init To limit Step [step] result = i Next End Sub Public Shared Operator >=(x As C, y As C) As Boolean Return False End Operator Public Shared Operator <=(x As C, y As C) As Boolean Return False End Operator Public Shared Operator +(x As C, y As C) As C Return Nothing End Operator End Class ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC33038: Type 'C' must define operator '-' to be used in a 'For' statement. For i = init To limit Step [step] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [2] [3] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (5) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'i') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'init') Value: IParameterReferenceOperation: init (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'init') IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'limit') Value: IParameterReferenceOperation: limit (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'limit') IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: '[step]') Value: IParameterReferenceOperation: step (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: '[step]') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsInvalid, IsImplicit) (Syntax: 'init') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'init') Next (Regular) Block[B2] Leaving: {R2} } Block[B2] - Block Predecessors: [B1] [B3] Statements (0) Jump if False (Regular) to Block[B4] IInvalidOperation (OperationKind.Invalid, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'limit') Children(2): IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i') IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'limit') Leaving: {R1} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'result = i') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: C) (Syntax: 'result') Right: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C) (Syntax: 'i') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsInvalid, IsImplicit) (Syntax: 'i') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: C, IsInvalid, IsImplicit) (Syntax: '[step]') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: '[step]') Next (Regular) Block[B2] } Block[B4] - Exit Predecessors: [B2] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForToFlow_24() Dim source = <![CDATA[ Imports System Public Class C Sub M(i As C, init As C, limit As C, [step] As C, result As C) 'BIND:"Sub M" For i = init To limit Step [step] result = i Next End Sub Public Shared Operator >=(x As C, y As C) As Boolean Return False End Operator Public Shared Operator <=(x As C, y As C) As Boolean Return False End Operator Public Shared Operator -(x As C, y As C) As C Return Nothing End Operator End Class ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC33038: Type 'C' must define operator '+' to be used in a 'For' statement. For i = init To limit Step [step] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [2] [3] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (5) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'i') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'init') Value: IParameterReferenceOperation: init (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'init') IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'limit') Value: IParameterReferenceOperation: limit (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'limit') IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: '[step]') Value: IParameterReferenceOperation: step (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: '[step]') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsInvalid, IsImplicit) (Syntax: 'init') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'init') Next (Regular) Block[B2] Leaving: {R2} } Block[B2] - Block Predecessors: [B1] [B3] Statements (0) Jump if False (Regular) to Block[B4] IInvalidOperation (OperationKind.Invalid, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'limit') Children(2): IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i') IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'limit') Leaving: {R1} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'result = i') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: C) (Syntax: 'result') Right: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C) (Syntax: 'i') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsInvalid, IsImplicit) (Syntax: 'i') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: C, IsInvalid, IsImplicit) (Syntax: '[step]') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: '[step]') Next (Regular) Block[B2] } Block[B4] - Exit Predecessors: [B2] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForToFlow_25() Dim source = <![CDATA[ Imports System Public Class C Sub M(i As C, init As C, limit As C, [step] As C, result As C) 'BIND:"Sub M" For i = init To limit Step [step] result = i Next End Sub Public Shared Operator >=(x As C, y As C) As Boolean Return False End Operator Public Shared Operator <=(x As C, y As C) As Boolean Return False End Operator Public Shared Operator -(x As C, y As C) As C Return Nothing End Operator Public Shared Operator +(x As C, y As C) As C Return Nothing End Operator End Class ]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [2] [3] [4] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (6) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C) (Syntax: 'i') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init') Value: IParameterReferenceOperation: init (OperationKind.ParameterReference, Type: C) (Syntax: 'init') IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit') Value: IParameterReferenceOperation: limit (OperationKind.ParameterReference, Type: C) (Syntax: 'limit') IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '[step]') Value: IParameterReferenceOperation: step (OperationKind.ParameterReference, Type: C) (Syntax: '[step]') IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'For i = ini ... Step [step]') Value: IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual, Checked) (OperatorMethod: Function C.op_GreaterThanOrEqual(x As C, y As C) As System.Boolean) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'For i = ini ... Step [step]') Left: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: '[step]') Right: IBinaryOperation (BinaryOperatorKind.Subtract, Checked) (OperatorMethod: Function C.op_Subtraction(x As C, y As C) As C) (OperationKind.Binary, Type: C, IsImplicit) (Syntax: 'For i = ini ... Step [step]') Left: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: '[step]') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: '[step]') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'init') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'init') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} } .locals {R3} { CaptureIds: [5] Block[B2] - Block Predecessors: [B1] [B5] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'i') Jump if False (Regular) to Block[B4] IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: 'For i = ini ... Step [step]') Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (0) Jump if False (Regular) to Block[B6] IBinaryOperation (BinaryOperatorKind.LessThanOrEqual, Checked) (OperatorMethod: Function C.op_LessThanOrEqual(x As C, y As C) As System.Boolean) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'For i = ini ... Step [step]') Left: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'limit') Leaving: {R3} {R1} Next (Regular) Block[B5] Leaving: {R3} Block[B4] - Block Predecessors: [B2] Statements (0) Jump if False (Regular) to Block[B6] IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual, Checked) (OperatorMethod: Function C.op_GreaterThanOrEqual(x As C, y As C) As System.Boolean) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'For i = ini ... Step [step]') Left: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'limit') Leaving: {R3} {R1} Next (Regular) Block[B5] Leaving: {R3} } Block[B5] - Block Predecessors: [B3] [B4] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'result = i') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: C) (Syntax: 'result') Right: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C) (Syntax: 'i') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'i') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperatorMethod: Function C.op_Addition(x As C, y As C) As C) (OperationKind.Binary, Type: C, IsImplicit) (Syntax: 'For i = ini ... Step [step]') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: '[step]') Next (Regular) Block[B2] Entering: {R3} } Block[B6] - Exit Predecessors: [B3] [B4] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForToFlow_26() Dim source = <![CDATA[ Imports System Public Class C Sub M(i As C, init As C, limit As C, [step] As C, result As C) 'BIND:"Sub M" For i = init To limit Step [step] result = i Next End Sub Public Shared Operator >=(x As C, y As C) As C Return Nothing End Operator Public Shared Operator <=(x As C, y As C) As C Return Nothing End Operator Public Shared Operator -(x As C, y As C) As C Return Nothing End Operator Public Shared Operator +(x As C, y As C) As C Return Nothing End Operator End Class ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30311: Value of type 'C' cannot be converted to 'Boolean'. For i = init To limit Step [step] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [2] [3] [4] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (6) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'i') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'init') Value: IParameterReferenceOperation: init (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'init') IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'limit') Value: IParameterReferenceOperation: limit (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'limit') IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: '[step]') Value: IParameterReferenceOperation: step (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: '[step]') IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'For i = ini ... Step [step]') Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'For i = ini ... Step [step]') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (DelegateRelaxationLevelNone) Operand: IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual, Checked) (OperatorMethod: Function C.op_GreaterThanOrEqual(x As C, y As C) As C) (OperationKind.Binary, Type: C, IsInvalid, IsImplicit) (Syntax: 'For i = ini ... Step [step]') Left: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: '[step]') Right: IBinaryOperation (BinaryOperatorKind.Subtract, Checked) (OperatorMethod: Function C.op_Subtraction(x As C, y As C) As C) (OperationKind.Binary, Type: C, IsInvalid, IsImplicit) (Syntax: 'For i = ini ... Step [step]') Left: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: '[step]') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: '[step]') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsInvalid, IsImplicit) (Syntax: 'init') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'init') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} } .locals {R3} { CaptureIds: [5] Block[B2] - Block Predecessors: [B1] [B5] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i') Jump if False (Regular) to Block[B4] IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'For i = ini ... Step [step]') Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (0) Jump if False (Regular) to Block[B6] IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'For i = ini ... Step [step]') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (DelegateRelaxationLevelNone) Operand: IBinaryOperation (BinaryOperatorKind.LessThanOrEqual, Checked) (OperatorMethod: Function C.op_LessThanOrEqual(x As C, y As C) As C) (OperationKind.Binary, Type: C, IsInvalid, IsImplicit) (Syntax: 'For i = ini ... Step [step]') Left: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'limit') Leaving: {R3} {R1} Next (Regular) Block[B5] Leaving: {R3} Block[B4] - Block Predecessors: [B2] Statements (0) Jump if False (Regular) to Block[B6] IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'For i = ini ... Step [step]') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (DelegateRelaxationLevelNone) Operand: IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual, Checked) (OperatorMethod: Function C.op_GreaterThanOrEqual(x As C, y As C) As C) (OperationKind.Binary, Type: C, IsInvalid, IsImplicit) (Syntax: 'For i = ini ... Step [step]') Left: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'limit') Leaving: {R3} {R1} Next (Regular) Block[B5] Leaving: {R3} } Block[B5] - Block Predecessors: [B3] [B4] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'result = i') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: C) (Syntax: 'result') Right: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C) (Syntax: 'i') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsInvalid, IsImplicit) (Syntax: 'i') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperatorMethod: Function C.op_Addition(x As C, y As C) As C) (OperationKind.Binary, Type: C, IsInvalid, IsImplicit) (Syntax: 'For i = ini ... Step [step]') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: '[step]') Next (Regular) Block[B2] Entering: {R3} } Block[B6] - Exit Predecessors: [B3] [B4] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForToFlow_27() Dim source = <![CDATA[ Imports System Public Class C Sub M(i As C, init As C, limit As C, [step] As C, result As C) 'BIND:"Sub M" For i = init To limit Step [step] result = i Next End Sub Public Shared Operator >=(x As C, y As C) As C Return Nothing End Operator Public Shared Operator <=(x As C, y As C) As C Return Nothing End Operator Public Shared Operator -(x As C, y As C) As C Return Nothing End Operator Public Shared Operator +(x As C, y As C) As C Return Nothing End Operator Public Shared Operator IsTrue(x As C) As Boolean Return Nothing End Operator Public Shared Operator IsFalse(x As C) As Boolean Return Nothing End Operator End Class ]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [2] [3] [4] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (6) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C) (Syntax: 'i') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init') Value: IParameterReferenceOperation: init (OperationKind.ParameterReference, Type: C) (Syntax: 'init') IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit') Value: IParameterReferenceOperation: limit (OperationKind.ParameterReference, Type: C) (Syntax: 'limit') IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '[step]') Value: IParameterReferenceOperation: step (OperationKind.ParameterReference, Type: C) (Syntax: '[step]') IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'For i = ini ... Step [step]') Value: IUnaryOperation (UnaryOperatorKind.True) (OperatorMethod: Function C.op_True(x As C) As System.Boolean) (OperationKind.Unary, Type: System.Boolean, IsImplicit) (Syntax: 'For i = ini ... Step [step]') Operand: IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual, Checked) (OperatorMethod: Function C.op_GreaterThanOrEqual(x As C, y As C) As C) (OperationKind.Binary, Type: C, IsImplicit) (Syntax: 'For i = ini ... Step [step]') Left: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: '[step]') Right: IBinaryOperation (BinaryOperatorKind.Subtract, Checked) (OperatorMethod: Function C.op_Subtraction(x As C, y As C) As C) (OperationKind.Binary, Type: C, IsImplicit) (Syntax: 'For i = ini ... Step [step]') Left: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: '[step]') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: '[step]') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'init') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'init') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} } .locals {R3} { CaptureIds: [5] Block[B2] - Block Predecessors: [B1] [B5] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'i') Jump if False (Regular) to Block[B4] IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: 'For i = ini ... Step [step]') Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (0) Jump if False (Regular) to Block[B6] IUnaryOperation (UnaryOperatorKind.True) (OperatorMethod: Function C.op_True(x As C) As System.Boolean) (OperationKind.Unary, Type: System.Boolean, IsImplicit) (Syntax: 'For i = ini ... Step [step]') Operand: IBinaryOperation (BinaryOperatorKind.LessThanOrEqual, Checked) (OperatorMethod: Function C.op_LessThanOrEqual(x As C, y As C) As C) (OperationKind.Binary, Type: C, IsImplicit) (Syntax: 'For i = ini ... Step [step]') Left: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'limit') Leaving: {R3} {R1} Next (Regular) Block[B5] Leaving: {R3} Block[B4] - Block Predecessors: [B2] Statements (0) Jump if False (Regular) to Block[B6] IUnaryOperation (UnaryOperatorKind.True) (OperatorMethod: Function C.op_True(x As C) As System.Boolean) (OperationKind.Unary, Type: System.Boolean, IsImplicit) (Syntax: 'For i = ini ... Step [step]') Operand: IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual, Checked) (OperatorMethod: Function C.op_GreaterThanOrEqual(x As C, y As C) As C) (OperationKind.Binary, Type: C, IsImplicit) (Syntax: 'For i = ini ... Step [step]') Left: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'limit') Leaving: {R3} {R1} Next (Regular) Block[B5] Leaving: {R3} } Block[B5] - Block Predecessors: [B3] [B4] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'result = i') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: C) (Syntax: 'result') Right: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C) (Syntax: 'i') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'i') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperatorMethod: Function C.op_Addition(x As C, y As C) As C) (OperationKind.Binary, Type: C, IsImplicit) (Syntax: 'For i = ini ... Step [step]') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: '[step]') Next (Regular) Block[B2] Entering: {R3} } Block[B6] - Exit Predecessors: [B3] [B4] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForToFlow_28() Dim source = <![CDATA[ Imports System Public Structure C Sub M(i As C?, init As C?, limit As C?, [step] As C?, result As C?) 'BIND:"Sub M" For i = init To limit Step [step] result = i Next End Sub Public Shared Operator >=(x As C, y As C) As Boolean Return False End Operator Public Shared Operator <=(x As C, y As C) As Boolean Return False End Operator Public Shared Operator -(x As C, y As C) As C Return Nothing End Operator Public Shared Operator +(x As C, y As C) As C Return Nothing End Operator End Structure ]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [2] [3] [4] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (6) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of C)) (Syntax: 'i') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init') Value: IParameterReferenceOperation: init (OperationKind.ParameterReference, Type: System.Nullable(Of C)) (Syntax: 'init') IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit') Value: IParameterReferenceOperation: limit (OperationKind.ParameterReference, Type: System.Nullable(Of C)) (Syntax: 'limit') IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '[step]') Value: IParameterReferenceOperation: step (OperationKind.ParameterReference, Type: System.Nullable(Of C)) (Syntax: '[step]') IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'For i = ini ... Step [step]') Value: IInvocationOperation ( Function System.Nullable(Of System.Boolean).GetValueOrDefault() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'For i = ini ... Step [step]') Instance Receiver: IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual, IsLifted, Checked) (OperatorMethod: Function C.op_GreaterThanOrEqual(x As C, y As C) As System.Boolean) (OperationKind.Binary, Type: System.Nullable(Of System.Boolean), IsImplicit) (Syntax: 'For i = ini ... Step [step]') Left: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: '[step]') Right: IBinaryOperation (BinaryOperatorKind.Subtract, IsLifted, Checked) (OperatorMethod: Function C.op_Subtraction(x As C, y As C) As C) (OperationKind.Binary, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'For i = ini ... Step [step]') Left: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: '[step]') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: '[step]') Arguments(0) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'init') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'init') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} } .locals {R3} { CaptureIds: [5] Block[B2] - Block Predecessors: [B1] [B5] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'i') Jump if False (Regular) to Block[B4] IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: 'For i = ini ... Step [step]') Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (0) Jump if False (Regular) to Block[B6] IInvocationOperation ( Function System.Nullable(Of System.Boolean).GetValueOrDefault() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'For i = ini ... Step [step]') Instance Receiver: IBinaryOperation (BinaryOperatorKind.LessThanOrEqual, IsLifted, Checked) (OperatorMethod: Function C.op_LessThanOrEqual(x As C, y As C) As System.Boolean) (OperationKind.Binary, Type: System.Nullable(Of System.Boolean), IsImplicit) (Syntax: 'For i = ini ... Step [step]') Left: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'limit') Arguments(0) Leaving: {R3} {R1} Next (Regular) Block[B5] Leaving: {R3} Block[B4] - Block Predecessors: [B2] Statements (0) Jump if False (Regular) to Block[B6] IInvocationOperation ( Function System.Nullable(Of System.Boolean).GetValueOrDefault() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'For i = ini ... Step [step]') Instance Receiver: IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual, IsLifted, Checked) (OperatorMethod: Function C.op_GreaterThanOrEqual(x As C, y As C) As System.Boolean) (OperationKind.Binary, Type: System.Nullable(Of System.Boolean), IsImplicit) (Syntax: 'For i = ini ... Step [step]') Left: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'limit') Arguments(0) Leaving: {R3} {R1} Next (Regular) Block[B5] Leaving: {R3} } Block[B5] - Block Predecessors: [B3] [B4] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'result = i') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Nullable(Of C)) (Syntax: 'result') Right: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of C)) (Syntax: 'i') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'i') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Add, IsLifted, Checked) (OperatorMethod: Function C.op_Addition(x As C, y As C) As C) (OperationKind.Binary, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'For i = ini ... Step [step]') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: '[step]') Next (Regular) Block[B2] Entering: {R3} } Block[B6] - Exit Predecessors: [B3] [B4] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForToFlow_29() Dim source = <![CDATA[ Imports System Public Class C Sub M(c1 As C, c2 As C, bInit As Boolean, init1 As C, init2 As C, bLimit As Boolean, limit1 As C, limit2 As C, bStep As Boolean, step1 As C, step2 As C, result As Boolean) 'BIND:"Sub M" For If(c1, c2).i = If(bInit, init1, init2) To If(bLimit, limit1, limit2) Step If(bStep, step1, step2) result = true Next End Sub Public i As C Public Shared Operator >=(x As C, y As C) As Boolean Return False End Operator Public Shared Operator <=(x As C, y As C) As Boolean Return False End Operator Public Shared Operator -(x As C, y As C) As C Return Nothing End Operator Public Shared Operator +(x As C, y As C) As C Return Nothing End Operator End Class ]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} {R3} {R4} .locals {R1} { CaptureIds: [4] [5] [6] .locals {R2} { CaptureIds: [2] [3] .locals {R3} { CaptureIds: [1] .locals {R4} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C) (Syntax: 'c1') Jump if True (Regular) to Block[B3] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Leaving: {R4} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B4] Leaving: {R4} } Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C) (Syntax: 'c2') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i') Value: IFieldReferenceOperation: C.i As C (OperationKind.FieldReference, Type: C) (Syntax: 'If(c1, c2).i') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)') Next (Regular) Block[B5] Leaving: {R3} } Block[B5] - Block Predecessors: [B4] Statements (0) Jump if False (Regular) to Block[B7] IParameterReferenceOperation: bInit (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bInit') Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init1') Value: IParameterReferenceOperation: init1 (OperationKind.ParameterReference, Type: C) (Syntax: 'init1') Next (Regular) Block[B8] Block[B7] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init2') Value: IParameterReferenceOperation: init2 (OperationKind.ParameterReference, Type: C) (Syntax: 'init2') Next (Regular) Block[B8] Block[B8] - Block Predecessors: [B6] [B7] Statements (0) Jump if False (Regular) to Block[B10] IParameterReferenceOperation: bLimit (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bLimit') Next (Regular) Block[B9] Block[B9] - Block Predecessors: [B8] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit1') Value: IParameterReferenceOperation: limit1 (OperationKind.ParameterReference, Type: C) (Syntax: 'limit1') Next (Regular) Block[B11] Block[B10] - Block Predecessors: [B8] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit2') Value: IParameterReferenceOperation: limit2 (OperationKind.ParameterReference, Type: C) (Syntax: 'limit2') Next (Regular) Block[B11] Block[B11] - Block Predecessors: [B9] [B10] Statements (0) Jump if False (Regular) to Block[B13] IParameterReferenceOperation: bStep (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bStep') Next (Regular) Block[B12] Block[B12] - Block Predecessors: [B11] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'step1') Value: IParameterReferenceOperation: step1 (OperationKind.ParameterReference, Type: C) (Syntax: 'step1') Next (Regular) Block[B14] Block[B13] - Block Predecessors: [B11] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'step2') Value: IParameterReferenceOperation: step2 (OperationKind.ParameterReference, Type: C) (Syntax: 'step2') Next (Regular) Block[B14] Block[B14] - Block Predecessors: [B12] [B13] Statements (2) IFlowCaptureOperation: 6 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'For If(c1, ... ep1, step2)') Value: IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual, Checked) (OperatorMethod: Function C.op_GreaterThanOrEqual(x As C, y As C) As System.Boolean) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'For If(c1, ... ep1, step2)') Left: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(bStep, step1, step2)') Right: IBinaryOperation (BinaryOperatorKind.Subtract, Checked) (OperatorMethod: Function C.op_Subtraction(x As C, y As C) As C) (OperationKind.Binary, Type: C, IsImplicit) (Syntax: 'For If(c1, ... ep1, step2)') Left: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(bStep, step1, step2)') Right: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(bStep, step1, step2)') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'If(bInit, init1, init2)') Left: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2).i') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(bInit, init1, init2)') Next (Regular) Block[B15] Leaving: {R2} Entering: {R5} {R6} {R7} } .locals {R5} { CaptureIds: [9] .locals {R6} { CaptureIds: [8] .locals {R7} { CaptureIds: [7] Block[B15] - Block Predecessors: [B14] [B30] Statements (1) IFlowCaptureOperation: 7 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1') Jump if True (Regular) to Block[B17] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 7 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Leaving: {R7} Next (Regular) Block[B16] Block[B16] - Block Predecessors: [B15] Statements (1) IFlowCaptureOperation: 8 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 7 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B18] Leaving: {R7} } Block[B17] - Block Predecessors: [B15] Statements (1) IFlowCaptureOperation: 8 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2') Next (Regular) Block[B18] Block[B18] - Block Predecessors: [B16] [B17] Statements (1) IFlowCaptureOperation: 9 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i') Value: IFieldReferenceOperation: C.i As C (OperationKind.FieldReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2).i') Instance Receiver: IFlowCaptureReferenceOperation: 8 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)') Next (Regular) Block[B19] Leaving: {R6} } Block[B19] - Block Predecessors: [B18] Statements (0) Jump if False (Regular) to Block[B21] IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: 'For If(c1, ... ep1, step2)') Next (Regular) Block[B20] Block[B20] - Block Predecessors: [B19] Statements (0) Jump if False (Regular) to Block[B31] IBinaryOperation (BinaryOperatorKind.LessThanOrEqual, Checked) (OperatorMethod: Function C.op_LessThanOrEqual(x As C, y As C) As System.Boolean) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'For If(c1, ... ep1, step2)') Left: IFlowCaptureReferenceOperation: 9 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2).i') Right: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)') Leaving: {R5} {R1} Next (Regular) Block[B22] Leaving: {R5} Block[B21] - Block Predecessors: [B19] Statements (0) Jump if False (Regular) to Block[B31] IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual, Checked) (OperatorMethod: Function C.op_GreaterThanOrEqual(x As C, y As C) As System.Boolean) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'For If(c1, ... ep1, step2)') Left: IFlowCaptureReferenceOperation: 9 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2).i') Right: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)') Leaving: {R5} {R1} Next (Regular) Block[B22] Leaving: {R5} } Block[B22] - Block Predecessors: [B20] [B21] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = true') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsImplicit) (Syntax: 'result = true') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B23] Entering: {R8} {R9} {R10} .locals {R8} { CaptureIds: [12] [14] .locals {R9} { CaptureIds: [11] .locals {R10} { CaptureIds: [10] Block[B23] - Block Predecessors: [B22] Statements (1) IFlowCaptureOperation: 10 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1') Jump if True (Regular) to Block[B25] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 10 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Leaving: {R10} Next (Regular) Block[B24] Block[B24] - Block Predecessors: [B23] Statements (1) IFlowCaptureOperation: 11 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 10 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B26] Leaving: {R10} } Block[B25] - Block Predecessors: [B23] Statements (1) IFlowCaptureOperation: 11 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2') Next (Regular) Block[B26] Block[B26] - Block Predecessors: [B24] [B25] Statements (1) IFlowCaptureOperation: 12 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i') Value: IFieldReferenceOperation: C.i As C (OperationKind.FieldReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2).i') Instance Receiver: IFlowCaptureReferenceOperation: 11 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)') Next (Regular) Block[B27] Leaving: {R9} Entering: {R11} } .locals {R11} { CaptureIds: [13] Block[B27] - Block Predecessors: [B26] Statements (1) IFlowCaptureOperation: 13 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1') Jump if True (Regular) to Block[B29] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 13 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Leaving: {R11} Next (Regular) Block[B28] Block[B28] - Block Predecessors: [B27] Statements (1) IFlowCaptureOperation: 14 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 13 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B30] Leaving: {R11} } Block[B29] - Block Predecessors: [B27] Statements (1) IFlowCaptureOperation: 14 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2') Next (Regular) Block[B30] Block[B30] - Block Predecessors: [B28] [B29] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i') Left: IFlowCaptureReferenceOperation: 12 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2).i') Right: IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperatorMethod: Function C.op_Addition(x As C, y As C) As C) (OperationKind.Binary, Type: C, IsImplicit) (Syntax: 'For If(c1, ... ep1, step2)') Left: IFieldReferenceOperation: C.i As C (OperationKind.FieldReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2).i') Instance Receiver: IFlowCaptureReferenceOperation: 14 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)') Right: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(bStep, step1, step2)') Next (Regular) Block[B15] Leaving: {R8} Entering: {R5} {R6} {R7} } } Block[B31] - Exit Predecessors: [B20] [B21] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForToFlow_30() Dim source = <![CDATA[ Imports System Public Class C1 Sub M(c1 As C1, c2 As C1, bInit As Boolean, init1 As C?, init2 As C?, bLimit As Boolean, limit1 As C?, limit2 As C?, bStep As Boolean, step1 As C?, step2 As C?, result As Boolean) 'BIND:"Sub M" For If(c1, c2).i = If(bInit, init1, init2) To If(bLimit, limit1, limit2) Step If(bStep, step1, step2) result = true Next End Sub Public i As C? End Class Public Structure C Public Shared Operator >=(x As C, y As C) As Boolean Return False End Operator Public Shared Operator <=(x As C, y As C) As Boolean Return False End Operator Public Shared Operator -(x As C, y As C) As C Return Nothing End Operator Public Shared Operator +(x As C, y As C) As C Return Nothing End Operator End Structure ]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} {R3} {R4} .locals {R1} { CaptureIds: [4] [5] [6] .locals {R2} { CaptureIds: [2] [3] .locals {R3} { CaptureIds: [1] .locals {R4} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C1) (Syntax: 'c1') Jump if True (Regular) to Block[B3] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'c1') Leaving: {R4} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B4] Leaving: {R4} } Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C1) (Syntax: 'c2') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i') Value: IFieldReferenceOperation: C1.i As System.Nullable(Of C) (OperationKind.FieldReference, Type: System.Nullable(Of C)) (Syntax: 'If(c1, c2).i') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'If(c1, c2)') Next (Regular) Block[B5] Leaving: {R3} } Block[B5] - Block Predecessors: [B4] Statements (0) Jump if False (Regular) to Block[B7] IParameterReferenceOperation: bInit (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bInit') Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init1') Value: IParameterReferenceOperation: init1 (OperationKind.ParameterReference, Type: System.Nullable(Of C)) (Syntax: 'init1') Next (Regular) Block[B8] Block[B7] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init2') Value: IParameterReferenceOperation: init2 (OperationKind.ParameterReference, Type: System.Nullable(Of C)) (Syntax: 'init2') Next (Regular) Block[B8] Block[B8] - Block Predecessors: [B6] [B7] Statements (0) Jump if False (Regular) to Block[B10] IParameterReferenceOperation: bLimit (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bLimit') Next (Regular) Block[B9] Block[B9] - Block Predecessors: [B8] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit1') Value: IParameterReferenceOperation: limit1 (OperationKind.ParameterReference, Type: System.Nullable(Of C)) (Syntax: 'limit1') Next (Regular) Block[B11] Block[B10] - Block Predecessors: [B8] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit2') Value: IParameterReferenceOperation: limit2 (OperationKind.ParameterReference, Type: System.Nullable(Of C)) (Syntax: 'limit2') Next (Regular) Block[B11] Block[B11] - Block Predecessors: [B9] [B10] Statements (0) Jump if False (Regular) to Block[B13] IParameterReferenceOperation: bStep (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bStep') Next (Regular) Block[B12] Block[B12] - Block Predecessors: [B11] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'step1') Value: IParameterReferenceOperation: step1 (OperationKind.ParameterReference, Type: System.Nullable(Of C)) (Syntax: 'step1') Next (Regular) Block[B14] Block[B13] - Block Predecessors: [B11] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'step2') Value: IParameterReferenceOperation: step2 (OperationKind.ParameterReference, Type: System.Nullable(Of C)) (Syntax: 'step2') Next (Regular) Block[B14] Block[B14] - Block Predecessors: [B12] [B13] Statements (2) IFlowCaptureOperation: 6 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'For If(c1, ... ep1, step2)') Value: IInvocationOperation ( Function System.Nullable(Of System.Boolean).GetValueOrDefault() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'For If(c1, ... ep1, step2)') Instance Receiver: IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual, IsLifted, Checked) (OperatorMethod: Function C.op_GreaterThanOrEqual(x As C, y As C) As System.Boolean) (OperationKind.Binary, Type: System.Nullable(Of System.Boolean), IsImplicit) (Syntax: 'For If(c1, ... ep1, step2)') Left: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'If(bStep, step1, step2)') Right: IBinaryOperation (BinaryOperatorKind.Subtract, IsLifted, Checked) (OperatorMethod: Function C.op_Subtraction(x As C, y As C) As C) (OperationKind.Binary, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'For If(c1, ... ep1, step2)') Left: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'If(bStep, step1, step2)') Right: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'If(bStep, step1, step2)') Arguments(0) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'If(bInit, init1, init2)') Left: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'If(c1, c2).i') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'If(bInit, init1, init2)') Next (Regular) Block[B15] Leaving: {R2} Entering: {R5} {R6} {R7} } .locals {R5} { CaptureIds: [9] .locals {R6} { CaptureIds: [8] .locals {R7} { CaptureIds: [7] Block[B15] - Block Predecessors: [B14] [B30] Statements (1) IFlowCaptureOperation: 7 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C1, IsImplicit) (Syntax: 'c1') Jump if True (Regular) to Block[B17] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 7 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'c1') Leaving: {R7} Next (Regular) Block[B16] Block[B16] - Block Predecessors: [B15] Statements (1) IFlowCaptureOperation: 8 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 7 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B18] Leaving: {R7} } Block[B17] - Block Predecessors: [B15] Statements (1) IFlowCaptureOperation: 8 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C1, IsImplicit) (Syntax: 'c2') Next (Regular) Block[B18] Block[B18] - Block Predecessors: [B16] [B17] Statements (1) IFlowCaptureOperation: 9 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i') Value: IFieldReferenceOperation: C1.i As System.Nullable(Of C) (OperationKind.FieldReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'If(c1, c2).i') Instance Receiver: IFlowCaptureReferenceOperation: 8 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'If(c1, c2)') Next (Regular) Block[B19] Leaving: {R6} } Block[B19] - Block Predecessors: [B18] Statements (0) Jump if False (Regular) to Block[B21] IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: 'For If(c1, ... ep1, step2)') Next (Regular) Block[B20] Block[B20] - Block Predecessors: [B19] Statements (0) Jump if False (Regular) to Block[B31] IInvocationOperation ( Function System.Nullable(Of System.Boolean).GetValueOrDefault() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'For If(c1, ... ep1, step2)') Instance Receiver: IBinaryOperation (BinaryOperatorKind.LessThanOrEqual, IsLifted, Checked) (OperatorMethod: Function C.op_LessThanOrEqual(x As C, y As C) As System.Boolean) (OperationKind.Binary, Type: System.Nullable(Of System.Boolean), IsImplicit) (Syntax: 'For If(c1, ... ep1, step2)') Left: IFlowCaptureReferenceOperation: 9 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'If(c1, c2).i') Right: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)') Arguments(0) Leaving: {R5} {R1} Next (Regular) Block[B22] Leaving: {R5} Block[B21] - Block Predecessors: [B19] Statements (0) Jump if False (Regular) to Block[B31] IInvocationOperation ( Function System.Nullable(Of System.Boolean).GetValueOrDefault() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'For If(c1, ... ep1, step2)') Instance Receiver: IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual, IsLifted, Checked) (OperatorMethod: Function C.op_GreaterThanOrEqual(x As C, y As C) As System.Boolean) (OperationKind.Binary, Type: System.Nullable(Of System.Boolean), IsImplicit) (Syntax: 'For If(c1, ... ep1, step2)') Left: IFlowCaptureReferenceOperation: 9 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'If(c1, c2).i') Right: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)') Arguments(0) Leaving: {R5} {R1} Next (Regular) Block[B22] Leaving: {R5} } Block[B22] - Block Predecessors: [B20] [B21] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = true') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsImplicit) (Syntax: 'result = true') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B23] Entering: {R8} {R9} {R10} .locals {R8} { CaptureIds: [12] [14] .locals {R9} { CaptureIds: [11] .locals {R10} { CaptureIds: [10] Block[B23] - Block Predecessors: [B22] Statements (1) IFlowCaptureOperation: 10 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C1, IsImplicit) (Syntax: 'c1') Jump if True (Regular) to Block[B25] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 10 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'c1') Leaving: {R10} Next (Regular) Block[B24] Block[B24] - Block Predecessors: [B23] Statements (1) IFlowCaptureOperation: 11 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 10 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B26] Leaving: {R10} } Block[B25] - Block Predecessors: [B23] Statements (1) IFlowCaptureOperation: 11 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C1, IsImplicit) (Syntax: 'c2') Next (Regular) Block[B26] Block[B26] - Block Predecessors: [B24] [B25] Statements (1) IFlowCaptureOperation: 12 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i') Value: IFieldReferenceOperation: C1.i As System.Nullable(Of C) (OperationKind.FieldReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'If(c1, c2).i') Instance Receiver: IFlowCaptureReferenceOperation: 11 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'If(c1, c2)') Next (Regular) Block[B27] Leaving: {R9} Entering: {R11} } .locals {R11} { CaptureIds: [13] Block[B27] - Block Predecessors: [B26] Statements (1) IFlowCaptureOperation: 13 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C1, IsImplicit) (Syntax: 'c1') Jump if True (Regular) to Block[B29] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 13 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'c1') Leaving: {R11} Next (Regular) Block[B28] Block[B28] - Block Predecessors: [B27] Statements (1) IFlowCaptureOperation: 14 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 13 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B30] Leaving: {R11} } Block[B29] - Block Predecessors: [B27] Statements (1) IFlowCaptureOperation: 14 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C1, IsImplicit) (Syntax: 'c2') Next (Regular) Block[B30] Block[B30] - Block Predecessors: [B28] [B29] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i') Left: IFlowCaptureReferenceOperation: 12 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'If(c1, c2).i') Right: IBinaryOperation (BinaryOperatorKind.Add, IsLifted, Checked) (OperatorMethod: Function C.op_Addition(x As C, y As C) As C) (OperationKind.Binary, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'For If(c1, ... ep1, step2)') Left: IFieldReferenceOperation: C1.i As System.Nullable(Of C) (OperationKind.FieldReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'If(c1, c2).i') Instance Receiver: IFlowCaptureReferenceOperation: 14 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'If(c1, c2)') Right: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'If(bStep, step1, step2)') Next (Regular) Block[B15] Leaving: {R8} Entering: {R5} {R6} {R7} } } Block[B31] - Exit Predecessors: [B20] [B21] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForToFlow_31() Dim source = <![CDATA[ Imports System Public Class C Sub M(i As Object, init As Object, limit As Object, result As Object) 'BIND:"Sub M" For i = init To limit result = i Next End Sub End Class ]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [<anonymous local> As System.Object] Block[B1] - Block Predecessors: [B0] Statements (0) Jump if False (Regular) to Block[B3] IInvocationOperation (Function Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl.ForLoopInitObj(Counter As System.Object, Start As System.Object, Limit As System.Object, StepValue As System.Object, ByRef LoopForResult As System.Object, ByRef CounterResult As System.Object) As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'limit') Instance Receiver: null Arguments(6): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Counter) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i') IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Start) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'init') IParameterReferenceOperation: init (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'init') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Limit) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'limit') IParameterReferenceOperation: limit (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'limit') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: StepValue) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'For i = ini ... Next') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'For i = ini ... Next') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (WideningValue) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For i = ini ... Next') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: LoopForResult) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i') ILocalReferenceOperation: (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: CounterResult) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i') IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Object, IsImplicit) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Leaving: {R1} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] [B2] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object, IsImplicit) (Syntax: 'result = i') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'result') Right: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'i') Jump if False (Regular) to Block[B3] IInvocationOperation (Function Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl.ForNextCheckObj(Counter As System.Object, LoopObj As System.Object, ByRef CounterResult As System.Object) As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'limit') Instance Receiver: null Arguments(3): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Counter) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'limit') IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Object, IsImplicit) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: LoopObj) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'limit') ILocalReferenceOperation: (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: CounterResult) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'limit') IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Object, IsImplicit) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Leaving: {R1} Next (Regular) Block[B2] } Block[B3] - Exit Predecessors: [B1] [B2] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForToFlow_32() Dim source = <![CDATA[ Imports System Public Class C Sub M(init As Object, limit As Object, [step] as Object, result As Object) 'BIND:"Sub M" For i = init To limit Step [step] result = i Next End Sub End Class ]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [<anonymous local> As System.Object] [i As System.Object] Block[B1] - Block Predecessors: [B0] Statements (0) Jump if False (Regular) to Block[B3] IInvocationOperation (Function Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl.ForLoopInitObj(Counter As System.Object, Start As System.Object, Limit As System.Object, StepValue As System.Object, ByRef LoopForResult As System.Object, ByRef CounterResult As System.Object) As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'limit') Instance Receiver: null Arguments(6): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Counter) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i') ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Start) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'init') IParameterReferenceOperation: init (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'init') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Limit) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'limit') IParameterReferenceOperation: limit (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'limit') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: StepValue) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '[step]') IParameterReferenceOperation: step (OperationKind.ParameterReference, Type: System.Object) (Syntax: '[step]') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: LoopForResult) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i') ILocalReferenceOperation: (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: CounterResult) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i') ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Leaving: {R1} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] [B2] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object, IsImplicit) (Syntax: 'result = i') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'result') Right: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Object) (Syntax: 'i') Jump if False (Regular) to Block[B3] IInvocationOperation (Function Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl.ForNextCheckObj(Counter As System.Object, LoopObj As System.Object, ByRef CounterResult As System.Object) As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'limit') Instance Receiver: null Arguments(3): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Counter) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'limit') ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: LoopObj) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'limit') ILocalReferenceOperation: (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: CounterResult) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'limit') ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Leaving: {R1} Next (Regular) Block[B2] } Block[B3] - Exit Predecessors: [B1] [B2] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForToFlow_33() Dim source = <![CDATA[ Imports System Public Class C Sub M(c1 As C, c2 As C, bInit As Boolean, init1 As Object, init2 As Object, bLimit As Boolean, limit1 As Object, limit2 As Object, bStep As Boolean, step1 As Object, step2 As Object, result As Boolean) 'BIND:"Sub M" For If(c1, c2).i = If(bInit, init1, init2) To If(bLimit, limit1, limit2) Step If(bStep, step1, step2) result = true Next End Sub Public i As Object End Class ]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} {R3} {R4} .locals {R1} { Locals: [<anonymous local> As System.Object] .locals {R2} { CaptureIds: [2] [3] [4] [5] [7] .locals {R3} { CaptureIds: [1] .locals {R4} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C) (Syntax: 'c1') Jump if True (Regular) to Block[B3] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Leaving: {R4} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B4] Leaving: {R4} } Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C) (Syntax: 'c2') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i') Value: IFieldReferenceOperation: C.i As System.Object (OperationKind.FieldReference, Type: System.Object) (Syntax: 'If(c1, c2).i') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)') Next (Regular) Block[B5] Leaving: {R3} } Block[B5] - Block Predecessors: [B4] Statements (0) Jump if False (Regular) to Block[B7] IParameterReferenceOperation: bInit (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bInit') Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init1') Value: IParameterReferenceOperation: init1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'init1') Next (Regular) Block[B8] Block[B7] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init2') Value: IParameterReferenceOperation: init2 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'init2') Next (Regular) Block[B8] Block[B8] - Block Predecessors: [B6] [B7] Statements (0) Jump if False (Regular) to Block[B10] IParameterReferenceOperation: bLimit (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bLimit') Next (Regular) Block[B9] Block[B9] - Block Predecessors: [B8] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit1') Value: IParameterReferenceOperation: limit1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'limit1') Next (Regular) Block[B11] Block[B10] - Block Predecessors: [B8] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit2') Value: IParameterReferenceOperation: limit2 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'limit2') Next (Regular) Block[B11] Block[B11] - Block Predecessors: [B9] [B10] Statements (0) Jump if False (Regular) to Block[B13] IParameterReferenceOperation: bStep (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bStep') Next (Regular) Block[B12] Block[B12] - Block Predecessors: [B11] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'step1') Value: IParameterReferenceOperation: step1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'step1') Next (Regular) Block[B14] Entering: {R5} Block[B13] - Block Predecessors: [B11] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'step2') Value: IParameterReferenceOperation: step2 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'step2') Next (Regular) Block[B14] Entering: {R5} .locals {R5} { CaptureIds: [6] Block[B14] - Block Predecessors: [B12] [B13] Statements (1) IFlowCaptureOperation: 6 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1') Jump if True (Regular) to Block[B16] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Leaving: {R5} Next (Regular) Block[B15] Block[B15] - Block Predecessors: [B14] Statements (1) IFlowCaptureOperation: 7 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B17] Leaving: {R5} } Block[B16] - Block Predecessors: [B14] Statements (1) IFlowCaptureOperation: 7 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2') Next (Regular) Block[B17] Block[B17] - Block Predecessors: [B15] [B16] Statements (0) Jump if False (Regular) to Block[B27] IInvocationOperation (Function Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl.ForLoopInitObj(Counter As System.Object, Start As System.Object, Limit As System.Object, StepValue As System.Object, ByRef LoopForResult As System.Object, ByRef CounterResult As System.Object) As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)') Instance Receiver: null Arguments(6): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Counter) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i') IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'If(c1, c2).i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Start) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'If(bInit, init1, init2)') IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'If(bInit, init1, init2)') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Limit) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)') IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: StepValue) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'If(bStep, step1, step2)') IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'If(bStep, step1, step2)') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: LoopForResult) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i') ILocalReferenceOperation: (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'If(c1, c2).i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: CounterResult) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i') IFieldReferenceOperation: C.i As System.Object (OperationKind.FieldReference, Type: System.Object, IsImplicit) (Syntax: 'If(c1, c2).i') Instance Receiver: IFlowCaptureReferenceOperation: 7 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Leaving: {R2} {R1} Next (Regular) Block[B26] Leaving: {R2} } .locals {R6} { CaptureIds: [10] [12] .locals {R7} { CaptureIds: [9] .locals {R8} { CaptureIds: [8] Block[B18] - Block Predecessors: [B26] Statements (1) IFlowCaptureOperation: 8 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1') Jump if True (Regular) to Block[B20] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 8 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Leaving: {R8} Next (Regular) Block[B19] Block[B19] - Block Predecessors: [B18] Statements (1) IFlowCaptureOperation: 9 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 8 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B21] Leaving: {R8} } Block[B20] - Block Predecessors: [B18] Statements (1) IFlowCaptureOperation: 9 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2') Next (Regular) Block[B21] Block[B21] - Block Predecessors: [B19] [B20] Statements (1) IFlowCaptureOperation: 10 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i') Value: IFieldReferenceOperation: C.i As System.Object (OperationKind.FieldReference, Type: System.Object, IsImplicit) (Syntax: 'If(c1, c2).i') Instance Receiver: IFlowCaptureReferenceOperation: 9 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)') Next (Regular) Block[B22] Leaving: {R7} Entering: {R9} } .locals {R9} { CaptureIds: [11] Block[B22] - Block Predecessors: [B21] Statements (1) IFlowCaptureOperation: 11 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1') Jump if True (Regular) to Block[B24] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 11 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Leaving: {R9} Next (Regular) Block[B23] Block[B23] - Block Predecessors: [B22] Statements (1) IFlowCaptureOperation: 12 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 11 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B25] Leaving: {R9} } Block[B24] - Block Predecessors: [B22] Statements (1) IFlowCaptureOperation: 12 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2') Next (Regular) Block[B25] Block[B25] - Block Predecessors: [B23] [B24] Statements (0) Jump if False (Regular) to Block[B27] IInvocationOperation (Function Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl.ForNextCheckObj(Counter As System.Object, LoopObj As System.Object, ByRef CounterResult As System.Object) As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)') Instance Receiver: null Arguments(3): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Counter) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)') IFlowCaptureReferenceOperation: 10 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'If(c1, c2).i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: LoopObj) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)') ILocalReferenceOperation: (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'If(c1, c2).i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: CounterResult) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)') IFieldReferenceOperation: C.i As System.Object (OperationKind.FieldReference, Type: System.Object, IsImplicit) (Syntax: 'If(c1, c2).i') Instance Receiver: IFlowCaptureReferenceOperation: 12 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Leaving: {R6} {R1} Next (Regular) Block[B26] Leaving: {R6} } Block[B26] - Block Predecessors: [B17] [B25] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = true') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsImplicit) (Syntax: 'result = true') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B18] Entering: {R6} {R7} {R8} } Block[B27] - Exit Predecessors: [B17] [B25] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForToFlow_34() Dim source = <![CDATA[ Imports System Public Class C Sub M(c1 As C, c2 As C, init1 As Object, limit1 As Object, step1 As Object, result As Boolean) 'BIND:"Sub M" For If(c1, c2).i = init1 To limit1 Step step1 result = true Next End Sub Public i As Object End Class ]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} {R3} {R4} .locals {R1} { Locals: [<anonymous local> As System.Object] .locals {R2} { CaptureIds: [2] [3] [4] [5] [7] .locals {R3} { CaptureIds: [1] .locals {R4} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C) (Syntax: 'c1') Jump if True (Regular) to Block[B3] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Leaving: {R4} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B4] Leaving: {R4} } Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C) (Syntax: 'c2') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i') Value: IFieldReferenceOperation: C.i As System.Object (OperationKind.FieldReference, Type: System.Object) (Syntax: 'If(c1, c2).i') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)') Next (Regular) Block[B5] Leaving: {R3} } Block[B5] - Block Predecessors: [B4] Statements (3) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init1') Value: IParameterReferenceOperation: init1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'init1') IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit1') Value: IParameterReferenceOperation: limit1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'limit1') IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'step1') Value: IParameterReferenceOperation: step1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'step1') Next (Regular) Block[B6] Entering: {R5} .locals {R5} { CaptureIds: [6] Block[B6] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 6 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1') Jump if True (Regular) to Block[B8] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Leaving: {R5} Next (Regular) Block[B7] Block[B7] - Block Predecessors: [B6] Statements (1) IFlowCaptureOperation: 7 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B9] Leaving: {R5} } Block[B8] - Block Predecessors: [B6] Statements (1) IFlowCaptureOperation: 7 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2') Next (Regular) Block[B9] Block[B9] - Block Predecessors: [B7] [B8] Statements (0) Jump if False (Regular) to Block[B19] IInvocationOperation (Function Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl.ForLoopInitObj(Counter As System.Object, Start As System.Object, Limit As System.Object, StepValue As System.Object, ByRef LoopForResult As System.Object, ByRef CounterResult As System.Object) As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'limit1') Instance Receiver: null Arguments(6): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Counter) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i') IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'If(c1, c2).i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Start) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'init1') IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'init1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Limit) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'limit1') IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'limit1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: StepValue) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'step1') IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'step1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: LoopForResult) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i') ILocalReferenceOperation: (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'If(c1, c2).i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: CounterResult) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i') IFieldReferenceOperation: C.i As System.Object (OperationKind.FieldReference, Type: System.Object, IsImplicit) (Syntax: 'If(c1, c2).i') Instance Receiver: IFlowCaptureReferenceOperation: 7 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Leaving: {R2} {R1} Next (Regular) Block[B18] Leaving: {R2} } .locals {R6} { CaptureIds: [10] [12] .locals {R7} { CaptureIds: [9] .locals {R8} { CaptureIds: [8] Block[B10] - Block Predecessors: [B18] Statements (1) IFlowCaptureOperation: 8 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1') Jump if True (Regular) to Block[B12] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 8 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Leaving: {R8} Next (Regular) Block[B11] Block[B11] - Block Predecessors: [B10] Statements (1) IFlowCaptureOperation: 9 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 8 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B13] Leaving: {R8} } Block[B12] - Block Predecessors: [B10] Statements (1) IFlowCaptureOperation: 9 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2') Next (Regular) Block[B13] Block[B13] - Block Predecessors: [B11] [B12] Statements (1) IFlowCaptureOperation: 10 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i') Value: IFieldReferenceOperation: C.i As System.Object (OperationKind.FieldReference, Type: System.Object, IsImplicit) (Syntax: 'If(c1, c2).i') Instance Receiver: IFlowCaptureReferenceOperation: 9 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)') Next (Regular) Block[B14] Leaving: {R7} Entering: {R9} } .locals {R9} { CaptureIds: [11] Block[B14] - Block Predecessors: [B13] Statements (1) IFlowCaptureOperation: 11 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1') Jump if True (Regular) to Block[B16] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 11 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Leaving: {R9} Next (Regular) Block[B15] Block[B15] - Block Predecessors: [B14] Statements (1) IFlowCaptureOperation: 12 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 11 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B17] Leaving: {R9} } Block[B16] - Block Predecessors: [B14] Statements (1) IFlowCaptureOperation: 12 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2') Next (Regular) Block[B17] Block[B17] - Block Predecessors: [B15] [B16] Statements (0) Jump if False (Regular) to Block[B19] IInvocationOperation (Function Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl.ForNextCheckObj(Counter As System.Object, LoopObj As System.Object, ByRef CounterResult As System.Object) As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'limit1') Instance Receiver: null Arguments(3): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Counter) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'limit1') IFlowCaptureReferenceOperation: 10 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'If(c1, c2).i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: LoopObj) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'limit1') ILocalReferenceOperation: (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'If(c1, c2).i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: CounterResult) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'limit1') IFieldReferenceOperation: C.i As System.Object (OperationKind.FieldReference, Type: System.Object, IsImplicit) (Syntax: 'If(c1, c2).i') Instance Receiver: IFlowCaptureReferenceOperation: 12 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Leaving: {R6} {R1} Next (Regular) Block[B18] Leaving: {R6} } Block[B18] - Block Predecessors: [B9] [B17] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = true') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsImplicit) (Syntax: 'result = true') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B10] Entering: {R6} {R7} {R8} } Block[B19] - Exit Predecessors: [B9] [B17] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForToFlow_35() Dim source = <![CDATA[ Imports System Public Class C Sub M(i As Object, bInit As Boolean, init1 As Object, init2 As Object, limit1 As Object, step1 As Object, result As Boolean) 'BIND:"Sub M" For i = If(bInit, init1, init2) To limit1 Step step1 result = true Next End Sub End Class ]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous local> As System.Object] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'i') Jump if False (Regular) to Block[B3] IParameterReferenceOperation: bInit (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bInit') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init1') Value: IParameterReferenceOperation: init1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'init1') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init2') Value: IParameterReferenceOperation: init2 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'init2') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (0) Jump if False (Regular) to Block[B6] IInvocationOperation (Function Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl.ForLoopInitObj(Counter As System.Object, Start As System.Object, Limit As System.Object, StepValue As System.Object, ByRef LoopForResult As System.Object, ByRef CounterResult As System.Object) As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'limit1') Instance Receiver: null Arguments(6): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Counter) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i') IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Start) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'If(bInit, init1, init2)') IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'If(bInit, init1, init2)') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Limit) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'limit1') IParameterReferenceOperation: limit1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'limit1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: StepValue) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'step1') IParameterReferenceOperation: step1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'step1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: LoopForResult) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i') ILocalReferenceOperation: (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: CounterResult) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i') IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Object, IsImplicit) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Leaving: {R2} {R1} Next (Regular) Block[B5] Leaving: {R2} } Block[B5] - Block Predecessors: [B4] [B5] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = true') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsImplicit) (Syntax: 'result = true') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Jump if False (Regular) to Block[B6] IInvocationOperation (Function Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl.ForNextCheckObj(Counter As System.Object, LoopObj As System.Object, ByRef CounterResult As System.Object) As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'limit1') Instance Receiver: null Arguments(3): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Counter) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'limit1') IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Object, IsImplicit) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: LoopObj) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'limit1') ILocalReferenceOperation: (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: CounterResult) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'limit1') IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Object, IsImplicit) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Leaving: {R1} Next (Regular) Block[B5] } Block[B6] - Exit Predecessors: [B4] [B5] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForToFlow_36() Dim source = <![CDATA[ Imports System Public Class C Sub M(i As Object, init1 As Object, bLimit As Boolean, limit1 As Object, limit2 As Object, step1 As Object, result As Boolean) 'BIND:"Sub M" For i = init1 To If(bLimit, limit1, limit2) Step step1 result = true Next End Sub End Class ]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous local> As System.Object] .locals {R2} { CaptureIds: [0] [1] [2] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'i') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init1') Value: IParameterReferenceOperation: init1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'init1') Jump if False (Regular) to Block[B3] IParameterReferenceOperation: bLimit (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bLimit') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit1') Value: IParameterReferenceOperation: limit1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'limit1') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit2') Value: IParameterReferenceOperation: limit2 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'limit2') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (0) Jump if False (Regular) to Block[B6] IInvocationOperation (Function Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl.ForLoopInitObj(Counter As System.Object, Start As System.Object, Limit As System.Object, StepValue As System.Object, ByRef LoopForResult As System.Object, ByRef CounterResult As System.Object) As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)') Instance Receiver: null Arguments(6): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Counter) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i') IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Start) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'init1') IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'init1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Limit) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)') IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: StepValue) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'step1') IParameterReferenceOperation: step1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'step1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: LoopForResult) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i') ILocalReferenceOperation: (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: CounterResult) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i') IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Object, IsImplicit) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Leaving: {R2} {R1} Next (Regular) Block[B5] Leaving: {R2} } Block[B5] - Block Predecessors: [B4] [B5] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = true') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsImplicit) (Syntax: 'result = true') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Jump if False (Regular) to Block[B6] IInvocationOperation (Function Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl.ForNextCheckObj(Counter As System.Object, LoopObj As System.Object, ByRef CounterResult As System.Object) As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)') Instance Receiver: null Arguments(3): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Counter) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)') IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Object, IsImplicit) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: LoopObj) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)') ILocalReferenceOperation: (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: CounterResult) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)') IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Object, IsImplicit) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Leaving: {R1} Next (Regular) Block[B5] } Block[B6] - Exit Predecessors: [B4] [B5] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForToFlow_37() Dim source = <![CDATA[ Imports System Public Class C Sub M(i As Object, init1 As Object, limit1 As Object, bStep As Boolean, step1 As Object, step2 As Object, result As Boolean) 'BIND:"Sub M" For i = init1 To limit1 Step If(bStep, step1, step2) result = true Next End Sub End Class ]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous local> As System.Object] .locals {R2} { CaptureIds: [0] [1] [2] [3] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'i') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init1') Value: IParameterReferenceOperation: init1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'init1') IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit1') Value: IParameterReferenceOperation: limit1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'limit1') Jump if False (Regular) to Block[B3] IParameterReferenceOperation: bStep (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bStep') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'step1') Value: IParameterReferenceOperation: step1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'step1') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'step2') Value: IParameterReferenceOperation: step2 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'step2') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (0) Jump if False (Regular) to Block[B6] IInvocationOperation (Function Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl.ForLoopInitObj(Counter As System.Object, Start As System.Object, Limit As System.Object, StepValue As System.Object, ByRef LoopForResult As System.Object, ByRef CounterResult As System.Object) As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'limit1') Instance Receiver: null Arguments(6): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Counter) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i') IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Start) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'init1') IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'init1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Limit) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'limit1') IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'limit1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: StepValue) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'If(bStep, step1, step2)') IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'If(bStep, step1, step2)') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: LoopForResult) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i') ILocalReferenceOperation: (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: CounterResult) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i') IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Object, IsImplicit) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Leaving: {R2} {R1} Next (Regular) Block[B5] Leaving: {R2} } Block[B5] - Block Predecessors: [B4] [B5] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = true') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsImplicit) (Syntax: 'result = true') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Jump if False (Regular) to Block[B6] IInvocationOperation (Function Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl.ForNextCheckObj(Counter As System.Object, LoopObj As System.Object, ByRef CounterResult As System.Object) As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'limit1') Instance Receiver: null Arguments(3): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Counter) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'limit1') IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Object, IsImplicit) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: LoopObj) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'limit1') ILocalReferenceOperation: (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: CounterResult) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'limit1') IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Object, IsImplicit) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Leaving: {R1} Next (Regular) Block[B5] } Block[B6] - Exit Predecessors: [B4] [B5] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForToFlow_38() Dim source = <![CDATA[ Imports System Public Class C Sub M(i As Object, init As Object, limit As Object, result As Object) 'BIND:"Sub M" For i = init To limit result = i Next End Sub End Class ]]>.Value Dim compilation = CreateCompilationWithMscorlib45(source, options:=TestOptions.ReleaseDebugDll) Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [<anonymous local> As System.Object] Block[B1] - Block Predecessors: [B0] Statements (0) Jump if False (Regular) to Block[B3] IInvalidOperation (OperationKind.Invalid, Type: System.Boolean, IsImplicit) (Syntax: 'limit') Children(5): IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'i') IParameterReferenceOperation: init (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'init') IParameterReferenceOperation: limit (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'limit') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'For i = ini ... Next') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (WideningValue) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For i = ini ... Next') ILocalReferenceOperation: (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'i') Leaving: {R1} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] [B2] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object, IsImplicit) (Syntax: 'result = i') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'result') Right: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'i') Jump if False (Regular) to Block[B3] IInvalidOperation (OperationKind.Invalid, Type: System.Boolean, IsImplicit) (Syntax: 'limit') Children(2): IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Object, IsImplicit) (Syntax: 'i') ILocalReferenceOperation: (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'i') Leaving: {R1} Next (Regular) Block[B2] } Block[B3] - Exit Predecessors: [B1] [B2] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(compilation, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForToFlow_39() Dim source = <![CDATA[ Imports System Public Class C Sub M(i As Integer?, init As Integer?, limit As Integer?, [step] As Integer?, result As Integer?) 'BIND:"Sub M" For i = init To limit Step [step] result = i Next End Sub End Class ]]>.Value Dim compilation = CreateCompilationWithMscorlib45(source, options:=TestOptions.ReleaseDebugDll) compilation.MakeMemberMissing(SpecialMember.System_Nullable_T_GetValueOrDefault) Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [2] [3] [4] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (4) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'i') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init') Value: IParameterReferenceOperation: init (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'init') IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit') Value: IParameterReferenceOperation: limit (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'limit') IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '[step]') Value: IParameterReferenceOperation: step (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: '[step]') Jump if False (Regular) to Block[B3] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: '[step]') Operand: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: '[step]') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '[step]') Value: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False, IsImplicit) (Syntax: '[step]') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '[step]') Value: IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '[step]') Left: IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsImplicit) (Syntax: '[step]') Children(1): IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: '[step]') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: '[step]') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'init') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'init') Next (Regular) Block[B5] Leaving: {R2} } Block[B5] - Block Predecessors: [B4] [B11] [B12] Statements (0) Jump if False (Regular) to Block[B6] IBinaryOperation (BinaryOperatorKind.Or) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '[step]') Left: IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'limit') Operand: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'limit') Right: IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'i') Operand: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i') Entering: {R3} Next (Regular) Block[B13] Leaving: {R1} .locals {R3} { CaptureIds: [5] Block[B6] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsImplicit) (Syntax: 'i') Children(1): IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i') Jump if False (Regular) to Block[B8] IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: '[step]') Next (Regular) Block[B7] Block[B7] - Block Predecessors: [B6] Statements (0) Jump if False (Regular) to Block[B13] IBinaryOperation (BinaryOperatorKind.LessThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'limit') Left: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i') Right: IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsImplicit) (Syntax: 'limit') Children(1): IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'limit') Leaving: {R3} {R1} Next (Regular) Block[B9] Leaving: {R3} Block[B8] - Block Predecessors: [B6] Statements (0) Jump if False (Regular) to Block[B13] IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'limit') Left: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i') Right: IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsImplicit) (Syntax: 'limit') Children(1): IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'limit') Leaving: {R3} {R1} Next (Regular) Block[B9] Leaving: {R3} } Block[B9] - Block Predecessors: [B7] [B8] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'result = i') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'result') Right: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'i') Next (Regular) Block[B10] Entering: {R4} .locals {R4} { CaptureIds: [6] Block[B10] - Block Predecessors: [B9] Statements (1) IFlowCaptureOperation: 6 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i') Jump if False (Regular) to Block[B12] IBinaryOperation (BinaryOperatorKind.Or) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '[step]') Left: IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: '[step]') Operand: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: '[step]') Right: IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'i') Operand: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i') Next (Regular) Block[B11] Block[B11] - Block Predecessors: [B10] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'i') Left: IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i') Right: IDefaultValueOperation (OperationKind.DefaultValue, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i') Next (Regular) Block[B5] Leaving: {R4} Block[B12] - Block Predecessors: [B10] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'i') Left: IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: '[step]') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (WideningNullable) Operand: IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32, IsImplicit) (Syntax: '[step]') Left: IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsImplicit) (Syntax: 'i') Children(1): IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i') Right: IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsImplicit) (Syntax: '[step]') Children(1): IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: '[step]') Next (Regular) Block[B5] Leaving: {R4} } } Block[B13] - Exit Predecessors: [B5] [B7] [B8] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(compilation, expectedFlowGraph, expectedDiagnostics) End Sub End Class End Namespace
' 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.Operations Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Partial Public Class IOperationTests Inherits SemanticModelTestBase <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")> Public Sub IForLoopStatement_SimpleForLoopsTest() Dim source = <![CDATA[ Public Class MyClass1 Public Shared Sub Main() Dim myarray As Integer() = New Integer(2) {1, 2, 3} For i As Integer = 0 To myarray.Length - 1'BIND:"For i As Integer = 0 To myarray.Length - 1" System.Console.WriteLine(myarray(i)) Next End Sub End Class ]]>.Value Dim expectedOperationTree = <![CDATA[ IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For i As In ... Next') Locals: Local_1: i As System.Int32 LoopControlVariable: IVariableDeclaratorOperation (Symbol: i As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i As Integer') Initializer: null InitialValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') LimitValue: IBinaryOperation (BinaryOperatorKind.Subtract, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: 'myarray.Length - 1') Left: IPropertyReferenceOperation: ReadOnly Property System.Array.Length As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'myarray.Length') Instance Receiver: ILocalReferenceOperation: myarray (OperationKind.LocalReference, Type: System.Int32()) (Syntax: 'myarray') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') StepValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For i As In ... Next') Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For i As In ... Next') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For i As In ... Next') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... myarray(i))') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Int32)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... myarray(i))') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'myarray(i)') IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.Int32) (Syntax: 'myarray(i)') Array reference: ILocalReferenceOperation: myarray (OperationKind.LocalReference, Type: System.Int32()) (Syntax: 'myarray') Indices(1): ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) NextVariables(0) ]]>.Value VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")> Public Sub IForLoopStatement_SimpleForLoopsTestConversion() Dim source = <![CDATA[ Option Strict Off Public Class MyClass1 Public Shared Sub Main() Dim myarray As Integer() = New Integer(1) {} myarray(0) = 1 myarray(1) = 2 Dim s As Double = 1.1 For i As Integer = 0 To "1" Step s'BIND:"For i As Integer = 0 To "1" Step s" System.Console.WriteLine(myarray(i)) Next End Sub End Class ]]>.Value Dim expectedOperationTree = <![CDATA[ IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'For i As In ... Next') Locals: Local_1: i As System.Int32 LoopControlVariable: IVariableDeclaratorOperation (Symbol: i As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i As Integer') Initializer: null InitialValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') LimitValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: '"1"') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "1") (Syntax: '"1"') StepValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: 's') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: s (OperationKind.LocalReference, Type: System.Double) (Syntax: 's') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For i As In ... Next') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... myarray(i))') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Int32)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... myarray(i))') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'myarray(i)') IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.Int32) (Syntax: 'myarray(i)') Array reference: ILocalReferenceOperation: myarray (OperationKind.LocalReference, Type: System.Int32()) (Syntax: 'myarray') Indices(1): ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) NextVariables(0) ]]>.Value VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree, TestOptions.ReleaseDll.WithOverflowChecks(False)) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")> Public Sub IForLoopStatement_ForLoopStepIsFloatNegativeVar() Dim source = <![CDATA[ Option Strict On Public Class MyClass1 Public Shared Sub Main() Dim s As Double = -1.1 For i As Double = 2 To 0 Step s'BIND:"For i As Double = 2 To 0 Step s" System.Console.WriteLine(i) Next End Sub End Class ]]>.Value Dim expectedOperationTree = <![CDATA[ IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For i As Do ... Next') Locals: Local_1: i As System.Double LoopControlVariable: IVariableDeclaratorOperation (Symbol: i As System.Double) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i As Double') Initializer: null InitialValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Double, Constant: 2, IsImplicit) (Syntax: '2') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') LimitValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Double, Constant: 0, IsImplicit) (Syntax: '0') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') StepValue: ILocalReferenceOperation: s (OperationKind.LocalReference, Type: System.Double) (Syntax: 's') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For i As Do ... Next') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... riteLine(i)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Double)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... riteLine(i)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'i') ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Double) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) NextVariables(0) ]]>.Value VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")> Public Sub IForLoopStatement_ForLoopObject() Dim source = <![CDATA[ Option Strict On Public Class MyClass1 Public Shared Sub Main() Dim ctrlVar As Object Dim initValue As Object = 0 Dim limit As Object = 2 Dim stp As Object = 1 For ctrlVar = initValue To limit Step stp'BIND:"For ctrlVar = initValue To limit Step stp" System.Console.WriteLine(ctrlVar) Next End Sub End Class ]]>.Value Dim expectedOperationTree = <![CDATA[ IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For ctrlVar ... Next') LoopControlVariable: ILocalReferenceOperation: ctrlVar (OperationKind.LocalReference, Type: System.Object) (Syntax: 'ctrlVar') InitialValue: ILocalReferenceOperation: initValue (OperationKind.LocalReference, Type: System.Object) (Syntax: 'initValue') LimitValue: ILocalReferenceOperation: limit (OperationKind.LocalReference, Type: System.Object) (Syntax: 'limit') StepValue: ILocalReferenceOperation: stp (OperationKind.LocalReference, Type: System.Object) (Syntax: 'stp') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For ctrlVar ... Next') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... ne(ctrlVar)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Object)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... ne(ctrlVar)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'ctrlVar') ILocalReferenceOperation: ctrlVar (OperationKind.LocalReference, Type: System.Object) (Syntax: 'ctrlVar') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) NextVariables(0) ]]>.Value VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")> Public Sub IForLoopStatement_ForLoopNested() Dim source = <![CDATA[ Option Strict On Option Infer On Public Class MyClass1 Public Shared Sub Main() For AVarName = 1 To 2'BIND:"For AVarName = 1 To 2" For B = 1 To 2 For C = 1 To 2 For D = 1 To 2 Next D Next C Next B Next AVarName End Sub End Class ]]>.Value Dim expectedOperationTree = <![CDATA[ IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For AVarNam ... xt AVarName') Locals: Local_1: AVarName As System.Int32 LoopControlVariable: IVariableDeclaratorOperation (Symbol: AVarName As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'AVarName') Initializer: null InitialValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') LimitValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') StepValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For AVarNam ... xt AVarName') Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For AVarNam ... xt AVarName') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For AVarNam ... xt AVarName') IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 2, Exit Label Id: 3, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For B = 1 T ... Next B') Locals: Local_1: B As System.Int32 LoopControlVariable: IVariableDeclaratorOperation (Symbol: B As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'B') Initializer: null InitialValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') LimitValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') StepValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For B = 1 T ... Next B') Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For B = 1 T ... Next B') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For B = 1 T ... Next B') IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 4, Exit Label Id: 5, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For C = 1 T ... Next C') Locals: Local_1: C As System.Int32 LoopControlVariable: IVariableDeclaratorOperation (Symbol: C As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'C') Initializer: null InitialValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') LimitValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') StepValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For C = 1 T ... Next C') Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For C = 1 T ... Next C') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For C = 1 T ... Next C') IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 6, Exit Label Id: 7, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For D = 1 T ... Next D') Locals: Local_1: D As System.Int32 LoopControlVariable: IVariableDeclaratorOperation (Symbol: D As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'D') Initializer: null InitialValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') LimitValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') StepValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For D = 1 T ... Next D') Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For D = 1 T ... Next D') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For D = 1 T ... Next D') NextVariables(1): ILocalReferenceOperation: D (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'D') NextVariables(1): ILocalReferenceOperation: C (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'C') NextVariables(1): ILocalReferenceOperation: B (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'B') NextVariables(1): ILocalReferenceOperation: AVarName (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'AVarName') ]]>.Value VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")> Public Sub IForLoopStatement_ChangeOuterVarInInnerFor() Dim source = <![CDATA[ Option Strict On Option Infer On Public Class MyClass1 Public Shared Sub Main() For I = 1 To 2'BIND:"For I = 1 To 2" For J = 1 To 2 I = 3 System.Console.WriteLine(I) Next Next End Sub End Class ]]>.Value Dim expectedOperationTree = <![CDATA[ IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For I = 1 T ... Next') Locals: Local_1: I As System.Int32 LoopControlVariable: IVariableDeclaratorOperation (Symbol: I As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'I') Initializer: null InitialValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') LimitValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') StepValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For I = 1 T ... Next') Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For I = 1 T ... Next') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For I = 1 T ... Next') IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 2, Exit Label Id: 3, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For J = 1 T ... Next') Locals: Local_1: J As System.Int32 LoopControlVariable: IVariableDeclaratorOperation (Symbol: J As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'J') Initializer: null InitialValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') LimitValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') StepValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For J = 1 T ... Next') Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For J = 1 T ... Next') Body: IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For J = 1 T ... Next') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'I = 3') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'I = 3') Left: ILocalReferenceOperation: I (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'I') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... riteLine(I)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Int32)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... riteLine(I)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'I') ILocalReferenceOperation: I (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'I') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) NextVariables(0) NextVariables(0) ]]>.Value VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")> Public Sub IForLoopStatement_InnerForRefOuterForVar() Dim source = <![CDATA[ Option Strict On Option Infer On Public Class MyClass1 Public Shared Sub Main() For I = 1 To 2'BIND:"For I = 1 To 2" For J = I + 1 To 2 System.Console.WriteLine(J) Next Next End Sub End Class ]]>.Value Dim expectedOperationTree = <![CDATA[ IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For I = 1 T ... Next') Locals: Local_1: I As System.Int32 LoopControlVariable: IVariableDeclaratorOperation (Symbol: I As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'I') Initializer: null InitialValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') LimitValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') StepValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For I = 1 T ... Next') Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For I = 1 T ... Next') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For I = 1 T ... Next') IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 2, Exit Label Id: 3, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For J = I + ... Next') Locals: Local_1: J As System.Int32 LoopControlVariable: IVariableDeclaratorOperation (Symbol: J As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'J') Initializer: null InitialValue: IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: 'I + 1') Left: ILocalReferenceOperation: I (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'I') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') LimitValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') StepValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For J = I + ... Next') Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For J = I + ... Next') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For J = I + ... Next') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... riteLine(J)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Int32)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... riteLine(J)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'J') ILocalReferenceOperation: J (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'J') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) NextVariables(0) NextVariables(0) ]]>.Value VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")> Public Sub IForLoopStatement_ExitNestedFor() Dim source = <![CDATA[ Option Strict On Option Infer On Public Class MyClass1 Public Shared Sub Main() For I = 1 To 2'BIND:"For I = 1 To 2" For J = 1 To 2 Exit For Next System.Console.WriteLine(I) Next End Sub End Class ]]>.Value Dim expectedOperationTree = <![CDATA[ IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For I = 1 T ... Next') Locals: Local_1: I As System.Int32 LoopControlVariable: IVariableDeclaratorOperation (Symbol: I As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'I') Initializer: null InitialValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') LimitValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') StepValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For I = 1 T ... Next') Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For I = 1 T ... Next') Body: IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For I = 1 T ... Next') IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 2, Exit Label Id: 3, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For J = 1 T ... Next') Locals: Local_1: J As System.Int32 LoopControlVariable: IVariableDeclaratorOperation (Symbol: J As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'J') Initializer: null InitialValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') LimitValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') StepValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For J = 1 T ... Next') Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For J = 1 T ... Next') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For J = 1 T ... Next') IBranchOperation (BranchKind.Break, Label Id: 3) (OperationKind.Branch, Type: null) (Syntax: 'Exit For') NextVariables(0) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... riteLine(I)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Int32)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... riteLine(I)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'I') ILocalReferenceOperation: I (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'I') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) NextVariables(0) ]]>.Value VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")> Public Sub IForLoopStatement_EnumAsStart() Dim source = <![CDATA[ Option Strict Off Option Infer Off Public Class MyClass1 Public Shared Sub Main() For x As e1 = e1.a To e1.c'BIND:"For x As e1 = e1.a To e1.c" Next End Sub End Class Enum e1 a b c End Enum ]]>.Value Dim expectedOperationTree = <![CDATA[ IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For x As e1 ... Next') Locals: Local_1: x As e1 LoopControlVariable: IVariableDeclaratorOperation (Symbol: x As e1) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x As e1') Initializer: null InitialValue: IFieldReferenceOperation: e1.a (Static) (OperationKind.FieldReference, Type: e1, Constant: 0) (Syntax: 'e1.a') Instance Receiver: null LimitValue: IFieldReferenceOperation: e1.c (Static) (OperationKind.FieldReference, Type: e1, Constant: 2) (Syntax: 'e1.c') Instance Receiver: null StepValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: e1, Constant: 1, IsImplicit) (Syntax: 'For x As e1 ... Next') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For x As e1 ... Next') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For x As e1 ... Next') NextVariables(0) ]]>.Value VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")> Public Sub IForLoopStatement_PropertyAsStart() Dim source = <![CDATA[ Option Strict Off Option Infer Off Public Class MyClass1 Property P1(ByVal x As Long) As Byte Get Return x - 10 End Get Set(ByVal Value As Byte) End Set End Property Public Shared Sub Main() End Sub Public Sub F() For i As Integer = P1(30 + i) To 30'BIND:"For i As Integer = P1(30 + i) To 30" Next End Sub End Class ]]>.Value Dim expectedOperationTree = <![CDATA[ IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For i As In ... Next') Locals: Local_1: i As System.Int32 LoopControlVariable: IVariableDeclaratorOperation (Symbol: i As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i As Integer') Initializer: null InitialValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: 'P1(30 + i)') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IPropertyReferenceOperation: Property MyClass1.P1(x As System.Int64) As System.Byte (OperationKind.PropertyReference, Type: System.Byte) (Syntax: 'P1(30 + i)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: MyClass1, IsImplicit) (Syntax: 'P1') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: '30 + i') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int64, IsImplicit) (Syntax: '30 + i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: '30 + i') Left: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 30) (Syntax: '30') Right: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) LimitValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 30) (Syntax: '30') StepValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For i As In ... Next') Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For i As In ... Next') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For i As In ... Next') NextVariables(0) ]]>.Value VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")> Public Sub IForLoopStatement_FieldNameAsIteration() Dim source = <![CDATA[ Option Strict Off Option Infer On Public Class MyClass1 Dim global_x As Integer = 10 Const global_y As Long = 20 Public Shared Sub Main() For global_x As Integer = global_y To 10'BIND:"For global_x As Integer = global_y To 10" Next End Sub End Class ]]>.Value Dim expectedOperationTree = <![CDATA[ IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For global_ ... Next') Locals: Local_1: global_x As System.Int32 LoopControlVariable: IVariableDeclaratorOperation (Symbol: global_x As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'global_x As Integer') Initializer: null InitialValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 20, IsImplicit) (Syntax: 'global_y') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IFieldReferenceOperation: MyClass1.global_y As System.Int64 (Static) (OperationKind.FieldReference, Type: System.Int64, Constant: 20) (Syntax: 'global_y') Instance Receiver: null LimitValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') StepValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For global_ ... Next') Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For global_ ... Next') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For global_ ... Next') NextVariables(0) ]]>.Value VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")> Public Sub IForLoopStatement_SingleLine() Dim source = <![CDATA[ Option Strict On Public Class MyClass1 Public Shared Sub Main() For x As Integer = 0 To 10 : Next'BIND:"For x As Integer = 0 To 10 : Next" End Sub End Class ]]>.Value Dim expectedOperationTree = <![CDATA[ IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For x As In ... o 10 : Next') Locals: Local_1: x As System.Int32 LoopControlVariable: IVariableDeclaratorOperation (Symbol: x As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x As Integer') Initializer: null InitialValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') LimitValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') StepValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For x As In ... o 10 : Next') Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For x As In ... o 10 : Next') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For x As In ... o 10 : Next') NextVariables(0) ]]>.Value VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")> Public Sub IForLoopStatement_VarDeclOutOfForeach() Dim source = <![CDATA[ Option Strict On Option Infer On Public Class MyClass1 Public Shared Sub Main() Dim Y As Integer For Y = 1 To 2'BIND:"For Y = 1 To 2" Next End Sub End Class ]]>.Value Dim expectedOperationTree = <![CDATA[ IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For Y = 1 T ... Next') LoopControlVariable: ILocalReferenceOperation: Y (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'Y') InitialValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') LimitValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') StepValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For Y = 1 T ... Next') Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For Y = 1 T ... Next') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Y = 1 T ... Next') NextVariables(0) ]]>.Value VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")> Public Sub IForLoopStatement_GetDeclaredSymbolOfForStatement() Dim source = <![CDATA[ Option Strict On Option Infer On Imports System Imports System.Collection Class C1 Public Shared Sub Main() For element1 = 23 To 42'BIND:"For element1 = 23 To 42" Next For element2 As Integer = 23 To 42 Next End Sub End Class ]]>.Value Dim expectedOperationTree = <![CDATA[ IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For element ... Next') Locals: Local_1: element1 As System.Int32 LoopControlVariable: IVariableDeclaratorOperation (Symbol: element1 As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'element1') Initializer: null InitialValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 23) (Syntax: '23') LimitValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 42) (Syntax: '42') StepValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For element ... Next') Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For element ... Next') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For element ... Next') NextVariables(0) ]]>.Value VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")> Public Sub IForLoopStatement_ForLoopContinue() Dim source = <![CDATA[ Option Strict On Option Infer On Imports System Imports System.Collection Class C1 Public Shared Sub Main() For i As Integer = 0 To 5'BIND:"For i As Integer = 0 To 5" If i Mod 2 = 0 Then Continue For End If Next End Sub End Class ]]>.Value Dim expectedOperationTree = <![CDATA[ IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For i As In ... Next') Locals: Local_1: i As System.Int32 LoopControlVariable: IVariableDeclaratorOperation (Symbol: i As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i As Integer') Initializer: null InitialValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') LimitValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') StepValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For i As In ... Next') Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For i As In ... Next') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For i As In ... Next') IConditionalOperation (OperationKind.Conditional, Type: null) (Syntax: 'If i Mod 2 ... End If') Condition: IBinaryOperation (BinaryOperatorKind.Equals, Checked) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'i Mod 2 = 0') Left: IBinaryOperation (BinaryOperatorKind.Remainder, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: 'i Mod 2') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') WhenTrue: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'If i Mod 2 ... End If') IBranchOperation (BranchKind.Continue, Label Id: 0) (OperationKind.Branch, Type: null) (Syntax: 'Continue For') WhenFalse: null NextVariables(0) ]]>.Value VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")> Public Sub IForLoopStatement_ForReverse() Dim source = <![CDATA[ Option Infer On Module Program Sub Main() For X = 10 To 0'BIND:"For X = 10 To 0" Next End Sub End Module Module M Public X As Integer End Module ]]>.Value Dim expectedOperationTree = <![CDATA[ IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For X = 10 ... Next') LoopControlVariable: IFieldReferenceOperation: M.X As System.Int32 (Static) (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'X') Instance Receiver: null InitialValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') LimitValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') StepValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For X = 10 ... Next') Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For X = 10 ... Next') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For X = 10 ... Next') NextVariables(0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of ForBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")> Public Sub IForLoopStatement_InValid() Dim source = <![CDATA[ Option Infer On Module Program Sub Main() For X = 10 To 0'BIND:"For X = 10 To 0" Next End Sub End Module Module M Public X As String End Module ]]>.Value Dim expectedOperationTree = <![CDATA[ IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null, IsInvalid) (Syntax: 'For X = 10 ... Next') LoopControlVariable: IFieldReferenceOperation: M.X As System.String (Static) (OperationKind.FieldReference, Type: System.String, IsInvalid) (Syntax: 'X') Instance Receiver: null InitialValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') LimitValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') StepValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid, IsImplicit) (Syntax: 'For X = 10 ... Next') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'For X = 10 ... Next') NextVariables(0) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30337: 'For' loop control variable cannot be of type 'String' because the type does not support the required operators. For X = 10 To 0'BIND:"For X = 10 To 0" ~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of ForBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")> Public Sub IForLoopStatement_ForCombined() Dim source = <![CDATA[ Option Infer On Module Program Sub Main(args As String()) For A = 1 To 2'BIND:"For A = 1 To 2" For B = A To 2 Next B, A End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For A = 1 T ... Next B, A') Locals: Local_1: A As System.Int32 LoopControlVariable: IVariableDeclaratorOperation (Symbol: A As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'A') Initializer: null InitialValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') LimitValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') StepValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For A = 1 T ... Next B, A') Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For A = 1 T ... Next B, A') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For A = 1 T ... Next B, A') IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 2, Exit Label Id: 3, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For B = A T ... Next B, A') Locals: Local_1: B As System.Int32 LoopControlVariable: IVariableDeclaratorOperation (Symbol: B As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'B') Initializer: null InitialValue: ILocalReferenceOperation: A (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'A') LimitValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') StepValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For B = A T ... Next B, A') Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For B = A T ... Next B, A') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For B = A T ... Next B, A') NextVariables(2): ILocalReferenceOperation: B (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'B') ILocalReferenceOperation: A (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'A') NextVariables(0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of ForBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub VerifyForToLoop1() Dim source = <![CDATA[ Structure C Sub F() Dim x As Integer Dim y As Integer = 16 For x = 12 To y 'BIND:"For x = 12 To y" Next End Sub End Structure ]]>.Value Dim expectedOperationTree = <![CDATA[ IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For x = 12 ... Next') LoopControlVariable: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x') InitialValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 12) (Syntax: '12') LimitValue: ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'y') StepValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For x = 12 ... Next') Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For x = 12 ... Next') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For x = 12 ... Next') NextVariables(0) ]]>.Value VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub VerifyForToLoop2() Dim source = <![CDATA[ Structure C Sub F() Dim x As Integer? Dim y As Integer = 16 For x = 12 To y 'BIND:"For x = 12 To y" Next End Sub End Structure ]]>.Value Dim expectedOperationTree = <![CDATA[ IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For x = 12 ... Next') LoopControlVariable: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'x') InitialValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: '12') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 12) (Syntax: '12') LimitValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'y') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'y') StepValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'For x = 12 ... Next') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For x = 12 ... Next') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For x = 12 ... Next') NextVariables(0) ]]>.Value VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub VerifyForToLoop3() Dim source = <![CDATA[ Structure C Sub F() Dim x As Integer Dim y As Integer? = 16 For x = 12 To y 'BIND:"For x = 12 To y" Next End Sub End Structure ]]>.Value Dim expectedOperationTree = <![CDATA[ IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For x = 12 ... Next') LoopControlVariable: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x') InitialValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 12) (Syntax: '12') LimitValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: 'y') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'y') StepValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For x = 12 ... Next') Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For x = 12 ... Next') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For x = 12 ... Next') NextVariables(0) ]]>.Value VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub VerifyForToLoop4() Dim source = <![CDATA[ Structure C Sub F() Dim x As Integer? Dim y As Integer? = 16 For x = 12 To y 'BIND:"For x = 12 To y" Next End Sub End Structure ]]>.Value Dim expectedOperationTree = <![CDATA[ IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For x = 12 ... Next') LoopControlVariable: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'x') InitialValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: '12') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 12) (Syntax: '12') LimitValue: ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'y') StepValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'For x = 12 ... Next') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For x = 12 ... Next') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For x = 12 ... Next') NextVariables(0) ]]>.Value VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub VerifyForToLoop5() Dim source = <![CDATA[ Structure C Sub F() Dim x As Integer Dim y As Integer = 16 Dim s As Integer? = nothing For x = 12 To y Step s 'BIND:"For x = 12 To y Step s" Next End Sub End Structure ]]>.Value Dim expectedOperationTree = <![CDATA[ IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For x = 12 ... Next') LoopControlVariable: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x') InitialValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 12) (Syntax: '12') LimitValue: ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'y') StepValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: 's') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: s (OperationKind.LocalReference, Type: System.Nullable(Of System.Int32)) (Syntax: 's') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For x = 12 ... Next') NextVariables(0) ]]>.Value VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub VerifyForToLoop6() Dim source = <![CDATA[ Structure C Sub F() Dim x As Integer? Dim y As Integer = 16 Dim s As Integer? = nothing For x = 12 To y Step s 'BIND:"For x = 12 To y Step s" Next End Sub End Structure ]]>.Value Dim expectedOperationTree = <![CDATA[ IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For x = 12 ... Next') LoopControlVariable: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'x') InitialValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: '12') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 12) (Syntax: '12') LimitValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'y') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'y') StepValue: ILocalReferenceOperation: s (OperationKind.LocalReference, Type: System.Nullable(Of System.Int32)) (Syntax: 's') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For x = 12 ... Next') NextVariables(0) ]]>.Value VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub VerifyForToLoop7() Dim source = <![CDATA[ Structure C Sub F() Dim x As Integer Dim y As Integer? = 16 Dim s As Integer? = nothing For x = 12 To y Step s 'BIND:"For x = 12 To y Step s" Next End Sub End Structure ]]>.Value Dim expectedOperationTree = <![CDATA[ IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For x = 12 ... Next') LoopControlVariable: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x') InitialValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 12) (Syntax: '12') LimitValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: 'y') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'y') StepValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: 's') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: s (OperationKind.LocalReference, Type: System.Nullable(Of System.Int32)) (Syntax: 's') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For x = 12 ... Next') NextVariables(0) ]]>.Value VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub VerifyForToLoop8() Dim source = <![CDATA[ Structure C Sub F() Dim x As Integer? Dim y As Integer? = 16 Dim s As Integer? = nothing For x = 12 To y Step s 'BIND:"For x = 12 To y Step s" Next End Sub End Structure ]]>.Value Dim expectedOperationTree = <![CDATA[ IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For x = 12 ... Next') LoopControlVariable: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'x') InitialValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: '12') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 12) (Syntax: '12') LimitValue: ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'y') StepValue: ILocalReferenceOperation: s (OperationKind.LocalReference, Type: System.Nullable(Of System.Int32)) (Syntax: 's') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For x = 12 ... Next') NextVariables(0) ]]>.Value VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub VerifyForToLoop_FieldAsIterationVariable() Dim source = <![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Class C Private X As Integer = 0 Sub M() For X = 0 To 10'BIND:"For X = 0 To 10" Next X End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For X = 0 T ... Next X') LoopControlVariable: IFieldReferenceOperation: C.X As System.Int32 (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'X') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'X') InitialValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') LimitValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') StepValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For X = 0 T ... Next X') Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For X = 0 T ... Next X') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For X = 0 T ... Next X') NextVariables(1): IFieldReferenceOperation: C.X As System.Int32 (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'X') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'X') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of ForBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub VerifyForToLoop_FieldWithExplicitReceiverAsIterationVariable() Dim source = <![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Class C Private X As Integer = 0 Sub M(c As C) For c.X = 0 To 10'BIND:"For c.X = 0 To 10" Next c.X End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For c.X = 0 ... Next c.X') LoopControlVariable: IFieldReferenceOperation: C.X As System.Int32 (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'c.X') Instance Receiver: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c') InitialValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') LimitValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') StepValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For c.X = 0 ... Next c.X') Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For c.X = 0 ... Next c.X') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For c.X = 0 ... Next c.X') NextVariables(1): IFieldReferenceOperation: C.X As System.Int32 (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'c.X') Instance Receiver: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of ForBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub VerifyForToLoop_InvalidLoopControlVariableDeclaration() Dim source = <![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Class C Sub M() Dim i as Integer = 0 For i as Integer = 0 To 10'BIND:"For i as Integer = 0 To 10" Next i End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null, IsInvalid) (Syntax: 'For i as In ... Next i') Locals: Local_1: i As System.Int32 LoopControlVariable: IVariableDeclaratorOperation (Symbol: i As System.Int32) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'i as Integer') Initializer: null InitialValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') LimitValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') StepValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsInvalid, IsImplicit) (Syntax: 'For i as In ... Next i') Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid, IsImplicit) (Syntax: 'For i as In ... Next i') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'For i as In ... Next i') NextVariables(1): ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30616: Variable 'i' hides a variable in an enclosing block. For i as Integer = 0 To 10'BIND:"For i as Integer = 0 To 10" ~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of ForBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForToFlow_01() Dim source = <![CDATA[ Imports System Public Class C Sub M(result As Integer) 'BIND:"Sub M" For i As UInteger = 0UI To 2UI result = if(i > 0UI, 3, 4) Next End Sub End Class]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [i As System.UInt32] CaptureIds: [2] [3] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (5) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i As UInteger') Value: ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.UInt32, IsImplicit) (Syntax: 'i As UInteger') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '0UI') Value: ILiteralOperation (OperationKind.Literal, Type: System.UInt32, Constant: 0) (Syntax: '0UI') IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '2UI') Value: ILiteralOperation (OperationKind.Literal, Type: System.UInt32, Constant: 2) (Syntax: '2UI') IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'For i As UI ... Next') Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.UInt32, Constant: 1, IsImplicit) (Syntax: 'For i As UI ... Next') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (WideningNumeric, InvolvesNarrowingFromNumericConstant) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For i As UI ... Next') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: '0UI') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.UInt32, IsImplicit) (Syntax: 'i As UInteger') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.UInt32, Constant: 0, IsImplicit) (Syntax: '0UI') Next (Regular) Block[B2] Leaving: {R2} } Block[B2] - Block Predecessors: [B1] [B7] Statements (0) Jump if False (Regular) to Block[B8] IBinaryOperation (BinaryOperatorKind.LessThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '2UI') Left: ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.UInt32, IsImplicit) (Syntax: 'i As UInteger') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.UInt32, Constant: 2, IsImplicit) (Syntax: '2UI') Leaving: {R1} Next (Regular) Block[B3] Entering: {R3} .locals {R3} { CaptureIds: [4] [5] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result') Value: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result') Jump if False (Regular) to Block[B5] IBinaryOperation (BinaryOperatorKind.GreaterThan, Checked) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'i > 0UI') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.UInt32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.UInt32, Constant: 0) (Syntax: '0UI') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B3] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '3') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') Next (Regular) Block[B6] Block[B5] - Block Predecessors: [B3] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '4') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4') Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B4] [B5] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = if ... 0UI, 3, 4)') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'result = if ... 0UI, 3, 4)') Left: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'result') Right: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'if(i > 0UI, 3, 4)') Next (Regular) Block[B7] Leaving: {R3} } Block[B7] - Block Predecessors: [B6] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'i As UInteger') Left: ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.UInt32, IsImplicit) (Syntax: 'i As UInteger') Right: IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.UInt32, IsImplicit) (Syntax: 'For i As UI ... Next') Left: ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.UInt32, IsImplicit) (Syntax: 'i As UInteger') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.UInt32, Constant: 1, IsImplicit) (Syntax: 'For i As UI ... Next') Next (Regular) Block[B2] } Block[B8] - Exit Predecessors: [B2] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForToFlow_02() Dim source = <![CDATA[ Imports System Public Class C Sub M(i As Integer, result As Integer) 'BIND:"Sub M" For i = 0 To 4 Step 2 result = i Next End Sub End Class]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [2] [3] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (5) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '0') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '4') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4') IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '2') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: '0') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: '0') Next (Regular) Block[B2] Leaving: {R2} } Block[B2] - Block Predecessors: [B1] [B3] Statements (0) Jump if False (Regular) to Block[B4] IBinaryOperation (BinaryOperatorKind.LessThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '4') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 4, IsImplicit) (Syntax: '4') Leaving: {R1} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'result = i') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result') Right: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'i') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32, IsImplicit) (Syntax: '2') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: '2') Next (Regular) Block[B2] } Block[B4] - Exit Predecessors: [B2] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics, TestOptions.ReleaseDll.WithOverflowChecks(False)) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForToFlow_03() Dim source = <![CDATA[ Imports System Public Class C Sub M(i As Decimal, result As Decimal) 'BIND:"Sub M" For i = 3D To 0D Step -1D result = i Next End Sub End Class]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [2] [3] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (5) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Decimal) (Syntax: 'i') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '3D') Value: ILiteralOperation (OperationKind.Literal, Type: System.Decimal, Constant: 3) (Syntax: '3D') IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '0D') Value: ILiteralOperation (OperationKind.Literal, Type: System.Decimal, Constant: 0) (Syntax: '0D') IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '-1D') Value: IUnaryOperation (UnaryOperatorKind.Minus, Checked) (OperationKind.Unary, Type: System.Decimal, Constant: -1) (Syntax: '-1D') Operand: ILiteralOperation (OperationKind.Literal, Type: System.Decimal, Constant: 1) (Syntax: '1D') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: '3D') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Decimal, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Decimal, Constant: 3, IsImplicit) (Syntax: '3D') Next (Regular) Block[B2] Leaving: {R2} } Block[B2] - Block Predecessors: [B1] [B3] Statements (0) Jump if False (Regular) to Block[B4] IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '0D') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Decimal, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Decimal, Constant: 0, IsImplicit) (Syntax: '0D') Leaving: {R1} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Decimal, IsImplicit) (Syntax: 'result = i') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Decimal) (Syntax: 'result') Right: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Decimal) (Syntax: 'i') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'i') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Decimal, IsImplicit) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Decimal, IsImplicit) (Syntax: '-1D') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Decimal, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Decimal, Constant: -1, IsImplicit) (Syntax: '-1D') Next (Regular) Block[B2] } Block[B4] - Exit Predecessors: [B2] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForToFlow_04() Dim source = <![CDATA[ Imports System Public Class C Sub M(i As Short, [step] As Short, result As Short) 'BIND:"Sub M" For i = 0S To 4S Step [step] result = i Next End Sub End Class]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [2] [3] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (5) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int16) (Syntax: 'i') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '0S') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int16, Constant: 0) (Syntax: '0S') IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '4S') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int16, Constant: 4) (Syntax: '4S') IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '[step]') Value: IParameterReferenceOperation: step (OperationKind.ParameterReference, Type: System.Int16) (Syntax: '[step]') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: '0S') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int16, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int16, Constant: 0, IsImplicit) (Syntax: '0S') Next (Regular) Block[B2] Leaving: {R2} } Block[B2] - Block Predecessors: [B1] [B3] Statements (0) Jump if False (Regular) to Block[B4] IBinaryOperation (BinaryOperatorKind.LessThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '4S') Left: IBinaryOperation (BinaryOperatorKind.ExclusiveOr) (OperationKind.Binary, Type: System.Int16, IsImplicit) (Syntax: 'i') Left: IBinaryOperation (BinaryOperatorKind.RightShift) (OperationKind.Binary, Type: System.Int16, IsImplicit) (Syntax: 'i') Left: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int16, IsImplicit) (Syntax: '[step]') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 15, IsImplicit) (Syntax: 'i') Right: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int16, IsImplicit) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.ExclusiveOr) (OperationKind.Binary, Type: System.Int16, IsImplicit) (Syntax: '4S') Left: IBinaryOperation (BinaryOperatorKind.RightShift) (OperationKind.Binary, Type: System.Int16, IsImplicit) (Syntax: '4S') Left: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int16, IsImplicit) (Syntax: '[step]') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 15, IsImplicit) (Syntax: '4S') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int16, Constant: 4, IsImplicit) (Syntax: '4S') Leaving: {R1} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int16, IsImplicit) (Syntax: 'result = i') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int16) (Syntax: 'result') Right: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int16) (Syntax: 'i') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'i') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int16, IsImplicit) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int16, IsImplicit) (Syntax: '[step]') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int16, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int16, IsImplicit) (Syntax: '[step]') Next (Regular) Block[B2] } Block[B4] - Exit Predecessors: [B2] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForToFlow_05() Dim source = <![CDATA[ Imports System Public Class C Sub M(i As Decimal, [step] As Decimal, result As Decimal) 'BIND:"Sub M" For i = 3D To 0D Step [step] result = i Next End Sub End Class]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [2] [3] [4] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (6) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Decimal) (Syntax: 'i') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '3D') Value: ILiteralOperation (OperationKind.Literal, Type: System.Decimal, Constant: 3) (Syntax: '3D') IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '0D') Value: ILiteralOperation (OperationKind.Literal, Type: System.Decimal, Constant: 0) (Syntax: '0D') IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '[step]') Value: IParameterReferenceOperation: step (OperationKind.ParameterReference, Type: System.Decimal) (Syntax: '[step]') IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '[step]') Value: IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '[step]') Left: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Decimal, IsImplicit) (Syntax: '[step]') Right: ILiteralOperation (OperationKind.Literal, Type: System.Decimal, Constant: 0, IsImplicit) (Syntax: '[step]') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: '3D') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Decimal, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Decimal, Constant: 3, IsImplicit) (Syntax: '3D') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} } .locals {R3} { CaptureIds: [5] Block[B2] - Block Predecessors: [B1] [B5] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Decimal, IsImplicit) (Syntax: 'i') Jump if False (Regular) to Block[B4] IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: '[step]') Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (0) Jump if False (Regular) to Block[B6] IBinaryOperation (BinaryOperatorKind.LessThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '0D') Left: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Decimal, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Decimal, Constant: 0, IsImplicit) (Syntax: '0D') Leaving: {R3} {R1} Next (Regular) Block[B5] Leaving: {R3} Block[B4] - Block Predecessors: [B2] Statements (0) Jump if False (Regular) to Block[B6] IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '0D') Left: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Decimal, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Decimal, Constant: 0, IsImplicit) (Syntax: '0D') Leaving: {R3} {R1} Next (Regular) Block[B5] Leaving: {R3} } Block[B5] - Block Predecessors: [B3] [B4] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Decimal, IsImplicit) (Syntax: 'result = i') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Decimal) (Syntax: 'result') Right: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Decimal) (Syntax: 'i') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'i') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Decimal, IsImplicit) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Decimal, IsImplicit) (Syntax: '[step]') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Decimal, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Decimal, IsImplicit) (Syntax: '[step]') Next (Regular) Block[B2] Entering: {R3} } Block[B6] - Exit Predecessors: [B3] [B4] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForToFlow_06() Dim source = <![CDATA[ Imports System Public Enum MyEnum As UShort One = 1 End Enum Public Class C Sub M(i as MyEnum, init As MyEnum, limit As MyEnum, [step] as MyEnum, result As MyEnum) 'BIND:"Sub M" For i = init To limit Step [step] result = i Next End Sub End Class]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [2] [3] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (5) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: MyEnum) (Syntax: 'i') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init') Value: IParameterReferenceOperation: init (OperationKind.ParameterReference, Type: MyEnum) (Syntax: 'init') IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit') Value: IParameterReferenceOperation: limit (OperationKind.ParameterReference, Type: MyEnum) (Syntax: 'limit') IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '[step]') Value: IParameterReferenceOperation: step (OperationKind.ParameterReference, Type: MyEnum) (Syntax: '[step]') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'init') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyEnum, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: MyEnum, IsImplicit) (Syntax: 'init') Next (Regular) Block[B2] Leaving: {R2} } Block[B2] - Block Predecessors: [B1] [B3] Statements (0) Jump if False (Regular) to Block[B4] IBinaryOperation (BinaryOperatorKind.LessThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'limit') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: MyEnum, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: MyEnum, IsImplicit) (Syntax: 'limit') Leaving: {R1} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: MyEnum, IsImplicit) (Syntax: 'result = i') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: MyEnum) (Syntax: 'result') Right: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: MyEnum) (Syntax: 'i') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'i') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: MyEnum, IsImplicit) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: MyEnum, IsImplicit) (Syntax: '[step]') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: MyEnum, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: MyEnum, IsImplicit) (Syntax: '[step]') Next (Regular) Block[B2] } Block[B4] - Exit Predecessors: [B2] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForToFlow_07() Dim source = <![CDATA[ Imports System Public Enum MyEnum As SByte One = 1 End Enum Public Class C Sub M(i as MyEnum, init As MyEnum, limit As MyEnum, [step] as MyEnum, result As MyEnum) 'BIND:"Sub M" For i = init To limit Step [step] result = i Next End Sub End Class]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [2] [3] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (5) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: MyEnum) (Syntax: 'i') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init') Value: IParameterReferenceOperation: init (OperationKind.ParameterReference, Type: MyEnum) (Syntax: 'init') IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit') Value: IParameterReferenceOperation: limit (OperationKind.ParameterReference, Type: MyEnum) (Syntax: 'limit') IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '[step]') Value: IParameterReferenceOperation: step (OperationKind.ParameterReference, Type: MyEnum) (Syntax: '[step]') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'init') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyEnum, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: MyEnum, IsImplicit) (Syntax: 'init') Next (Regular) Block[B2] Leaving: {R2} } Block[B2] - Block Predecessors: [B1] [B3] Statements (0) Jump if False (Regular) to Block[B4] IBinaryOperation (BinaryOperatorKind.LessThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'limit') Left: IBinaryOperation (BinaryOperatorKind.ExclusiveOr) (OperationKind.Binary, Type: MyEnum, IsImplicit) (Syntax: 'i') Left: IBinaryOperation (BinaryOperatorKind.RightShift) (OperationKind.Binary, Type: MyEnum, IsImplicit) (Syntax: 'i') Left: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: MyEnum, IsImplicit) (Syntax: '[step]') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 7, IsImplicit) (Syntax: 'i') Right: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: MyEnum, IsImplicit) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.ExclusiveOr) (OperationKind.Binary, Type: MyEnum, IsImplicit) (Syntax: 'limit') Left: IBinaryOperation (BinaryOperatorKind.RightShift) (OperationKind.Binary, Type: MyEnum, IsImplicit) (Syntax: 'limit') Left: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: MyEnum, IsImplicit) (Syntax: '[step]') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 7, IsImplicit) (Syntax: 'limit') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: MyEnum, IsImplicit) (Syntax: 'limit') Leaving: {R1} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: MyEnum, IsImplicit) (Syntax: 'result = i') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: MyEnum) (Syntax: 'result') Right: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: MyEnum) (Syntax: 'i') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'i') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: MyEnum, IsImplicit) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: MyEnum, IsImplicit) (Syntax: '[step]') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: MyEnum, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: MyEnum, IsImplicit) (Syntax: '[step]') Next (Regular) Block[B2] } Block[B4] - Exit Predecessors: [B2] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForToFlow_08() Dim source = <![CDATA[ Imports System Public Enum MyEnum As Long MinusOne = -1 End Enum Public Class C Sub M(i as MyEnum, init As MyEnum, limit As MyEnum, result As MyEnum) 'BIND:"Sub M" For i = init To limit Step MyEnum.MinusOne result = i Next End Sub End Class]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [2] [3] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (5) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: MyEnum) (Syntax: 'i') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init') Value: IParameterReferenceOperation: init (OperationKind.ParameterReference, Type: MyEnum) (Syntax: 'init') IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit') Value: IParameterReferenceOperation: limit (OperationKind.ParameterReference, Type: MyEnum) (Syntax: 'limit') IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'MyEnum.MinusOne') Value: IFieldReferenceOperation: MyEnum.MinusOne (Static) (OperationKind.FieldReference, Type: MyEnum, Constant: -1) (Syntax: 'MyEnum.MinusOne') Instance Receiver: null ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'init') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyEnum, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: MyEnum, IsImplicit) (Syntax: 'init') Next (Regular) Block[B2] Leaving: {R2} } Block[B2] - Block Predecessors: [B1] [B3] Statements (0) Jump if False (Regular) to Block[B4] IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'limit') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: MyEnum, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: MyEnum, IsImplicit) (Syntax: 'limit') Leaving: {R1} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: MyEnum, IsImplicit) (Syntax: 'result = i') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: MyEnum) (Syntax: 'result') Right: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: MyEnum) (Syntax: 'i') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'i') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: MyEnum, IsImplicit) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: MyEnum, IsImplicit) (Syntax: 'MyEnum.MinusOne') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: MyEnum, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: MyEnum, Constant: -1, IsImplicit) (Syntax: 'MyEnum.MinusOne') Next (Regular) Block[B2] } Block[B4] - Exit Predecessors: [B2] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForToFlow_09() Dim source = <![CDATA[ Imports System Public Class C Sub M(i As Integer?, init As Integer?, limit As Integer?, [step] As Integer?, result As Integer?) 'BIND:"Sub M" For i = init To limit Step [step] result = i Next End Sub End Class]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [2] [3] [4] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (4) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'i') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init') Value: IParameterReferenceOperation: init (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'init') IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit') Value: IParameterReferenceOperation: limit (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'limit') IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '[step]') Value: IParameterReferenceOperation: step (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: '[step]') Jump if False (Regular) to Block[B3] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: '[step]') Operand: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: '[step]') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '[step]') Value: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False, IsImplicit) (Syntax: '[step]') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '[step]') Value: IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '[step]') Left: IInvocationOperation ( Function System.Nullable(Of System.Int32).GetValueOrDefault() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: '[step]') Instance Receiver: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: '[step]') Arguments(0) Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: '[step]') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'init') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'init') Next (Regular) Block[B5] Leaving: {R2} } Block[B5] - Block Predecessors: [B4] [B11] [B12] Statements (0) Jump if False (Regular) to Block[B6] IBinaryOperation (BinaryOperatorKind.Or) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '[step]') Left: IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'limit') Operand: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'limit') Right: IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'i') Operand: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i') Entering: {R3} Next (Regular) Block[B13] Leaving: {R1} .locals {R3} { CaptureIds: [5] Block[B6] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IInvocationOperation ( Function System.Nullable(Of System.Int32).GetValueOrDefault() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'i') Instance Receiver: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i') Arguments(0) Jump if False (Regular) to Block[B8] IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: '[step]') Next (Regular) Block[B7] Block[B7] - Block Predecessors: [B6] Statements (0) Jump if False (Regular) to Block[B13] IBinaryOperation (BinaryOperatorKind.LessThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'limit') Left: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i') Right: IInvocationOperation ( Function System.Nullable(Of System.Int32).GetValueOrDefault() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'limit') Instance Receiver: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'limit') Arguments(0) Leaving: {R3} {R1} Next (Regular) Block[B9] Leaving: {R3} Block[B8] - Block Predecessors: [B6] Statements (0) Jump if False (Regular) to Block[B13] IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'limit') Left: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i') Right: IInvocationOperation ( Function System.Nullable(Of System.Int32).GetValueOrDefault() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'limit') Instance Receiver: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'limit') Arguments(0) Leaving: {R3} {R1} Next (Regular) Block[B9] Leaving: {R3} } Block[B9] - Block Predecessors: [B7] [B8] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'result = i') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'result') Right: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'i') Next (Regular) Block[B10] Entering: {R4} .locals {R4} { CaptureIds: [6] Block[B10] - Block Predecessors: [B9] Statements (1) IFlowCaptureOperation: 6 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i') Jump if False (Regular) to Block[B12] IBinaryOperation (BinaryOperatorKind.Or) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '[step]') Left: IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: '[step]') Operand: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: '[step]') Right: IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'i') Operand: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i') Next (Regular) Block[B11] Block[B11] - Block Predecessors: [B10] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'i') Left: IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i') Right: IDefaultValueOperation (OperationKind.DefaultValue, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i') Next (Regular) Block[B5] Leaving: {R4} Block[B12] - Block Predecessors: [B10] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'i') Left: IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: '[step]') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (WideningNullable) Operand: IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32, IsImplicit) (Syntax: '[step]') Left: IInvocationOperation ( Function System.Nullable(Of System.Int32).GetValueOrDefault() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'i') Instance Receiver: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i') Arguments(0) Right: IInvocationOperation ( Function System.Nullable(Of System.Int32).GetValueOrDefault() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: '[step]') Instance Receiver: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: '[step]') Arguments(0) Next (Regular) Block[B5] Leaving: {R4} } } Block[B13] - Exit Predecessors: [B5] [B7] [B8] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForToFlow_10() Dim source = <![CDATA[ Imports System Public Class C Sub M(i As C, init As C, limit As C, [step] As C, result As C) 'BIND:"Sub M" For i = init To limit Step [step] result = i Next End Sub End Class]]>.Value Dim expectedDiagnostics = <![CDATA[ BC33038: Type 'C' must define operator '+' to be used in a 'For' statement. For i = init To limit Step [step] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC33038: Type 'C' must define operator '-' to be used in a 'For' statement. For i = init To limit Step [step] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC33038: Type 'C' must define operator '<=' to be used in a 'For' statement. For i = init To limit Step [step] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC33038: Type 'C' must define operator '>=' to be used in a 'For' statement. For i = init To limit Step [step] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [2] [3] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (5) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'i') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'init') Value: IParameterReferenceOperation: init (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'init') IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'limit') Value: IParameterReferenceOperation: limit (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'limit') IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: '[step]') Value: IParameterReferenceOperation: step (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: '[step]') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsInvalid, IsImplicit) (Syntax: 'init') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'init') Next (Regular) Block[B2] Leaving: {R2} } Block[B2] - Block Predecessors: [B1] [B3] Statements (0) Jump if False (Regular) to Block[B4] IInvalidOperation (OperationKind.Invalid, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'limit') Children(2): IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i') IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'limit') Leaving: {R1} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'result = i') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: C) (Syntax: 'result') Right: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C) (Syntax: 'i') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsInvalid, IsImplicit) (Syntax: 'i') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: C, IsInvalid, IsImplicit) (Syntax: '[step]') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: '[step]') Next (Regular) Block[B2] } Block[B4] - Exit Predecessors: [B2] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForToFlow_11() Dim source = <![CDATA[ Imports System Public Structure C Sub M(i As C?, init As C?, limit As C?, [step] As C?, result As C?) 'BIND:"Sub M" For i = init To limit Step [step] result = i Next End Sub End Structure]]>.Value Dim expectedDiagnostics = <![CDATA[ BC33038: Type 'C?' must define operator '+' to be used in a 'For' statement. For i = init To limit Step [step] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC33038: Type 'C?' must define operator '-' to be used in a 'For' statement. For i = init To limit Step [step] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC33038: Type 'C?' must define operator '<=' to be used in a 'For' statement. For i = init To limit Step [step] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC33038: Type 'C?' must define operator '>=' to be used in a 'For' statement. For i = init To limit Step [step] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [2] [3] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (5) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of C), IsInvalid) (Syntax: 'i') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'init') Value: IParameterReferenceOperation: init (OperationKind.ParameterReference, Type: System.Nullable(Of C), IsInvalid) (Syntax: 'init') IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'limit') Value: IParameterReferenceOperation: limit (OperationKind.ParameterReference, Type: System.Nullable(Of C), IsInvalid) (Syntax: 'limit') IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: '[step]') Value: IParameterReferenceOperation: step (OperationKind.ParameterReference, Type: System.Nullable(Of C), IsInvalid) (Syntax: '[step]') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsInvalid, IsImplicit) (Syntax: 'init') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsInvalid, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsInvalid, IsImplicit) (Syntax: 'init') Next (Regular) Block[B2] Leaving: {R2} } Block[B2] - Block Predecessors: [B1] [B5] [B6] Statements (0) Jump if False (Regular) to Block[B7] IInvalidOperation (OperationKind.Invalid, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'limit') Children(2): IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of C), IsInvalid, IsImplicit) (Syntax: 'i') IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsInvalid, IsImplicit) (Syntax: 'limit') Leaving: {R1} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'result = i') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Nullable(Of C)) (Syntax: 'result') Right: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of C)) (Syntax: 'i') Next (Regular) Block[B4] Entering: {R3} .locals {R3} { CaptureIds: [4] Block[B4] - Block Predecessors: [B3] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of C), IsInvalid, IsImplicit) (Syntax: 'i') Jump if False (Regular) to Block[B6] IBinaryOperation (BinaryOperatorKind.Or) (OperationKind.Binary, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: '[step]') Left: IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: '[step]') Operand: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsInvalid, IsImplicit) (Syntax: '[step]') Right: IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'i') Operand: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of C), IsInvalid, IsImplicit) (Syntax: 'i') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B4] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsInvalid, IsImplicit) (Syntax: 'i') Left: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsInvalid, IsImplicit) (Syntax: 'i') Right: IDefaultValueOperation (OperationKind.DefaultValue, Type: System.Nullable(Of C), IsInvalid, IsImplicit) (Syntax: 'i') Next (Regular) Block[B2] Leaving: {R3} Block[B6] - Block Predecessors: [B4] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsInvalid, IsImplicit) (Syntax: 'i') Left: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsInvalid, IsImplicit) (Syntax: 'i') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Nullable(Of C), IsInvalid, IsImplicit) (Syntax: '[step]') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (WideningNullable) Operand: IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: C, IsInvalid, IsImplicit) (Syntax: '[step]') Left: IInvocationOperation ( Function System.Nullable(Of C).GetValueOrDefault() As C) (OperationKind.Invocation, Type: C, IsInvalid, IsImplicit) (Syntax: 'i') Instance Receiver: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of C), IsInvalid, IsImplicit) (Syntax: 'i') Arguments(0) Right: IInvocationOperation ( Function System.Nullable(Of C).GetValueOrDefault() As C) (OperationKind.Invocation, Type: C, IsInvalid, IsImplicit) (Syntax: '[step]') Instance Receiver: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsInvalid, IsImplicit) (Syntax: '[step]') Arguments(0) Next (Regular) Block[B2] Leaving: {R3} } } Block[B7] - Exit Predecessors: [B2] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForToFlow_12() Dim source = <![CDATA[ Imports System Public Class C1 Sub M(i As C1, init As C2, limit As C3, [step] As C4, result As C1) 'BIND:"Sub M" For i = init To limit Step [step] result = i Next End Sub End Class Public Class C2 End Class Public Class C3 End Class Public Class C4 End Class ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30311: Value of type 'C2' cannot be converted to 'C1'. For i = init To limit Step [step] ~~~~ BC30311: Value of type 'C3' cannot be converted to 'C1'. For i = init To limit Step [step] ~~~~~ BC30311: Value of type 'C4' cannot be converted to 'C1'. For i = init To limit Step [step] ~~~~~~ ]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [2] [3] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (5) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C1) (Syntax: 'i') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'init') Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: C1, IsInvalid, IsImplicit) (Syntax: 'init') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (DelegateRelaxationLevelNone) Operand: IParameterReferenceOperation: init (OperationKind.ParameterReference, Type: C2, IsInvalid) (Syntax: 'init') IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'limit') Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: C1, IsInvalid, IsImplicit) (Syntax: 'limit') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (DelegateRelaxationLevelNone) Operand: IParameterReferenceOperation: limit (OperationKind.ParameterReference, Type: C3, IsInvalid) (Syntax: 'limit') IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: '[step]') Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: C1, IsInvalid, IsImplicit) (Syntax: '[step]') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (DelegateRelaxationLevelNone) Operand: IParameterReferenceOperation: step (OperationKind.ParameterReference, Type: C4, IsInvalid) (Syntax: '[step]') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsInvalid, IsImplicit) (Syntax: 'init') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C1, IsInvalid, IsImplicit) (Syntax: 'init') Next (Regular) Block[B2] Leaving: {R2} } Block[B2] - Block Predecessors: [B1] [B3] Statements (0) Jump if False (Regular) to Block[B4] IInvalidOperation (OperationKind.Invalid, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'limit') Children(2): IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C1, IsImplicit) (Syntax: 'i') IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: C1, IsInvalid, IsImplicit) (Syntax: 'limit') Leaving: {R1} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C1, IsImplicit) (Syntax: 'result = i') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: C1) (Syntax: 'result') Right: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C1) (Syntax: 'i') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'i') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C1, IsImplicit) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: C1, IsInvalid, IsImplicit) (Syntax: '[step]') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C1, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: C1, IsInvalid, IsImplicit) (Syntax: '[step]') Next (Regular) Block[B2] } Block[B4] - Exit Predecessors: [B2] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForToFlow_13() Dim source = <![CDATA[ Imports System Public Enum MyEnum As Integer MinusOne = -1 End Enum Public Class C Sub M(i As MyEnum?, init As MyEnum?, limit As MyEnum?, [step] As MyEnum?, result As MyEnum?) 'BIND:"Sub M" For i = init To limit Step [step] result = i Next End Sub End Class]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [2] [3] [4] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (4) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of MyEnum)) (Syntax: 'i') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init') Value: IParameterReferenceOperation: init (OperationKind.ParameterReference, Type: System.Nullable(Of MyEnum)) (Syntax: 'init') IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit') Value: IParameterReferenceOperation: limit (OperationKind.ParameterReference, Type: System.Nullable(Of MyEnum)) (Syntax: 'limit') IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '[step]') Value: IParameterReferenceOperation: step (OperationKind.ParameterReference, Type: System.Nullable(Of MyEnum)) (Syntax: '[step]') Jump if False (Regular) to Block[B3] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: '[step]') Operand: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of MyEnum), IsImplicit) (Syntax: '[step]') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '[step]') Value: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False, IsImplicit) (Syntax: '[step]') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '[step]') Value: IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '[step]') Left: IInvocationOperation ( Function System.Nullable(Of MyEnum).GetValueOrDefault() As MyEnum) (OperationKind.Invocation, Type: MyEnum, IsImplicit) (Syntax: '[step]') Instance Receiver: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of MyEnum), IsImplicit) (Syntax: '[step]') Arguments(0) Right: ILiteralOperation (OperationKind.Literal, Type: MyEnum, Constant: 0, IsImplicit) (Syntax: '[step]') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'init') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of MyEnum), IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of MyEnum), IsImplicit) (Syntax: 'init') Next (Regular) Block[B5] Leaving: {R2} } Block[B5] - Block Predecessors: [B4] [B11] [B12] Statements (0) Jump if False (Regular) to Block[B6] IBinaryOperation (BinaryOperatorKind.Or) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '[step]') Left: IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'limit') Operand: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of MyEnum), IsImplicit) (Syntax: 'limit') Right: IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'i') Operand: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of MyEnum), IsImplicit) (Syntax: 'i') Entering: {R3} Next (Regular) Block[B13] Leaving: {R1} .locals {R3} { CaptureIds: [5] Block[B6] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IInvocationOperation ( Function System.Nullable(Of MyEnum).GetValueOrDefault() As MyEnum) (OperationKind.Invocation, Type: MyEnum, IsImplicit) (Syntax: 'i') Instance Receiver: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of MyEnum), IsImplicit) (Syntax: 'i') Arguments(0) Jump if False (Regular) to Block[B8] IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: '[step]') Next (Regular) Block[B7] Block[B7] - Block Predecessors: [B6] Statements (0) Jump if False (Regular) to Block[B13] IBinaryOperation (BinaryOperatorKind.LessThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'limit') Left: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: MyEnum, IsImplicit) (Syntax: 'i') Right: IInvocationOperation ( Function System.Nullable(Of MyEnum).GetValueOrDefault() As MyEnum) (OperationKind.Invocation, Type: MyEnum, IsImplicit) (Syntax: 'limit') Instance Receiver: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of MyEnum), IsImplicit) (Syntax: 'limit') Arguments(0) Leaving: {R3} {R1} Next (Regular) Block[B9] Leaving: {R3} Block[B8] - Block Predecessors: [B6] Statements (0) Jump if False (Regular) to Block[B13] IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'limit') Left: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: MyEnum, IsImplicit) (Syntax: 'i') Right: IInvocationOperation ( Function System.Nullable(Of MyEnum).GetValueOrDefault() As MyEnum) (OperationKind.Invocation, Type: MyEnum, IsImplicit) (Syntax: 'limit') Instance Receiver: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of MyEnum), IsImplicit) (Syntax: 'limit') Arguments(0) Leaving: {R3} {R1} Next (Regular) Block[B9] Leaving: {R3} } Block[B9] - Block Predecessors: [B7] [B8] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Nullable(Of MyEnum), IsImplicit) (Syntax: 'result = i') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Nullable(Of MyEnum)) (Syntax: 'result') Right: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of MyEnum)) (Syntax: 'i') Next (Regular) Block[B10] Entering: {R4} .locals {R4} { CaptureIds: [6] Block[B10] - Block Predecessors: [B9] Statements (1) IFlowCaptureOperation: 6 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of MyEnum), IsImplicit) (Syntax: 'i') Jump if False (Regular) to Block[B12] IBinaryOperation (BinaryOperatorKind.Or) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '[step]') Left: IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: '[step]') Operand: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of MyEnum), IsImplicit) (Syntax: '[step]') Right: IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'i') Operand: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of MyEnum), IsImplicit) (Syntax: 'i') Next (Regular) Block[B11] Block[B11] - Block Predecessors: [B10] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'i') Left: IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of MyEnum), IsImplicit) (Syntax: 'i') Right: IDefaultValueOperation (OperationKind.DefaultValue, Type: System.Nullable(Of MyEnum), IsImplicit) (Syntax: 'i') Next (Regular) Block[B5] Leaving: {R4} Block[B12] - Block Predecessors: [B10] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'i') Left: IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of MyEnum), IsImplicit) (Syntax: 'i') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Nullable(Of MyEnum), IsImplicit) (Syntax: '[step]') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (WideningNullable) Operand: IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: MyEnum, IsImplicit) (Syntax: '[step]') Left: IInvocationOperation ( Function System.Nullable(Of MyEnum).GetValueOrDefault() As MyEnum) (OperationKind.Invocation, Type: MyEnum, IsImplicit) (Syntax: 'i') Instance Receiver: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of MyEnum), IsImplicit) (Syntax: 'i') Arguments(0) Right: IInvocationOperation ( Function System.Nullable(Of MyEnum).GetValueOrDefault() As MyEnum) (OperationKind.Invocation, Type: MyEnum, IsImplicit) (Syntax: '[step]') Instance Receiver: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of MyEnum), IsImplicit) (Syntax: '[step]') Arguments(0) Next (Regular) Block[B5] Leaving: {R4} } } Block[B13] - Exit Predecessors: [B5] [B7] [B8] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact> Public Sub ForToFlow_14() Dim source = <![CDATA[ Imports System Public Class C Sub M(c1 As C, c2 As C, bInit As Boolean, init1 As Integer, init2 As Integer, bLimit As Boolean, limit1 As Integer, limit2 As Integer, result As Boolean) 'BIND:"Sub M" For If(c1, c2).i = If(bInit, init1, init2) To If(bLimit, limit1, limit2) Step 2 result = true Next End Sub Public i As Integer End Class]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} {R3} {R4} .locals {R1} { CaptureIds: [4] [5] .locals {R2} { CaptureIds: [2] [3] .locals {R3} { CaptureIds: [1] .locals {R4} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C) (Syntax: 'c1') Jump if True (Regular) to Block[B3] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Leaving: {R4} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B4] Leaving: {R4} } Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C) (Syntax: 'c2') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i') Value: IFieldReferenceOperation: C.i As System.Int32 (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'If(c1, c2).i') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)') Next (Regular) Block[B5] Leaving: {R3} } Block[B5] - Block Predecessors: [B4] Statements (0) Jump if False (Regular) to Block[B7] IParameterReferenceOperation: bInit (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bInit') Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init1') Value: IParameterReferenceOperation: init1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'init1') Next (Regular) Block[B8] Block[B7] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init2') Value: IParameterReferenceOperation: init2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'init2') Next (Regular) Block[B8] Block[B8] - Block Predecessors: [B6] [B7] Statements (0) Jump if False (Regular) to Block[B10] IParameterReferenceOperation: bLimit (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bLimit') Next (Regular) Block[B9] Block[B9] - Block Predecessors: [B8] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit1') Value: IParameterReferenceOperation: limit1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'limit1') Next (Regular) Block[B11] Block[B10] - Block Predecessors: [B8] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit2') Value: IParameterReferenceOperation: limit2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'limit2') Next (Regular) Block[B11] Block[B11] - Block Predecessors: [B9] [B10] Statements (2) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '2') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'If(bInit, init1, init2)') Left: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(c1, c2).i') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(bInit, init1, init2)') Next (Regular) Block[B12] Leaving: {R2} Entering: {R5} {R6} } .locals {R5} { CaptureIds: [7] .locals {R6} { CaptureIds: [6] Block[B12] - Block Predecessors: [B11] [B24] Statements (1) IFlowCaptureOperation: 6 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1') Jump if True (Regular) to Block[B14] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Leaving: {R6} Next (Regular) Block[B13] Block[B13] - Block Predecessors: [B12] Statements (1) IFlowCaptureOperation: 7 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B15] Leaving: {R6} } Block[B14] - Block Predecessors: [B12] Statements (1) IFlowCaptureOperation: 7 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2') Next (Regular) Block[B15] Block[B15] - Block Predecessors: [B13] [B14] Statements (0) Jump if False (Regular) to Block[B25] IBinaryOperation (BinaryOperatorKind.LessThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)') Left: IFieldReferenceOperation: C.i As System.Int32 (OperationKind.FieldReference, Type: System.Int32, IsImplicit) (Syntax: 'If(c1, c2).i') Instance Receiver: IFlowCaptureReferenceOperation: 7 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)') Right: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)') Leaving: {R5} {R1} Next (Regular) Block[B16] Leaving: {R5} } Block[B16] - Block Predecessors: [B15] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = true') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsImplicit) (Syntax: 'result = true') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B17] Entering: {R7} {R8} {R9} .locals {R7} { CaptureIds: [10] [12] .locals {R8} { CaptureIds: [9] .locals {R9} { CaptureIds: [8] Block[B17] - Block Predecessors: [B16] Statements (1) IFlowCaptureOperation: 8 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1') Jump if True (Regular) to Block[B19] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 8 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Leaving: {R9} Next (Regular) Block[B18] Block[B18] - Block Predecessors: [B17] Statements (1) IFlowCaptureOperation: 9 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 8 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B20] Leaving: {R9} } Block[B19] - Block Predecessors: [B17] Statements (1) IFlowCaptureOperation: 9 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2') Next (Regular) Block[B20] Block[B20] - Block Predecessors: [B18] [B19] Statements (1) IFlowCaptureOperation: 10 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i') Value: IFieldReferenceOperation: C.i As System.Int32 (OperationKind.FieldReference, Type: System.Int32, IsImplicit) (Syntax: 'If(c1, c2).i') Instance Receiver: IFlowCaptureReferenceOperation: 9 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)') Next (Regular) Block[B21] Leaving: {R8} Entering: {R10} } .locals {R10} { CaptureIds: [11] Block[B21] - Block Predecessors: [B20] Statements (1) IFlowCaptureOperation: 11 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1') Jump if True (Regular) to Block[B23] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 11 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Leaving: {R10} Next (Regular) Block[B22] Block[B22] - Block Predecessors: [B21] Statements (1) IFlowCaptureOperation: 12 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 11 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B24] Leaving: {R10} } Block[B23] - Block Predecessors: [B21] Statements (1) IFlowCaptureOperation: 12 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2') Next (Regular) Block[B24] Block[B24] - Block Predecessors: [B22] [B23] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i') Left: IFlowCaptureReferenceOperation: 10 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(c1, c2).i') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32, IsImplicit) (Syntax: '2') Left: IFieldReferenceOperation: C.i As System.Int32 (OperationKind.FieldReference, Type: System.Int32, IsImplicit) (Syntax: 'If(c1, c2).i') Instance Receiver: IFlowCaptureReferenceOperation: 12 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)') Right: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: '2') Next (Regular) Block[B12] Leaving: {R7} Entering: {R5} {R6} } } Block[B25] - Exit Predecessors: [B15] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics, TestOptions.ReleaseDll.WithOverflowChecks(False)) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact> Public Sub ForToFlow_15() Dim source = <![CDATA[ Imports System Public Class C Sub M(c1 As C, c2 As C, bInit As Boolean, init1 As Integer, init2 As Integer, bLimit As Boolean, limit1 As Integer, limit2 As Integer, result As Boolean) 'BIND:"Sub M" For If(c1, c2).i = If(bInit, init1, init2) To If(bLimit, limit1, limit2) Step -2 result = true Next End Sub Public i As Integer End Class]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} {R3} {R4} .locals {R1} { CaptureIds: [4] [5] .locals {R2} { CaptureIds: [2] [3] .locals {R3} { CaptureIds: [1] .locals {R4} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C) (Syntax: 'c1') Jump if True (Regular) to Block[B3] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Leaving: {R4} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B4] Leaving: {R4} } Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C) (Syntax: 'c2') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i') Value: IFieldReferenceOperation: C.i As System.Int32 (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'If(c1, c2).i') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)') Next (Regular) Block[B5] Leaving: {R3} } Block[B5] - Block Predecessors: [B4] Statements (0) Jump if False (Regular) to Block[B7] IParameterReferenceOperation: bInit (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bInit') Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init1') Value: IParameterReferenceOperation: init1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'init1') Next (Regular) Block[B8] Block[B7] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init2') Value: IParameterReferenceOperation: init2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'init2') Next (Regular) Block[B8] Block[B8] - Block Predecessors: [B6] [B7] Statements (0) Jump if False (Regular) to Block[B10] IParameterReferenceOperation: bLimit (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bLimit') Next (Regular) Block[B9] Block[B9] - Block Predecessors: [B8] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit1') Value: IParameterReferenceOperation: limit1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'limit1') Next (Regular) Block[B11] Block[B10] - Block Predecessors: [B8] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit2') Value: IParameterReferenceOperation: limit2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'limit2') Next (Regular) Block[B11] Block[B11] - Block Predecessors: [B9] [B10] Statements (2) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '-2') Value: IUnaryOperation (UnaryOperatorKind.Minus, Checked) (OperationKind.Unary, Type: System.Int32, Constant: -2) (Syntax: '-2') Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'If(bInit, init1, init2)') Left: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(c1, c2).i') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(bInit, init1, init2)') Next (Regular) Block[B12] Leaving: {R2} Entering: {R5} {R6} } .locals {R5} { CaptureIds: [7] .locals {R6} { CaptureIds: [6] Block[B12] - Block Predecessors: [B11] [B24] Statements (1) IFlowCaptureOperation: 6 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1') Jump if True (Regular) to Block[B14] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Leaving: {R6} Next (Regular) Block[B13] Block[B13] - Block Predecessors: [B12] Statements (1) IFlowCaptureOperation: 7 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B15] Leaving: {R6} } Block[B14] - Block Predecessors: [B12] Statements (1) IFlowCaptureOperation: 7 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2') Next (Regular) Block[B15] Block[B15] - Block Predecessors: [B13] [B14] Statements (0) Jump if False (Regular) to Block[B25] IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)') Left: IFieldReferenceOperation: C.i As System.Int32 (OperationKind.FieldReference, Type: System.Int32, IsImplicit) (Syntax: 'If(c1, c2).i') Instance Receiver: IFlowCaptureReferenceOperation: 7 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)') Right: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)') Leaving: {R5} {R1} Next (Regular) Block[B16] Leaving: {R5} } Block[B16] - Block Predecessors: [B15] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = true') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsImplicit) (Syntax: 'result = true') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B17] Entering: {R7} {R8} {R9} .locals {R7} { CaptureIds: [10] [12] .locals {R8} { CaptureIds: [9] .locals {R9} { CaptureIds: [8] Block[B17] - Block Predecessors: [B16] Statements (1) IFlowCaptureOperation: 8 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1') Jump if True (Regular) to Block[B19] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 8 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Leaving: {R9} Next (Regular) Block[B18] Block[B18] - Block Predecessors: [B17] Statements (1) IFlowCaptureOperation: 9 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 8 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B20] Leaving: {R9} } Block[B19] - Block Predecessors: [B17] Statements (1) IFlowCaptureOperation: 9 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2') Next (Regular) Block[B20] Block[B20] - Block Predecessors: [B18] [B19] Statements (1) IFlowCaptureOperation: 10 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i') Value: IFieldReferenceOperation: C.i As System.Int32 (OperationKind.FieldReference, Type: System.Int32, IsImplicit) (Syntax: 'If(c1, c2).i') Instance Receiver: IFlowCaptureReferenceOperation: 9 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)') Next (Regular) Block[B21] Leaving: {R8} Entering: {R10} } .locals {R10} { CaptureIds: [11] Block[B21] - Block Predecessors: [B20] Statements (1) IFlowCaptureOperation: 11 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1') Jump if True (Regular) to Block[B23] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 11 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Leaving: {R10} Next (Regular) Block[B22] Block[B22] - Block Predecessors: [B21] Statements (1) IFlowCaptureOperation: 12 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 11 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B24] Leaving: {R10} } Block[B23] - Block Predecessors: [B21] Statements (1) IFlowCaptureOperation: 12 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2') Next (Regular) Block[B24] Block[B24] - Block Predecessors: [B22] [B23] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i') Left: IFlowCaptureReferenceOperation: 10 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(c1, c2).i') Right: IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32, IsImplicit) (Syntax: '-2') Left: IFieldReferenceOperation: C.i As System.Int32 (OperationKind.FieldReference, Type: System.Int32, IsImplicit) (Syntax: 'If(c1, c2).i') Instance Receiver: IFlowCaptureReferenceOperation: 12 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)') Right: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: -2, IsImplicit) (Syntax: '-2') Next (Regular) Block[B12] Leaving: {R7} Entering: {R5} {R6} } } Block[B25] - Exit Predecessors: [B15] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact> Public Sub ForToFlow_16() Dim source = <![CDATA[ Imports System Public Class C Sub M(c1 As C, c2 As C, bInit As Boolean, init1 As Integer, init2 As Integer, bLimit As Boolean, limit1 As Integer, limit2 As Integer, bStep As Boolean, step1 As Integer, step2 As Integer, result As Boolean) 'BIND:"Sub M" For If(c1, c2).i = If(bInit, init1, init2) To If(bLimit, limit1, limit2) Step If(bStep, step1, step2) result = true Next End Sub Public i As Integer End Class]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} {R3} {R4} .locals {R1} { CaptureIds: [4] [5] .locals {R2} { CaptureIds: [2] [3] .locals {R3} { CaptureIds: [1] .locals {R4} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C) (Syntax: 'c1') Jump if True (Regular) to Block[B3] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Leaving: {R4} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B4] Leaving: {R4} } Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C) (Syntax: 'c2') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i') Value: IFieldReferenceOperation: C.i As System.Int32 (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'If(c1, c2).i') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)') Next (Regular) Block[B5] Leaving: {R3} } Block[B5] - Block Predecessors: [B4] Statements (0) Jump if False (Regular) to Block[B7] IParameterReferenceOperation: bInit (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bInit') Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init1') Value: IParameterReferenceOperation: init1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'init1') Next (Regular) Block[B8] Block[B7] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init2') Value: IParameterReferenceOperation: init2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'init2') Next (Regular) Block[B8] Block[B8] - Block Predecessors: [B6] [B7] Statements (0) Jump if False (Regular) to Block[B10] IParameterReferenceOperation: bLimit (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bLimit') Next (Regular) Block[B9] Block[B9] - Block Predecessors: [B8] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit1') Value: IParameterReferenceOperation: limit1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'limit1') Next (Regular) Block[B11] Block[B10] - Block Predecessors: [B8] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit2') Value: IParameterReferenceOperation: limit2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'limit2') Next (Regular) Block[B11] Block[B11] - Block Predecessors: [B9] [B10] Statements (0) Jump if False (Regular) to Block[B13] IParameterReferenceOperation: bStep (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bStep') Next (Regular) Block[B12] Block[B12] - Block Predecessors: [B11] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'step1') Value: IParameterReferenceOperation: step1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'step1') Next (Regular) Block[B14] Block[B13] - Block Predecessors: [B11] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'step2') Value: IParameterReferenceOperation: step2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'step2') Next (Regular) Block[B14] Block[B14] - Block Predecessors: [B12] [B13] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'If(bInit, init1, init2)') Left: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(c1, c2).i') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(bInit, init1, init2)') Next (Regular) Block[B15] Leaving: {R2} Entering: {R5} {R6} } .locals {R5} { CaptureIds: [7] .locals {R6} { CaptureIds: [6] Block[B15] - Block Predecessors: [B14] [B27] Statements (1) IFlowCaptureOperation: 6 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1') Jump if True (Regular) to Block[B17] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Leaving: {R6} Next (Regular) Block[B16] Block[B16] - Block Predecessors: [B15] Statements (1) IFlowCaptureOperation: 7 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B18] Leaving: {R6} } Block[B17] - Block Predecessors: [B15] Statements (1) IFlowCaptureOperation: 7 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2') Next (Regular) Block[B18] Block[B18] - Block Predecessors: [B16] [B17] Statements (0) Jump if False (Regular) to Block[B28] IBinaryOperation (BinaryOperatorKind.LessThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)') Left: IBinaryOperation (BinaryOperatorKind.ExclusiveOr) (OperationKind.Binary, Type: System.Int32, IsImplicit) (Syntax: 'If(c1, c2).i') Left: IBinaryOperation (BinaryOperatorKind.RightShift) (OperationKind.Binary, Type: System.Int32, IsImplicit) (Syntax: 'If(c1, c2).i') Left: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(bStep, step1, step2)') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 31, IsImplicit) (Syntax: 'If(c1, c2).i') Right: IFieldReferenceOperation: C.i As System.Int32 (OperationKind.FieldReference, Type: System.Int32, IsImplicit) (Syntax: 'If(c1, c2).i') Instance Receiver: IFlowCaptureReferenceOperation: 7 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)') Right: IBinaryOperation (BinaryOperatorKind.ExclusiveOr) (OperationKind.Binary, Type: System.Int32, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)') Left: IBinaryOperation (BinaryOperatorKind.RightShift) (OperationKind.Binary, Type: System.Int32, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)') Left: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(bStep, step1, step2)') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 31, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)') Right: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)') Leaving: {R5} {R1} Next (Regular) Block[B19] Leaving: {R5} } Block[B19] - Block Predecessors: [B18] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = true') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsImplicit) (Syntax: 'result = true') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B20] Entering: {R7} {R8} {R9} .locals {R7} { CaptureIds: [10] [12] .locals {R8} { CaptureIds: [9] .locals {R9} { CaptureIds: [8] Block[B20] - Block Predecessors: [B19] Statements (1) IFlowCaptureOperation: 8 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1') Jump if True (Regular) to Block[B22] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 8 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Leaving: {R9} Next (Regular) Block[B21] Block[B21] - Block Predecessors: [B20] Statements (1) IFlowCaptureOperation: 9 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 8 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B23] Leaving: {R9} } Block[B22] - Block Predecessors: [B20] Statements (1) IFlowCaptureOperation: 9 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2') Next (Regular) Block[B23] Block[B23] - Block Predecessors: [B21] [B22] Statements (1) IFlowCaptureOperation: 10 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i') Value: IFieldReferenceOperation: C.i As System.Int32 (OperationKind.FieldReference, Type: System.Int32, IsImplicit) (Syntax: 'If(c1, c2).i') Instance Receiver: IFlowCaptureReferenceOperation: 9 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)') Next (Regular) Block[B24] Leaving: {R8} Entering: {R10} } .locals {R10} { CaptureIds: [11] Block[B24] - Block Predecessors: [B23] Statements (1) IFlowCaptureOperation: 11 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1') Jump if True (Regular) to Block[B26] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 11 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Leaving: {R10} Next (Regular) Block[B25] Block[B25] - Block Predecessors: [B24] Statements (1) IFlowCaptureOperation: 12 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 11 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B27] Leaving: {R10} } Block[B26] - Block Predecessors: [B24] Statements (1) IFlowCaptureOperation: 12 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2') Next (Regular) Block[B27] Block[B27] - Block Predecessors: [B25] [B26] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i') Left: IFlowCaptureReferenceOperation: 10 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(c1, c2).i') Right: IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32, IsImplicit) (Syntax: 'If(bStep, step1, step2)') Left: IFieldReferenceOperation: C.i As System.Int32 (OperationKind.FieldReference, Type: System.Int32, IsImplicit) (Syntax: 'If(c1, c2).i') Instance Receiver: IFlowCaptureReferenceOperation: 12 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)') Right: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(bStep, step1, step2)') Next (Regular) Block[B15] Leaving: {R7} Entering: {R5} {R6} } } Block[B28] - Exit Predecessors: [B18] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact> Public Sub ForToFlow_17() Dim source = <![CDATA[ Imports System Public Class C Sub M(c1 As C, c2 As C, bInit As Boolean, init1 As Double, init2 As Double, bLimit As Boolean, limit1 As Double, limit2 As Double, bStep As Boolean, step1 As Double, step2 As Double, result As Boolean) 'BIND:"Sub M" For If(c1, c2).i = If(bInit, init1, init2) To If(bLimit, limit1, limit2) Step If(bStep, step1, step2) result = true Next End Sub Public i As Double End Class]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} {R3} {R4} .locals {R1} { CaptureIds: [4] [5] [6] .locals {R2} { CaptureIds: [2] [3] .locals {R3} { CaptureIds: [1] .locals {R4} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C) (Syntax: 'c1') Jump if True (Regular) to Block[B3] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Leaving: {R4} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B4] Leaving: {R4} } Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C) (Syntax: 'c2') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i') Value: IFieldReferenceOperation: C.i As System.Double (OperationKind.FieldReference, Type: System.Double) (Syntax: 'If(c1, c2).i') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)') Next (Regular) Block[B5] Leaving: {R3} } Block[B5] - Block Predecessors: [B4] Statements (0) Jump if False (Regular) to Block[B7] IParameterReferenceOperation: bInit (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bInit') Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init1') Value: IParameterReferenceOperation: init1 (OperationKind.ParameterReference, Type: System.Double) (Syntax: 'init1') Next (Regular) Block[B8] Block[B7] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init2') Value: IParameterReferenceOperation: init2 (OperationKind.ParameterReference, Type: System.Double) (Syntax: 'init2') Next (Regular) Block[B8] Block[B8] - Block Predecessors: [B6] [B7] Statements (0) Jump if False (Regular) to Block[B10] IParameterReferenceOperation: bLimit (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bLimit') Next (Regular) Block[B9] Block[B9] - Block Predecessors: [B8] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit1') Value: IParameterReferenceOperation: limit1 (OperationKind.ParameterReference, Type: System.Double) (Syntax: 'limit1') Next (Regular) Block[B11] Block[B10] - Block Predecessors: [B8] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit2') Value: IParameterReferenceOperation: limit2 (OperationKind.ParameterReference, Type: System.Double) (Syntax: 'limit2') Next (Regular) Block[B11] Block[B11] - Block Predecessors: [B9] [B10] Statements (0) Jump if False (Regular) to Block[B13] IParameterReferenceOperation: bStep (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bStep') Next (Regular) Block[B12] Block[B12] - Block Predecessors: [B11] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'step1') Value: IParameterReferenceOperation: step1 (OperationKind.ParameterReference, Type: System.Double) (Syntax: 'step1') Next (Regular) Block[B14] Block[B13] - Block Predecessors: [B11] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'step2') Value: IParameterReferenceOperation: step2 (OperationKind.ParameterReference, Type: System.Double) (Syntax: 'step2') Next (Regular) Block[B14] Block[B14] - Block Predecessors: [B12] [B13] Statements (2) IFlowCaptureOperation: 6 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(bStep, step1, step2)') Value: IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'If(bStep, step1, step2)') Left: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Double, IsImplicit) (Syntax: 'If(bStep, step1, step2)') Right: ILiteralOperation (OperationKind.Literal, Type: System.Double, Constant: 0, IsImplicit) (Syntax: 'If(bStep, step1, step2)') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'If(bInit, init1, init2)') Left: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Double, IsImplicit) (Syntax: 'If(c1, c2).i') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Double, IsImplicit) (Syntax: 'If(bInit, init1, init2)') Next (Regular) Block[B15] Leaving: {R2} Entering: {R5} {R6} {R7} } .locals {R5} { CaptureIds: [9] .locals {R6} { CaptureIds: [8] .locals {R7} { CaptureIds: [7] Block[B15] - Block Predecessors: [B14] [B30] Statements (1) IFlowCaptureOperation: 7 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1') Jump if True (Regular) to Block[B17] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 7 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Leaving: {R7} Next (Regular) Block[B16] Block[B16] - Block Predecessors: [B15] Statements (1) IFlowCaptureOperation: 8 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 7 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B18] Leaving: {R7} } Block[B17] - Block Predecessors: [B15] Statements (1) IFlowCaptureOperation: 8 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2') Next (Regular) Block[B18] Block[B18] - Block Predecessors: [B16] [B17] Statements (1) IFlowCaptureOperation: 9 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i') Value: IFieldReferenceOperation: C.i As System.Double (OperationKind.FieldReference, Type: System.Double, IsImplicit) (Syntax: 'If(c1, c2).i') Instance Receiver: IFlowCaptureReferenceOperation: 8 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)') Next (Regular) Block[B19] Leaving: {R6} } Block[B19] - Block Predecessors: [B18] Statements (0) Jump if False (Regular) to Block[B21] IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: 'If(bStep, step1, step2)') Next (Regular) Block[B20] Block[B20] - Block Predecessors: [B19] Statements (0) Jump if False (Regular) to Block[B31] IBinaryOperation (BinaryOperatorKind.LessThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)') Left: IFlowCaptureReferenceOperation: 9 (OperationKind.FlowCaptureReference, Type: System.Double, IsImplicit) (Syntax: 'If(c1, c2).i') Right: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Double, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)') Leaving: {R5} {R1} Next (Regular) Block[B22] Leaving: {R5} Block[B21] - Block Predecessors: [B19] Statements (0) Jump if False (Regular) to Block[B31] IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)') Left: IFlowCaptureReferenceOperation: 9 (OperationKind.FlowCaptureReference, Type: System.Double, IsImplicit) (Syntax: 'If(c1, c2).i') Right: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Double, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)') Leaving: {R5} {R1} Next (Regular) Block[B22] Leaving: {R5} } Block[B22] - Block Predecessors: [B20] [B21] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = true') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsImplicit) (Syntax: 'result = true') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B23] Entering: {R8} {R9} {R10} .locals {R8} { CaptureIds: [12] [14] .locals {R9} { CaptureIds: [11] .locals {R10} { CaptureIds: [10] Block[B23] - Block Predecessors: [B22] Statements (1) IFlowCaptureOperation: 10 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1') Jump if True (Regular) to Block[B25] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 10 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Leaving: {R10} Next (Regular) Block[B24] Block[B24] - Block Predecessors: [B23] Statements (1) IFlowCaptureOperation: 11 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 10 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B26] Leaving: {R10} } Block[B25] - Block Predecessors: [B23] Statements (1) IFlowCaptureOperation: 11 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2') Next (Regular) Block[B26] Block[B26] - Block Predecessors: [B24] [B25] Statements (1) IFlowCaptureOperation: 12 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i') Value: IFieldReferenceOperation: C.i As System.Double (OperationKind.FieldReference, Type: System.Double, IsImplicit) (Syntax: 'If(c1, c2).i') Instance Receiver: IFlowCaptureReferenceOperation: 11 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)') Next (Regular) Block[B27] Leaving: {R9} Entering: {R11} } .locals {R11} { CaptureIds: [13] Block[B27] - Block Predecessors: [B26] Statements (1) IFlowCaptureOperation: 13 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1') Jump if True (Regular) to Block[B29] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 13 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Leaving: {R11} Next (Regular) Block[B28] Block[B28] - Block Predecessors: [B27] Statements (1) IFlowCaptureOperation: 14 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 13 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B30] Leaving: {R11} } Block[B29] - Block Predecessors: [B27] Statements (1) IFlowCaptureOperation: 14 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2') Next (Regular) Block[B30] Block[B30] - Block Predecessors: [B28] [B29] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i') Left: IFlowCaptureReferenceOperation: 12 (OperationKind.FlowCaptureReference, Type: System.Double, IsImplicit) (Syntax: 'If(c1, c2).i') Right: IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Double, IsImplicit) (Syntax: 'If(bStep, step1, step2)') Left: IFieldReferenceOperation: C.i As System.Double (OperationKind.FieldReference, Type: System.Double, IsImplicit) (Syntax: 'If(c1, c2).i') Instance Receiver: IFlowCaptureReferenceOperation: 14 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)') Right: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Double, IsImplicit) (Syntax: 'If(bStep, step1, step2)') Next (Regular) Block[B15] Leaving: {R8} Entering: {R5} {R6} {R7} } } Block[B31] - Exit Predecessors: [B20] [B21] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact> Public Sub ForToFlow_18() Dim source = <![CDATA[ Imports System Public Class C Sub M(c1 As C, c2 As C, bInit As Boolean, init1 As Double?, init2 As Double?, bLimit As Boolean, limit1 As Double?, limit2 As Double?, bStep As Boolean, step1 As Double?, step2 As Double?, result As Boolean) 'BIND:"Sub M" For If(c1, c2).i = If(bInit, init1, init2) To If(bLimit, limit1, limit2) Step If(bStep, step1, step2) result = true Next End Sub Public i As Double? End Class]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} {R3} {R4} .locals {R1} { CaptureIds: [4] [5] [6] .locals {R2} { CaptureIds: [2] [3] .locals {R3} { CaptureIds: [1] .locals {R4} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C) (Syntax: 'c1') Jump if True (Regular) to Block[B3] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Leaving: {R4} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B4] Leaving: {R4} } Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C) (Syntax: 'c2') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i') Value: IFieldReferenceOperation: C.i As System.Nullable(Of System.Double) (OperationKind.FieldReference, Type: System.Nullable(Of System.Double)) (Syntax: 'If(c1, c2).i') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)') Next (Regular) Block[B5] Leaving: {R3} } Block[B5] - Block Predecessors: [B4] Statements (0) Jump if False (Regular) to Block[B7] IParameterReferenceOperation: bInit (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bInit') Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init1') Value: IParameterReferenceOperation: init1 (OperationKind.ParameterReference, Type: System.Nullable(Of System.Double)) (Syntax: 'init1') Next (Regular) Block[B8] Block[B7] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init2') Value: IParameterReferenceOperation: init2 (OperationKind.ParameterReference, Type: System.Nullable(Of System.Double)) (Syntax: 'init2') Next (Regular) Block[B8] Block[B8] - Block Predecessors: [B6] [B7] Statements (0) Jump if False (Regular) to Block[B10] IParameterReferenceOperation: bLimit (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bLimit') Next (Regular) Block[B9] Block[B9] - Block Predecessors: [B8] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit1') Value: IParameterReferenceOperation: limit1 (OperationKind.ParameterReference, Type: System.Nullable(Of System.Double)) (Syntax: 'limit1') Next (Regular) Block[B11] Block[B10] - Block Predecessors: [B8] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit2') Value: IParameterReferenceOperation: limit2 (OperationKind.ParameterReference, Type: System.Nullable(Of System.Double)) (Syntax: 'limit2') Next (Regular) Block[B11] Block[B11] - Block Predecessors: [B9] [B10] Statements (0) Jump if False (Regular) to Block[B13] IParameterReferenceOperation: bStep (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bStep') Next (Regular) Block[B12] Block[B12] - Block Predecessors: [B11] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'step1') Value: IParameterReferenceOperation: step1 (OperationKind.ParameterReference, Type: System.Nullable(Of System.Double)) (Syntax: 'step1') Next (Regular) Block[B14] Block[B13] - Block Predecessors: [B11] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'step2') Value: IParameterReferenceOperation: step2 (OperationKind.ParameterReference, Type: System.Nullable(Of System.Double)) (Syntax: 'step2') Next (Regular) Block[B14] Block[B14] - Block Predecessors: [B12] [B13] Statements (0) Jump if False (Regular) to Block[B16] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'If(bStep, step1, step2)') Operand: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Double), IsImplicit) (Syntax: 'If(bStep, step1, step2)') Next (Regular) Block[B15] Block[B15] - Block Predecessors: [B14] Statements (1) IFlowCaptureOperation: 6 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(bStep, step1, step2)') Value: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False, IsImplicit) (Syntax: 'If(bStep, step1, step2)') Next (Regular) Block[B17] Block[B16] - Block Predecessors: [B14] Statements (1) IFlowCaptureOperation: 6 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(bStep, step1, step2)') Value: IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'If(bStep, step1, step2)') Left: IInvocationOperation ( Function System.Nullable(Of System.Double).GetValueOrDefault() As System.Double) (OperationKind.Invocation, Type: System.Double, IsImplicit) (Syntax: 'If(bStep, step1, step2)') Instance Receiver: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Double), IsImplicit) (Syntax: 'If(bStep, step1, step2)') Arguments(0) Right: ILiteralOperation (OperationKind.Literal, Type: System.Double, Constant: 0, IsImplicit) (Syntax: 'If(bStep, step1, step2)') Next (Regular) Block[B17] Block[B17] - Block Predecessors: [B15] [B16] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'If(bInit, init1, init2)') Left: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Double), IsImplicit) (Syntax: 'If(c1, c2).i') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Double), IsImplicit) (Syntax: 'If(bInit, init1, init2)') Next (Regular) Block[B18] Leaving: {R2} Entering: {R5} {R6} } .locals {R5} { CaptureIds: [8] .locals {R6} { CaptureIds: [7] Block[B18] - Block Predecessors: [B17] [B38] [B42] Statements (1) IFlowCaptureOperation: 7 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1') Jump if True (Regular) to Block[B20] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 7 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Leaving: {R6} Next (Regular) Block[B19] Block[B19] - Block Predecessors: [B18] Statements (1) IFlowCaptureOperation: 8 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 7 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B21] Leaving: {R6} } Block[B20] - Block Predecessors: [B18] Statements (1) IFlowCaptureOperation: 8 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2') Next (Regular) Block[B21] Block[B21] - Block Predecessors: [B19] [B20] Statements (0) Jump if False (Regular) to Block[B22] IBinaryOperation (BinaryOperatorKind.Or) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'If(bStep, step1, step2)') Left: IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)') Operand: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Double), IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)') Right: IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'If(c1, c2).i') Operand: IFieldReferenceOperation: C.i As System.Nullable(Of System.Double) (OperationKind.FieldReference, Type: System.Nullable(Of System.Double), IsImplicit) (Syntax: 'If(c1, c2).i') Instance Receiver: IFlowCaptureReferenceOperation: 8 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)') Leaving: {R5} Entering: {R7} {R8} {R9} Next (Regular) Block[B43] Leaving: {R5} {R1} } .locals {R7} { CaptureIds: [11] .locals {R8} { CaptureIds: [10] .locals {R9} { CaptureIds: [9] Block[B22] - Block Predecessors: [B21] Statements (1) IFlowCaptureOperation: 9 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1') Jump if True (Regular) to Block[B24] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 9 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Leaving: {R9} Next (Regular) Block[B23] Block[B23] - Block Predecessors: [B22] Statements (1) IFlowCaptureOperation: 10 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 9 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B25] Leaving: {R9} } Block[B24] - Block Predecessors: [B22] Statements (1) IFlowCaptureOperation: 10 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2') Next (Regular) Block[B25] Block[B25] - Block Predecessors: [B23] [B24] Statements (1) IFlowCaptureOperation: 11 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i') Value: IInvocationOperation ( Function System.Nullable(Of System.Double).GetValueOrDefault() As System.Double) (OperationKind.Invocation, Type: System.Double, IsImplicit) (Syntax: 'If(c1, c2).i') Instance Receiver: IFieldReferenceOperation: C.i As System.Nullable(Of System.Double) (OperationKind.FieldReference, Type: System.Nullable(Of System.Double), IsImplicit) (Syntax: 'If(c1, c2).i') Instance Receiver: IFlowCaptureReferenceOperation: 10 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)') Arguments(0) Next (Regular) Block[B26] Leaving: {R8} } Block[B26] - Block Predecessors: [B25] Statements (0) Jump if False (Regular) to Block[B28] IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: 'If(bStep, step1, step2)') Next (Regular) Block[B27] Block[B27] - Block Predecessors: [B26] Statements (0) Jump if False (Regular) to Block[B43] IBinaryOperation (BinaryOperatorKind.LessThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)') Left: IFlowCaptureReferenceOperation: 11 (OperationKind.FlowCaptureReference, Type: System.Double, IsImplicit) (Syntax: 'If(c1, c2).i') Right: IInvocationOperation ( Function System.Nullable(Of System.Double).GetValueOrDefault() As System.Double) (OperationKind.Invocation, Type: System.Double, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)') Instance Receiver: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Double), IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)') Arguments(0) Leaving: {R7} {R1} Next (Regular) Block[B29] Leaving: {R7} Block[B28] - Block Predecessors: [B26] Statements (0) Jump if False (Regular) to Block[B43] IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)') Left: IFlowCaptureReferenceOperation: 11 (OperationKind.FlowCaptureReference, Type: System.Double, IsImplicit) (Syntax: 'If(c1, c2).i') Right: IInvocationOperation ( Function System.Nullable(Of System.Double).GetValueOrDefault() As System.Double) (OperationKind.Invocation, Type: System.Double, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)') Instance Receiver: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Double), IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)') Arguments(0) Leaving: {R7} {R1} Next (Regular) Block[B29] Leaving: {R7} } Block[B29] - Block Predecessors: [B27] [B28] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = true') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsImplicit) (Syntax: 'result = true') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B30] Entering: {R10} {R11} {R12} .locals {R10} { CaptureIds: [14] .locals {R11} { CaptureIds: [13] .locals {R12} { CaptureIds: [12] Block[B30] - Block Predecessors: [B29] Statements (1) IFlowCaptureOperation: 12 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1') Jump if True (Regular) to Block[B32] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 12 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Leaving: {R12} Next (Regular) Block[B31] Block[B31] - Block Predecessors: [B30] Statements (1) IFlowCaptureOperation: 13 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 12 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B33] Leaving: {R12} } Block[B32] - Block Predecessors: [B30] Statements (1) IFlowCaptureOperation: 13 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2') Next (Regular) Block[B33] Block[B33] - Block Predecessors: [B31] [B32] Statements (1) IFlowCaptureOperation: 14 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i') Value: IFieldReferenceOperation: C.i As System.Nullable(Of System.Double) (OperationKind.FieldReference, Type: System.Nullable(Of System.Double), IsImplicit) (Syntax: 'If(c1, c2).i') Instance Receiver: IFlowCaptureReferenceOperation: 13 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)') Next (Regular) Block[B34] Leaving: {R11} Entering: {R13} {R14} } .locals {R13} { CaptureIds: [16] .locals {R14} { CaptureIds: [15] Block[B34] - Block Predecessors: [B33] Statements (1) IFlowCaptureOperation: 15 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1') Jump if True (Regular) to Block[B36] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 15 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Leaving: {R14} Next (Regular) Block[B35] Block[B35] - Block Predecessors: [B34] Statements (1) IFlowCaptureOperation: 16 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 15 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B37] Leaving: {R14} } Block[B36] - Block Predecessors: [B34] Statements (1) IFlowCaptureOperation: 16 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2') Next (Regular) Block[B37] Block[B37] - Block Predecessors: [B35] [B36] Statements (0) Jump if False (Regular) to Block[B39] IBinaryOperation (BinaryOperatorKind.Or) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'If(bStep, step1, step2)') Left: IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'If(bStep, step1, step2)') Operand: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Double), IsImplicit) (Syntax: 'If(bStep, step1, step2)') Right: IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'If(c1, c2).i') Operand: IFieldReferenceOperation: C.i As System.Nullable(Of System.Double) (OperationKind.FieldReference, Type: System.Nullable(Of System.Double), IsImplicit) (Syntax: 'If(c1, c2).i') Instance Receiver: IFlowCaptureReferenceOperation: 16 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)') Leaving: {R13} Entering: {R15} {R16} Next (Regular) Block[B38] Leaving: {R13} } Block[B38] - Block Predecessors: [B37] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i') Left: IFlowCaptureReferenceOperation: 14 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Double), IsImplicit) (Syntax: 'If(c1, c2).i') Right: IDefaultValueOperation (OperationKind.DefaultValue, Type: System.Nullable(Of System.Double), IsImplicit) (Syntax: 'If(c1, c2).i') Next (Regular) Block[B18] Leaving: {R10} Entering: {R5} {R6} .locals {R15} { CaptureIds: [18] .locals {R16} { CaptureIds: [17] Block[B39] - Block Predecessors: [B37] Statements (1) IFlowCaptureOperation: 17 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1') Jump if True (Regular) to Block[B41] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 17 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Leaving: {R16} Next (Regular) Block[B40] Block[B40] - Block Predecessors: [B39] Statements (1) IFlowCaptureOperation: 18 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 17 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B42] Leaving: {R16} } Block[B41] - Block Predecessors: [B39] Statements (1) IFlowCaptureOperation: 18 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2') Next (Regular) Block[B42] Block[B42] - Block Predecessors: [B40] [B41] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i') Left: IFlowCaptureReferenceOperation: 14 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Double), IsImplicit) (Syntax: 'If(c1, c2).i') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Nullable(Of System.Double), IsImplicit) (Syntax: 'If(bStep, step1, step2)') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (WideningNullable) Operand: IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Double, IsImplicit) (Syntax: 'If(bStep, step1, step2)') Left: IInvocationOperation ( Function System.Nullable(Of System.Double).GetValueOrDefault() As System.Double) (OperationKind.Invocation, Type: System.Double, IsImplicit) (Syntax: 'If(c1, c2).i') Instance Receiver: IFieldReferenceOperation: C.i As System.Nullable(Of System.Double) (OperationKind.FieldReference, Type: System.Nullable(Of System.Double), IsImplicit) (Syntax: 'If(c1, c2).i') Instance Receiver: IFlowCaptureReferenceOperation: 18 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)') Arguments(0) Right: IInvocationOperation ( Function System.Nullable(Of System.Double).GetValueOrDefault() As System.Double) (OperationKind.Invocation, Type: System.Double, IsImplicit) (Syntax: 'If(bStep, step1, step2)') Instance Receiver: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Double), IsImplicit) (Syntax: 'If(bStep, step1, step2)') Arguments(0) Next (Regular) Block[B18] Leaving: {R15} {R10} Entering: {R5} {R6} } } } Block[B43] - Exit Predecessors: [B21] [B27] [B28] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForToFlow_19() Dim source = <![CDATA[ Imports System Public Class C Sub M(i As Integer, result As Integer) 'BIND:"Sub M" For i = 0 To 4 Step 2 if result = i Exit For End If Next End Sub End Class]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [2] [3] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (5) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '0') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '4') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4') IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '2') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: '0') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: '0') Next (Regular) Block[B2] Leaving: {R2} } Block[B2] - Block Predecessors: [B1] [B4] Statements (0) Jump if False (Regular) to Block[B5] IBinaryOperation (BinaryOperatorKind.LessThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '4') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 4, IsImplicit) (Syntax: '4') Leaving: {R1} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (0) Jump if False (Regular) to Block[B4] IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'result = i') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result') Right: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') Next (Regular) Block[B5] Leaving: {R1} Block[B4] - Block Predecessors: [B3] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'i') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32, IsImplicit) (Syntax: '2') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: '2') Next (Regular) Block[B2] } Block[B5] - Exit Predecessors: [B2] [B3] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics, TestOptions.ReleaseDll.WithOverflowChecks(False)) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForToFlow_20() Dim source = <![CDATA[ Imports System Public Class C Sub M(i As Integer, result As Integer) 'BIND:"Sub M" For i = 0 To 4 Step 2 if result = i Continue For End If result = i Next End Sub End Class]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [2] [3] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (5) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '0') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '4') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4') IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '2') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: '0') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: '0') Next (Regular) Block[B2] Leaving: {R2} } Block[B2] - Block Predecessors: [B1] [B5] Statements (0) Jump if False (Regular) to Block[B6] IBinaryOperation (BinaryOperatorKind.LessThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '4') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 4, IsImplicit) (Syntax: '4') Leaving: {R1} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (0) Jump if False (Regular) to Block[B4] IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'result = i') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result') Right: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') Next (Regular) Block[B5] Block[B4] - Block Predecessors: [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'result = i') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result') Right: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'i') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32, IsImplicit) (Syntax: '2') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: '2') Next (Regular) Block[B2] } Block[B6] - Exit Predecessors: [B2] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics, TestOptions.ReleaseDll.WithOverflowChecks(False)) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForToFlow_21() Dim source = <![CDATA[ Imports System Public Class C Sub M(i As C, init As C, limit As C, [step] As C, result As C) 'BIND:"Sub M" For i = init To limit Step [step] result = i Next End Sub Public Shared Operator <=(x As C, y As C) As Boolean Return False End Operator Public Shared Operator -(x As C, y As C) As C Return Nothing End Operator Public Shared Operator +(x As C, y As C) As C Return Nothing End Operator End Class ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC33038: Type 'C' must define operator '>=' to be used in a 'For' statement. For i = init To limit Step [step] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC33033: Matching '>=' operator is required for 'Public Shared Operator <=(x As C, y As C) As Boolean'. Public Shared Operator <=(x As C, y As C) As Boolean ~~ ]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [2] [3] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (5) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'i') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'init') Value: IParameterReferenceOperation: init (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'init') IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'limit') Value: IParameterReferenceOperation: limit (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'limit') IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: '[step]') Value: IParameterReferenceOperation: step (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: '[step]') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsInvalid, IsImplicit) (Syntax: 'init') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'init') Next (Regular) Block[B2] Leaving: {R2} } Block[B2] - Block Predecessors: [B1] [B3] Statements (0) Jump if False (Regular) to Block[B4] IInvalidOperation (OperationKind.Invalid, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'limit') Children(2): IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i') IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'limit') Leaving: {R1} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'result = i') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: C) (Syntax: 'result') Right: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C) (Syntax: 'i') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsInvalid, IsImplicit) (Syntax: 'i') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: C, IsInvalid, IsImplicit) (Syntax: '[step]') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: '[step]') Next (Regular) Block[B2] } Block[B4] - Exit Predecessors: [B2] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForToFlow_22() Dim source = <![CDATA[ Imports System Public Class C Sub M(i As C, init As C, limit As C, [step] As C, result As C) 'BIND:"Sub M" For i = init To limit Step [step] result = i Next End Sub Public Shared Operator >=(x As C, y As C) As Boolean Return False End Operator Public Shared Operator -(x As C, y As C) As C Return Nothing End Operator Public Shared Operator +(x As C, y As C) As C Return Nothing End Operator End Class ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC33038: Type 'C' must define operator '<=' to be used in a 'For' statement. For i = init To limit Step [step] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC33033: Matching '<=' operator is required for 'Public Shared Operator >=(x As C, y As C) As Boolean'. Public Shared Operator >=(x As C, y As C) As Boolean ~~ ]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [2] [3] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (5) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'i') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'init') Value: IParameterReferenceOperation: init (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'init') IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'limit') Value: IParameterReferenceOperation: limit (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'limit') IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: '[step]') Value: IParameterReferenceOperation: step (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: '[step]') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsInvalid, IsImplicit) (Syntax: 'init') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'init') Next (Regular) Block[B2] Leaving: {R2} } Block[B2] - Block Predecessors: [B1] [B3] Statements (0) Jump if False (Regular) to Block[B4] IInvalidOperation (OperationKind.Invalid, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'limit') Children(2): IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i') IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'limit') Leaving: {R1} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'result = i') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: C) (Syntax: 'result') Right: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C) (Syntax: 'i') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsInvalid, IsImplicit) (Syntax: 'i') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: C, IsInvalid, IsImplicit) (Syntax: '[step]') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: '[step]') Next (Regular) Block[B2] } Block[B4] - Exit Predecessors: [B2] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForToFlow_23() Dim source = <![CDATA[ Imports System Public Class C Sub M(i As C, init As C, limit As C, [step] As C, result As C) 'BIND:"Sub M" For i = init To limit Step [step] result = i Next End Sub Public Shared Operator >=(x As C, y As C) As Boolean Return False End Operator Public Shared Operator <=(x As C, y As C) As Boolean Return False End Operator Public Shared Operator +(x As C, y As C) As C Return Nothing End Operator End Class ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC33038: Type 'C' must define operator '-' to be used in a 'For' statement. For i = init To limit Step [step] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [2] [3] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (5) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'i') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'init') Value: IParameterReferenceOperation: init (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'init') IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'limit') Value: IParameterReferenceOperation: limit (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'limit') IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: '[step]') Value: IParameterReferenceOperation: step (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: '[step]') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsInvalid, IsImplicit) (Syntax: 'init') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'init') Next (Regular) Block[B2] Leaving: {R2} } Block[B2] - Block Predecessors: [B1] [B3] Statements (0) Jump if False (Regular) to Block[B4] IInvalidOperation (OperationKind.Invalid, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'limit') Children(2): IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i') IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'limit') Leaving: {R1} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'result = i') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: C) (Syntax: 'result') Right: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C) (Syntax: 'i') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsInvalid, IsImplicit) (Syntax: 'i') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: C, IsInvalid, IsImplicit) (Syntax: '[step]') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: '[step]') Next (Regular) Block[B2] } Block[B4] - Exit Predecessors: [B2] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForToFlow_24() Dim source = <![CDATA[ Imports System Public Class C Sub M(i As C, init As C, limit As C, [step] As C, result As C) 'BIND:"Sub M" For i = init To limit Step [step] result = i Next End Sub Public Shared Operator >=(x As C, y As C) As Boolean Return False End Operator Public Shared Operator <=(x As C, y As C) As Boolean Return False End Operator Public Shared Operator -(x As C, y As C) As C Return Nothing End Operator End Class ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC33038: Type 'C' must define operator '+' to be used in a 'For' statement. For i = init To limit Step [step] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [2] [3] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (5) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'i') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'init') Value: IParameterReferenceOperation: init (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'init') IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'limit') Value: IParameterReferenceOperation: limit (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'limit') IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: '[step]') Value: IParameterReferenceOperation: step (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: '[step]') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsInvalid, IsImplicit) (Syntax: 'init') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'init') Next (Regular) Block[B2] Leaving: {R2} } Block[B2] - Block Predecessors: [B1] [B3] Statements (0) Jump if False (Regular) to Block[B4] IInvalidOperation (OperationKind.Invalid, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'limit') Children(2): IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i') IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'limit') Leaving: {R1} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'result = i') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: C) (Syntax: 'result') Right: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C) (Syntax: 'i') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsInvalid, IsImplicit) (Syntax: 'i') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: C, IsInvalid, IsImplicit) (Syntax: '[step]') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: '[step]') Next (Regular) Block[B2] } Block[B4] - Exit Predecessors: [B2] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForToFlow_25() Dim source = <![CDATA[ Imports System Public Class C Sub M(i As C, init As C, limit As C, [step] As C, result As C) 'BIND:"Sub M" For i = init To limit Step [step] result = i Next End Sub Public Shared Operator >=(x As C, y As C) As Boolean Return False End Operator Public Shared Operator <=(x As C, y As C) As Boolean Return False End Operator Public Shared Operator -(x As C, y As C) As C Return Nothing End Operator Public Shared Operator +(x As C, y As C) As C Return Nothing End Operator End Class ]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [2] [3] [4] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (6) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C) (Syntax: 'i') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init') Value: IParameterReferenceOperation: init (OperationKind.ParameterReference, Type: C) (Syntax: 'init') IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit') Value: IParameterReferenceOperation: limit (OperationKind.ParameterReference, Type: C) (Syntax: 'limit') IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '[step]') Value: IParameterReferenceOperation: step (OperationKind.ParameterReference, Type: C) (Syntax: '[step]') IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'For i = ini ... Step [step]') Value: IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual, Checked) (OperatorMethod: Function C.op_GreaterThanOrEqual(x As C, y As C) As System.Boolean) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'For i = ini ... Step [step]') Left: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: '[step]') Right: IBinaryOperation (BinaryOperatorKind.Subtract, Checked) (OperatorMethod: Function C.op_Subtraction(x As C, y As C) As C) (OperationKind.Binary, Type: C, IsImplicit) (Syntax: 'For i = ini ... Step [step]') Left: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: '[step]') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: '[step]') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'init') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'init') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} } .locals {R3} { CaptureIds: [5] Block[B2] - Block Predecessors: [B1] [B5] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'i') Jump if False (Regular) to Block[B4] IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: 'For i = ini ... Step [step]') Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (0) Jump if False (Regular) to Block[B6] IBinaryOperation (BinaryOperatorKind.LessThanOrEqual, Checked) (OperatorMethod: Function C.op_LessThanOrEqual(x As C, y As C) As System.Boolean) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'For i = ini ... Step [step]') Left: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'limit') Leaving: {R3} {R1} Next (Regular) Block[B5] Leaving: {R3} Block[B4] - Block Predecessors: [B2] Statements (0) Jump if False (Regular) to Block[B6] IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual, Checked) (OperatorMethod: Function C.op_GreaterThanOrEqual(x As C, y As C) As System.Boolean) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'For i = ini ... Step [step]') Left: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'limit') Leaving: {R3} {R1} Next (Regular) Block[B5] Leaving: {R3} } Block[B5] - Block Predecessors: [B3] [B4] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'result = i') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: C) (Syntax: 'result') Right: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C) (Syntax: 'i') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'i') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperatorMethod: Function C.op_Addition(x As C, y As C) As C) (OperationKind.Binary, Type: C, IsImplicit) (Syntax: 'For i = ini ... Step [step]') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: '[step]') Next (Regular) Block[B2] Entering: {R3} } Block[B6] - Exit Predecessors: [B3] [B4] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForToFlow_26() Dim source = <![CDATA[ Imports System Public Class C Sub M(i As C, init As C, limit As C, [step] As C, result As C) 'BIND:"Sub M" For i = init To limit Step [step] result = i Next End Sub Public Shared Operator >=(x As C, y As C) As C Return Nothing End Operator Public Shared Operator <=(x As C, y As C) As C Return Nothing End Operator Public Shared Operator -(x As C, y As C) As C Return Nothing End Operator Public Shared Operator +(x As C, y As C) As C Return Nothing End Operator End Class ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30311: Value of type 'C' cannot be converted to 'Boolean'. For i = init To limit Step [step] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [2] [3] [4] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (6) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'i') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'init') Value: IParameterReferenceOperation: init (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'init') IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'limit') Value: IParameterReferenceOperation: limit (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'limit') IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: '[step]') Value: IParameterReferenceOperation: step (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: '[step]') IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'For i = ini ... Step [step]') Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'For i = ini ... Step [step]') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (DelegateRelaxationLevelNone) Operand: IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual, Checked) (OperatorMethod: Function C.op_GreaterThanOrEqual(x As C, y As C) As C) (OperationKind.Binary, Type: C, IsInvalid, IsImplicit) (Syntax: 'For i = ini ... Step [step]') Left: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: '[step]') Right: IBinaryOperation (BinaryOperatorKind.Subtract, Checked) (OperatorMethod: Function C.op_Subtraction(x As C, y As C) As C) (OperationKind.Binary, Type: C, IsInvalid, IsImplicit) (Syntax: 'For i = ini ... Step [step]') Left: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: '[step]') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: '[step]') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsInvalid, IsImplicit) (Syntax: 'init') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'init') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} } .locals {R3} { CaptureIds: [5] Block[B2] - Block Predecessors: [B1] [B5] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i') Jump if False (Regular) to Block[B4] IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'For i = ini ... Step [step]') Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (0) Jump if False (Regular) to Block[B6] IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'For i = ini ... Step [step]') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (DelegateRelaxationLevelNone) Operand: IBinaryOperation (BinaryOperatorKind.LessThanOrEqual, Checked) (OperatorMethod: Function C.op_LessThanOrEqual(x As C, y As C) As C) (OperationKind.Binary, Type: C, IsInvalid, IsImplicit) (Syntax: 'For i = ini ... Step [step]') Left: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'limit') Leaving: {R3} {R1} Next (Regular) Block[B5] Leaving: {R3} Block[B4] - Block Predecessors: [B2] Statements (0) Jump if False (Regular) to Block[B6] IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'For i = ini ... Step [step]') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (DelegateRelaxationLevelNone) Operand: IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual, Checked) (OperatorMethod: Function C.op_GreaterThanOrEqual(x As C, y As C) As C) (OperationKind.Binary, Type: C, IsInvalid, IsImplicit) (Syntax: 'For i = ini ... Step [step]') Left: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'limit') Leaving: {R3} {R1} Next (Regular) Block[B5] Leaving: {R3} } Block[B5] - Block Predecessors: [B3] [B4] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'result = i') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: C) (Syntax: 'result') Right: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C) (Syntax: 'i') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsInvalid, IsImplicit) (Syntax: 'i') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperatorMethod: Function C.op_Addition(x As C, y As C) As C) (OperationKind.Binary, Type: C, IsInvalid, IsImplicit) (Syntax: 'For i = ini ... Step [step]') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: '[step]') Next (Regular) Block[B2] Entering: {R3} } Block[B6] - Exit Predecessors: [B3] [B4] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForToFlow_27() Dim source = <![CDATA[ Imports System Public Class C Sub M(i As C, init As C, limit As C, [step] As C, result As C) 'BIND:"Sub M" For i = init To limit Step [step] result = i Next End Sub Public Shared Operator >=(x As C, y As C) As C Return Nothing End Operator Public Shared Operator <=(x As C, y As C) As C Return Nothing End Operator Public Shared Operator -(x As C, y As C) As C Return Nothing End Operator Public Shared Operator +(x As C, y As C) As C Return Nothing End Operator Public Shared Operator IsTrue(x As C) As Boolean Return Nothing End Operator Public Shared Operator IsFalse(x As C) As Boolean Return Nothing End Operator End Class ]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [2] [3] [4] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (6) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C) (Syntax: 'i') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init') Value: IParameterReferenceOperation: init (OperationKind.ParameterReference, Type: C) (Syntax: 'init') IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit') Value: IParameterReferenceOperation: limit (OperationKind.ParameterReference, Type: C) (Syntax: 'limit') IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '[step]') Value: IParameterReferenceOperation: step (OperationKind.ParameterReference, Type: C) (Syntax: '[step]') IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'For i = ini ... Step [step]') Value: IUnaryOperation (UnaryOperatorKind.True) (OperatorMethod: Function C.op_True(x As C) As System.Boolean) (OperationKind.Unary, Type: System.Boolean, IsImplicit) (Syntax: 'For i = ini ... Step [step]') Operand: IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual, Checked) (OperatorMethod: Function C.op_GreaterThanOrEqual(x As C, y As C) As C) (OperationKind.Binary, Type: C, IsImplicit) (Syntax: 'For i = ini ... Step [step]') Left: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: '[step]') Right: IBinaryOperation (BinaryOperatorKind.Subtract, Checked) (OperatorMethod: Function C.op_Subtraction(x As C, y As C) As C) (OperationKind.Binary, Type: C, IsImplicit) (Syntax: 'For i = ini ... Step [step]') Left: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: '[step]') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: '[step]') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'init') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'init') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} } .locals {R3} { CaptureIds: [5] Block[B2] - Block Predecessors: [B1] [B5] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'i') Jump if False (Regular) to Block[B4] IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: 'For i = ini ... Step [step]') Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (0) Jump if False (Regular) to Block[B6] IUnaryOperation (UnaryOperatorKind.True) (OperatorMethod: Function C.op_True(x As C) As System.Boolean) (OperationKind.Unary, Type: System.Boolean, IsImplicit) (Syntax: 'For i = ini ... Step [step]') Operand: IBinaryOperation (BinaryOperatorKind.LessThanOrEqual, Checked) (OperatorMethod: Function C.op_LessThanOrEqual(x As C, y As C) As C) (OperationKind.Binary, Type: C, IsImplicit) (Syntax: 'For i = ini ... Step [step]') Left: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'limit') Leaving: {R3} {R1} Next (Regular) Block[B5] Leaving: {R3} Block[B4] - Block Predecessors: [B2] Statements (0) Jump if False (Regular) to Block[B6] IUnaryOperation (UnaryOperatorKind.True) (OperatorMethod: Function C.op_True(x As C) As System.Boolean) (OperationKind.Unary, Type: System.Boolean, IsImplicit) (Syntax: 'For i = ini ... Step [step]') Operand: IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual, Checked) (OperatorMethod: Function C.op_GreaterThanOrEqual(x As C, y As C) As C) (OperationKind.Binary, Type: C, IsImplicit) (Syntax: 'For i = ini ... Step [step]') Left: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'limit') Leaving: {R3} {R1} Next (Regular) Block[B5] Leaving: {R3} } Block[B5] - Block Predecessors: [B3] [B4] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'result = i') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: C) (Syntax: 'result') Right: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C) (Syntax: 'i') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'i') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperatorMethod: Function C.op_Addition(x As C, y As C) As C) (OperationKind.Binary, Type: C, IsImplicit) (Syntax: 'For i = ini ... Step [step]') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: '[step]') Next (Regular) Block[B2] Entering: {R3} } Block[B6] - Exit Predecessors: [B3] [B4] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForToFlow_28() Dim source = <![CDATA[ Imports System Public Structure C Sub M(i As C?, init As C?, limit As C?, [step] As C?, result As C?) 'BIND:"Sub M" For i = init To limit Step [step] result = i Next End Sub Public Shared Operator >=(x As C, y As C) As Boolean Return False End Operator Public Shared Operator <=(x As C, y As C) As Boolean Return False End Operator Public Shared Operator -(x As C, y As C) As C Return Nothing End Operator Public Shared Operator +(x As C, y As C) As C Return Nothing End Operator End Structure ]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [2] [3] [4] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (6) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of C)) (Syntax: 'i') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init') Value: IParameterReferenceOperation: init (OperationKind.ParameterReference, Type: System.Nullable(Of C)) (Syntax: 'init') IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit') Value: IParameterReferenceOperation: limit (OperationKind.ParameterReference, Type: System.Nullable(Of C)) (Syntax: 'limit') IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '[step]') Value: IParameterReferenceOperation: step (OperationKind.ParameterReference, Type: System.Nullable(Of C)) (Syntax: '[step]') IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'For i = ini ... Step [step]') Value: IInvocationOperation ( Function System.Nullable(Of System.Boolean).GetValueOrDefault() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'For i = ini ... Step [step]') Instance Receiver: IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual, IsLifted, Checked) (OperatorMethod: Function C.op_GreaterThanOrEqual(x As C, y As C) As System.Boolean) (OperationKind.Binary, Type: System.Nullable(Of System.Boolean), IsImplicit) (Syntax: 'For i = ini ... Step [step]') Left: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: '[step]') Right: IBinaryOperation (BinaryOperatorKind.Subtract, IsLifted, Checked) (OperatorMethod: Function C.op_Subtraction(x As C, y As C) As C) (OperationKind.Binary, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'For i = ini ... Step [step]') Left: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: '[step]') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: '[step]') Arguments(0) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'init') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'init') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} } .locals {R3} { CaptureIds: [5] Block[B2] - Block Predecessors: [B1] [B5] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'i') Jump if False (Regular) to Block[B4] IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: 'For i = ini ... Step [step]') Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (0) Jump if False (Regular) to Block[B6] IInvocationOperation ( Function System.Nullable(Of System.Boolean).GetValueOrDefault() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'For i = ini ... Step [step]') Instance Receiver: IBinaryOperation (BinaryOperatorKind.LessThanOrEqual, IsLifted, Checked) (OperatorMethod: Function C.op_LessThanOrEqual(x As C, y As C) As System.Boolean) (OperationKind.Binary, Type: System.Nullable(Of System.Boolean), IsImplicit) (Syntax: 'For i = ini ... Step [step]') Left: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'limit') Arguments(0) Leaving: {R3} {R1} Next (Regular) Block[B5] Leaving: {R3} Block[B4] - Block Predecessors: [B2] Statements (0) Jump if False (Regular) to Block[B6] IInvocationOperation ( Function System.Nullable(Of System.Boolean).GetValueOrDefault() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'For i = ini ... Step [step]') Instance Receiver: IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual, IsLifted, Checked) (OperatorMethod: Function C.op_GreaterThanOrEqual(x As C, y As C) As System.Boolean) (OperationKind.Binary, Type: System.Nullable(Of System.Boolean), IsImplicit) (Syntax: 'For i = ini ... Step [step]') Left: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'limit') Arguments(0) Leaving: {R3} {R1} Next (Regular) Block[B5] Leaving: {R3} } Block[B5] - Block Predecessors: [B3] [B4] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'result = i') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Nullable(Of C)) (Syntax: 'result') Right: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of C)) (Syntax: 'i') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'i') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Add, IsLifted, Checked) (OperatorMethod: Function C.op_Addition(x As C, y As C) As C) (OperationKind.Binary, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'For i = ini ... Step [step]') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: '[step]') Next (Regular) Block[B2] Entering: {R3} } Block[B6] - Exit Predecessors: [B3] [B4] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForToFlow_29() Dim source = <![CDATA[ Imports System Public Class C Sub M(c1 As C, c2 As C, bInit As Boolean, init1 As C, init2 As C, bLimit As Boolean, limit1 As C, limit2 As C, bStep As Boolean, step1 As C, step2 As C, result As Boolean) 'BIND:"Sub M" For If(c1, c2).i = If(bInit, init1, init2) To If(bLimit, limit1, limit2) Step If(bStep, step1, step2) result = true Next End Sub Public i As C Public Shared Operator >=(x As C, y As C) As Boolean Return False End Operator Public Shared Operator <=(x As C, y As C) As Boolean Return False End Operator Public Shared Operator -(x As C, y As C) As C Return Nothing End Operator Public Shared Operator +(x As C, y As C) As C Return Nothing End Operator End Class ]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} {R3} {R4} .locals {R1} { CaptureIds: [4] [5] [6] .locals {R2} { CaptureIds: [2] [3] .locals {R3} { CaptureIds: [1] .locals {R4} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C) (Syntax: 'c1') Jump if True (Regular) to Block[B3] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Leaving: {R4} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B4] Leaving: {R4} } Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C) (Syntax: 'c2') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i') Value: IFieldReferenceOperation: C.i As C (OperationKind.FieldReference, Type: C) (Syntax: 'If(c1, c2).i') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)') Next (Regular) Block[B5] Leaving: {R3} } Block[B5] - Block Predecessors: [B4] Statements (0) Jump if False (Regular) to Block[B7] IParameterReferenceOperation: bInit (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bInit') Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init1') Value: IParameterReferenceOperation: init1 (OperationKind.ParameterReference, Type: C) (Syntax: 'init1') Next (Regular) Block[B8] Block[B7] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init2') Value: IParameterReferenceOperation: init2 (OperationKind.ParameterReference, Type: C) (Syntax: 'init2') Next (Regular) Block[B8] Block[B8] - Block Predecessors: [B6] [B7] Statements (0) Jump if False (Regular) to Block[B10] IParameterReferenceOperation: bLimit (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bLimit') Next (Regular) Block[B9] Block[B9] - Block Predecessors: [B8] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit1') Value: IParameterReferenceOperation: limit1 (OperationKind.ParameterReference, Type: C) (Syntax: 'limit1') Next (Regular) Block[B11] Block[B10] - Block Predecessors: [B8] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit2') Value: IParameterReferenceOperation: limit2 (OperationKind.ParameterReference, Type: C) (Syntax: 'limit2') Next (Regular) Block[B11] Block[B11] - Block Predecessors: [B9] [B10] Statements (0) Jump if False (Regular) to Block[B13] IParameterReferenceOperation: bStep (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bStep') Next (Regular) Block[B12] Block[B12] - Block Predecessors: [B11] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'step1') Value: IParameterReferenceOperation: step1 (OperationKind.ParameterReference, Type: C) (Syntax: 'step1') Next (Regular) Block[B14] Block[B13] - Block Predecessors: [B11] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'step2') Value: IParameterReferenceOperation: step2 (OperationKind.ParameterReference, Type: C) (Syntax: 'step2') Next (Regular) Block[B14] Block[B14] - Block Predecessors: [B12] [B13] Statements (2) IFlowCaptureOperation: 6 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'For If(c1, ... ep1, step2)') Value: IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual, Checked) (OperatorMethod: Function C.op_GreaterThanOrEqual(x As C, y As C) As System.Boolean) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'For If(c1, ... ep1, step2)') Left: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(bStep, step1, step2)') Right: IBinaryOperation (BinaryOperatorKind.Subtract, Checked) (OperatorMethod: Function C.op_Subtraction(x As C, y As C) As C) (OperationKind.Binary, Type: C, IsImplicit) (Syntax: 'For If(c1, ... ep1, step2)') Left: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(bStep, step1, step2)') Right: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(bStep, step1, step2)') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'If(bInit, init1, init2)') Left: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2).i') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(bInit, init1, init2)') Next (Regular) Block[B15] Leaving: {R2} Entering: {R5} {R6} {R7} } .locals {R5} { CaptureIds: [9] .locals {R6} { CaptureIds: [8] .locals {R7} { CaptureIds: [7] Block[B15] - Block Predecessors: [B14] [B30] Statements (1) IFlowCaptureOperation: 7 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1') Jump if True (Regular) to Block[B17] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 7 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Leaving: {R7} Next (Regular) Block[B16] Block[B16] - Block Predecessors: [B15] Statements (1) IFlowCaptureOperation: 8 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 7 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B18] Leaving: {R7} } Block[B17] - Block Predecessors: [B15] Statements (1) IFlowCaptureOperation: 8 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2') Next (Regular) Block[B18] Block[B18] - Block Predecessors: [B16] [B17] Statements (1) IFlowCaptureOperation: 9 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i') Value: IFieldReferenceOperation: C.i As C (OperationKind.FieldReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2).i') Instance Receiver: IFlowCaptureReferenceOperation: 8 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)') Next (Regular) Block[B19] Leaving: {R6} } Block[B19] - Block Predecessors: [B18] Statements (0) Jump if False (Regular) to Block[B21] IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: 'For If(c1, ... ep1, step2)') Next (Regular) Block[B20] Block[B20] - Block Predecessors: [B19] Statements (0) Jump if False (Regular) to Block[B31] IBinaryOperation (BinaryOperatorKind.LessThanOrEqual, Checked) (OperatorMethod: Function C.op_LessThanOrEqual(x As C, y As C) As System.Boolean) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'For If(c1, ... ep1, step2)') Left: IFlowCaptureReferenceOperation: 9 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2).i') Right: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)') Leaving: {R5} {R1} Next (Regular) Block[B22] Leaving: {R5} Block[B21] - Block Predecessors: [B19] Statements (0) Jump if False (Regular) to Block[B31] IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual, Checked) (OperatorMethod: Function C.op_GreaterThanOrEqual(x As C, y As C) As System.Boolean) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'For If(c1, ... ep1, step2)') Left: IFlowCaptureReferenceOperation: 9 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2).i') Right: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)') Leaving: {R5} {R1} Next (Regular) Block[B22] Leaving: {R5} } Block[B22] - Block Predecessors: [B20] [B21] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = true') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsImplicit) (Syntax: 'result = true') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B23] Entering: {R8} {R9} {R10} .locals {R8} { CaptureIds: [12] [14] .locals {R9} { CaptureIds: [11] .locals {R10} { CaptureIds: [10] Block[B23] - Block Predecessors: [B22] Statements (1) IFlowCaptureOperation: 10 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1') Jump if True (Regular) to Block[B25] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 10 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Leaving: {R10} Next (Regular) Block[B24] Block[B24] - Block Predecessors: [B23] Statements (1) IFlowCaptureOperation: 11 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 10 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B26] Leaving: {R10} } Block[B25] - Block Predecessors: [B23] Statements (1) IFlowCaptureOperation: 11 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2') Next (Regular) Block[B26] Block[B26] - Block Predecessors: [B24] [B25] Statements (1) IFlowCaptureOperation: 12 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i') Value: IFieldReferenceOperation: C.i As C (OperationKind.FieldReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2).i') Instance Receiver: IFlowCaptureReferenceOperation: 11 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)') Next (Regular) Block[B27] Leaving: {R9} Entering: {R11} } .locals {R11} { CaptureIds: [13] Block[B27] - Block Predecessors: [B26] Statements (1) IFlowCaptureOperation: 13 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1') Jump if True (Regular) to Block[B29] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 13 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Leaving: {R11} Next (Regular) Block[B28] Block[B28] - Block Predecessors: [B27] Statements (1) IFlowCaptureOperation: 14 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 13 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B30] Leaving: {R11} } Block[B29] - Block Predecessors: [B27] Statements (1) IFlowCaptureOperation: 14 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2') Next (Regular) Block[B30] Block[B30] - Block Predecessors: [B28] [B29] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i') Left: IFlowCaptureReferenceOperation: 12 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2).i') Right: IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperatorMethod: Function C.op_Addition(x As C, y As C) As C) (OperationKind.Binary, Type: C, IsImplicit) (Syntax: 'For If(c1, ... ep1, step2)') Left: IFieldReferenceOperation: C.i As C (OperationKind.FieldReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2).i') Instance Receiver: IFlowCaptureReferenceOperation: 14 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)') Right: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(bStep, step1, step2)') Next (Regular) Block[B15] Leaving: {R8} Entering: {R5} {R6} {R7} } } Block[B31] - Exit Predecessors: [B20] [B21] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForToFlow_30() Dim source = <![CDATA[ Imports System Public Class C1 Sub M(c1 As C1, c2 As C1, bInit As Boolean, init1 As C?, init2 As C?, bLimit As Boolean, limit1 As C?, limit2 As C?, bStep As Boolean, step1 As C?, step2 As C?, result As Boolean) 'BIND:"Sub M" For If(c1, c2).i = If(bInit, init1, init2) To If(bLimit, limit1, limit2) Step If(bStep, step1, step2) result = true Next End Sub Public i As C? End Class Public Structure C Public Shared Operator >=(x As C, y As C) As Boolean Return False End Operator Public Shared Operator <=(x As C, y As C) As Boolean Return False End Operator Public Shared Operator -(x As C, y As C) As C Return Nothing End Operator Public Shared Operator +(x As C, y As C) As C Return Nothing End Operator End Structure ]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} {R3} {R4} .locals {R1} { CaptureIds: [4] [5] [6] .locals {R2} { CaptureIds: [2] [3] .locals {R3} { CaptureIds: [1] .locals {R4} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C1) (Syntax: 'c1') Jump if True (Regular) to Block[B3] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'c1') Leaving: {R4} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B4] Leaving: {R4} } Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C1) (Syntax: 'c2') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i') Value: IFieldReferenceOperation: C1.i As System.Nullable(Of C) (OperationKind.FieldReference, Type: System.Nullable(Of C)) (Syntax: 'If(c1, c2).i') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'If(c1, c2)') Next (Regular) Block[B5] Leaving: {R3} } Block[B5] - Block Predecessors: [B4] Statements (0) Jump if False (Regular) to Block[B7] IParameterReferenceOperation: bInit (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bInit') Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init1') Value: IParameterReferenceOperation: init1 (OperationKind.ParameterReference, Type: System.Nullable(Of C)) (Syntax: 'init1') Next (Regular) Block[B8] Block[B7] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init2') Value: IParameterReferenceOperation: init2 (OperationKind.ParameterReference, Type: System.Nullable(Of C)) (Syntax: 'init2') Next (Regular) Block[B8] Block[B8] - Block Predecessors: [B6] [B7] Statements (0) Jump if False (Regular) to Block[B10] IParameterReferenceOperation: bLimit (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bLimit') Next (Regular) Block[B9] Block[B9] - Block Predecessors: [B8] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit1') Value: IParameterReferenceOperation: limit1 (OperationKind.ParameterReference, Type: System.Nullable(Of C)) (Syntax: 'limit1') Next (Regular) Block[B11] Block[B10] - Block Predecessors: [B8] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit2') Value: IParameterReferenceOperation: limit2 (OperationKind.ParameterReference, Type: System.Nullable(Of C)) (Syntax: 'limit2') Next (Regular) Block[B11] Block[B11] - Block Predecessors: [B9] [B10] Statements (0) Jump if False (Regular) to Block[B13] IParameterReferenceOperation: bStep (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bStep') Next (Regular) Block[B12] Block[B12] - Block Predecessors: [B11] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'step1') Value: IParameterReferenceOperation: step1 (OperationKind.ParameterReference, Type: System.Nullable(Of C)) (Syntax: 'step1') Next (Regular) Block[B14] Block[B13] - Block Predecessors: [B11] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'step2') Value: IParameterReferenceOperation: step2 (OperationKind.ParameterReference, Type: System.Nullable(Of C)) (Syntax: 'step2') Next (Regular) Block[B14] Block[B14] - Block Predecessors: [B12] [B13] Statements (2) IFlowCaptureOperation: 6 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'For If(c1, ... ep1, step2)') Value: IInvocationOperation ( Function System.Nullable(Of System.Boolean).GetValueOrDefault() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'For If(c1, ... ep1, step2)') Instance Receiver: IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual, IsLifted, Checked) (OperatorMethod: Function C.op_GreaterThanOrEqual(x As C, y As C) As System.Boolean) (OperationKind.Binary, Type: System.Nullable(Of System.Boolean), IsImplicit) (Syntax: 'For If(c1, ... ep1, step2)') Left: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'If(bStep, step1, step2)') Right: IBinaryOperation (BinaryOperatorKind.Subtract, IsLifted, Checked) (OperatorMethod: Function C.op_Subtraction(x As C, y As C) As C) (OperationKind.Binary, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'For If(c1, ... ep1, step2)') Left: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'If(bStep, step1, step2)') Right: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'If(bStep, step1, step2)') Arguments(0) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'If(bInit, init1, init2)') Left: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'If(c1, c2).i') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'If(bInit, init1, init2)') Next (Regular) Block[B15] Leaving: {R2} Entering: {R5} {R6} {R7} } .locals {R5} { CaptureIds: [9] .locals {R6} { CaptureIds: [8] .locals {R7} { CaptureIds: [7] Block[B15] - Block Predecessors: [B14] [B30] Statements (1) IFlowCaptureOperation: 7 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C1, IsImplicit) (Syntax: 'c1') Jump if True (Regular) to Block[B17] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 7 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'c1') Leaving: {R7} Next (Regular) Block[B16] Block[B16] - Block Predecessors: [B15] Statements (1) IFlowCaptureOperation: 8 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 7 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B18] Leaving: {R7} } Block[B17] - Block Predecessors: [B15] Statements (1) IFlowCaptureOperation: 8 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C1, IsImplicit) (Syntax: 'c2') Next (Regular) Block[B18] Block[B18] - Block Predecessors: [B16] [B17] Statements (1) IFlowCaptureOperation: 9 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i') Value: IFieldReferenceOperation: C1.i As System.Nullable(Of C) (OperationKind.FieldReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'If(c1, c2).i') Instance Receiver: IFlowCaptureReferenceOperation: 8 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'If(c1, c2)') Next (Regular) Block[B19] Leaving: {R6} } Block[B19] - Block Predecessors: [B18] Statements (0) Jump if False (Regular) to Block[B21] IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: 'For If(c1, ... ep1, step2)') Next (Regular) Block[B20] Block[B20] - Block Predecessors: [B19] Statements (0) Jump if False (Regular) to Block[B31] IInvocationOperation ( Function System.Nullable(Of System.Boolean).GetValueOrDefault() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'For If(c1, ... ep1, step2)') Instance Receiver: IBinaryOperation (BinaryOperatorKind.LessThanOrEqual, IsLifted, Checked) (OperatorMethod: Function C.op_LessThanOrEqual(x As C, y As C) As System.Boolean) (OperationKind.Binary, Type: System.Nullable(Of System.Boolean), IsImplicit) (Syntax: 'For If(c1, ... ep1, step2)') Left: IFlowCaptureReferenceOperation: 9 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'If(c1, c2).i') Right: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)') Arguments(0) Leaving: {R5} {R1} Next (Regular) Block[B22] Leaving: {R5} Block[B21] - Block Predecessors: [B19] Statements (0) Jump if False (Regular) to Block[B31] IInvocationOperation ( Function System.Nullable(Of System.Boolean).GetValueOrDefault() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'For If(c1, ... ep1, step2)') Instance Receiver: IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual, IsLifted, Checked) (OperatorMethod: Function C.op_GreaterThanOrEqual(x As C, y As C) As System.Boolean) (OperationKind.Binary, Type: System.Nullable(Of System.Boolean), IsImplicit) (Syntax: 'For If(c1, ... ep1, step2)') Left: IFlowCaptureReferenceOperation: 9 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'If(c1, c2).i') Right: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)') Arguments(0) Leaving: {R5} {R1} Next (Regular) Block[B22] Leaving: {R5} } Block[B22] - Block Predecessors: [B20] [B21] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = true') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsImplicit) (Syntax: 'result = true') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B23] Entering: {R8} {R9} {R10} .locals {R8} { CaptureIds: [12] [14] .locals {R9} { CaptureIds: [11] .locals {R10} { CaptureIds: [10] Block[B23] - Block Predecessors: [B22] Statements (1) IFlowCaptureOperation: 10 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C1, IsImplicit) (Syntax: 'c1') Jump if True (Regular) to Block[B25] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 10 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'c1') Leaving: {R10} Next (Regular) Block[B24] Block[B24] - Block Predecessors: [B23] Statements (1) IFlowCaptureOperation: 11 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 10 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B26] Leaving: {R10} } Block[B25] - Block Predecessors: [B23] Statements (1) IFlowCaptureOperation: 11 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C1, IsImplicit) (Syntax: 'c2') Next (Regular) Block[B26] Block[B26] - Block Predecessors: [B24] [B25] Statements (1) IFlowCaptureOperation: 12 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i') Value: IFieldReferenceOperation: C1.i As System.Nullable(Of C) (OperationKind.FieldReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'If(c1, c2).i') Instance Receiver: IFlowCaptureReferenceOperation: 11 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'If(c1, c2)') Next (Regular) Block[B27] Leaving: {R9} Entering: {R11} } .locals {R11} { CaptureIds: [13] Block[B27] - Block Predecessors: [B26] Statements (1) IFlowCaptureOperation: 13 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C1, IsImplicit) (Syntax: 'c1') Jump if True (Regular) to Block[B29] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 13 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'c1') Leaving: {R11} Next (Regular) Block[B28] Block[B28] - Block Predecessors: [B27] Statements (1) IFlowCaptureOperation: 14 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 13 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B30] Leaving: {R11} } Block[B29] - Block Predecessors: [B27] Statements (1) IFlowCaptureOperation: 14 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C1, IsImplicit) (Syntax: 'c2') Next (Regular) Block[B30] Block[B30] - Block Predecessors: [B28] [B29] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i') Left: IFlowCaptureReferenceOperation: 12 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'If(c1, c2).i') Right: IBinaryOperation (BinaryOperatorKind.Add, IsLifted, Checked) (OperatorMethod: Function C.op_Addition(x As C, y As C) As C) (OperationKind.Binary, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'For If(c1, ... ep1, step2)') Left: IFieldReferenceOperation: C1.i As System.Nullable(Of C) (OperationKind.FieldReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'If(c1, c2).i') Instance Receiver: IFlowCaptureReferenceOperation: 14 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'If(c1, c2)') Right: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'If(bStep, step1, step2)') Next (Regular) Block[B15] Leaving: {R8} Entering: {R5} {R6} {R7} } } Block[B31] - Exit Predecessors: [B20] [B21] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForToFlow_31() Dim source = <![CDATA[ Imports System Public Class C Sub M(i As Object, init As Object, limit As Object, result As Object) 'BIND:"Sub M" For i = init To limit result = i Next End Sub End Class ]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [<anonymous local> As System.Object] Block[B1] - Block Predecessors: [B0] Statements (0) Jump if False (Regular) to Block[B3] IInvocationOperation (Function Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl.ForLoopInitObj(Counter As System.Object, Start As System.Object, Limit As System.Object, StepValue As System.Object, ByRef LoopForResult As System.Object, ByRef CounterResult As System.Object) As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'limit') Instance Receiver: null Arguments(6): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Counter) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i') IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Start) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'init') IParameterReferenceOperation: init (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'init') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Limit) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'limit') IParameterReferenceOperation: limit (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'limit') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: StepValue) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'For i = ini ... Next') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'For i = ini ... Next') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (WideningValue) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For i = ini ... Next') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: LoopForResult) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i') ILocalReferenceOperation: (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: CounterResult) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i') IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Object, IsImplicit) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Leaving: {R1} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] [B2] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object, IsImplicit) (Syntax: 'result = i') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'result') Right: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'i') Jump if False (Regular) to Block[B3] IInvocationOperation (Function Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl.ForNextCheckObj(Counter As System.Object, LoopObj As System.Object, ByRef CounterResult As System.Object) As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'limit') Instance Receiver: null Arguments(3): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Counter) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'limit') IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Object, IsImplicit) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: LoopObj) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'limit') ILocalReferenceOperation: (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: CounterResult) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'limit') IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Object, IsImplicit) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Leaving: {R1} Next (Regular) Block[B2] } Block[B3] - Exit Predecessors: [B1] [B2] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForToFlow_32() Dim source = <![CDATA[ Imports System Public Class C Sub M(init As Object, limit As Object, [step] as Object, result As Object) 'BIND:"Sub M" For i = init To limit Step [step] result = i Next End Sub End Class ]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [<anonymous local> As System.Object] [i As System.Object] Block[B1] - Block Predecessors: [B0] Statements (0) Jump if False (Regular) to Block[B3] IInvocationOperation (Function Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl.ForLoopInitObj(Counter As System.Object, Start As System.Object, Limit As System.Object, StepValue As System.Object, ByRef LoopForResult As System.Object, ByRef CounterResult As System.Object) As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'limit') Instance Receiver: null Arguments(6): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Counter) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i') ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Start) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'init') IParameterReferenceOperation: init (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'init') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Limit) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'limit') IParameterReferenceOperation: limit (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'limit') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: StepValue) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '[step]') IParameterReferenceOperation: step (OperationKind.ParameterReference, Type: System.Object) (Syntax: '[step]') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: LoopForResult) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i') ILocalReferenceOperation: (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: CounterResult) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i') ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Leaving: {R1} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] [B2] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object, IsImplicit) (Syntax: 'result = i') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'result') Right: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Object) (Syntax: 'i') Jump if False (Regular) to Block[B3] IInvocationOperation (Function Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl.ForNextCheckObj(Counter As System.Object, LoopObj As System.Object, ByRef CounterResult As System.Object) As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'limit') Instance Receiver: null Arguments(3): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Counter) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'limit') ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: LoopObj) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'limit') ILocalReferenceOperation: (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: CounterResult) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'limit') ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Leaving: {R1} Next (Regular) Block[B2] } Block[B3] - Exit Predecessors: [B1] [B2] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForToFlow_33() Dim source = <![CDATA[ Imports System Public Class C Sub M(c1 As C, c2 As C, bInit As Boolean, init1 As Object, init2 As Object, bLimit As Boolean, limit1 As Object, limit2 As Object, bStep As Boolean, step1 As Object, step2 As Object, result As Boolean) 'BIND:"Sub M" For If(c1, c2).i = If(bInit, init1, init2) To If(bLimit, limit1, limit2) Step If(bStep, step1, step2) result = true Next End Sub Public i As Object End Class ]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} {R3} {R4} .locals {R1} { Locals: [<anonymous local> As System.Object] .locals {R2} { CaptureIds: [2] [3] [4] [5] [7] .locals {R3} { CaptureIds: [1] .locals {R4} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C) (Syntax: 'c1') Jump if True (Regular) to Block[B3] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Leaving: {R4} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B4] Leaving: {R4} } Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C) (Syntax: 'c2') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i') Value: IFieldReferenceOperation: C.i As System.Object (OperationKind.FieldReference, Type: System.Object) (Syntax: 'If(c1, c2).i') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)') Next (Regular) Block[B5] Leaving: {R3} } Block[B5] - Block Predecessors: [B4] Statements (0) Jump if False (Regular) to Block[B7] IParameterReferenceOperation: bInit (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bInit') Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init1') Value: IParameterReferenceOperation: init1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'init1') Next (Regular) Block[B8] Block[B7] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init2') Value: IParameterReferenceOperation: init2 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'init2') Next (Regular) Block[B8] Block[B8] - Block Predecessors: [B6] [B7] Statements (0) Jump if False (Regular) to Block[B10] IParameterReferenceOperation: bLimit (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bLimit') Next (Regular) Block[B9] Block[B9] - Block Predecessors: [B8] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit1') Value: IParameterReferenceOperation: limit1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'limit1') Next (Regular) Block[B11] Block[B10] - Block Predecessors: [B8] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit2') Value: IParameterReferenceOperation: limit2 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'limit2') Next (Regular) Block[B11] Block[B11] - Block Predecessors: [B9] [B10] Statements (0) Jump if False (Regular) to Block[B13] IParameterReferenceOperation: bStep (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bStep') Next (Regular) Block[B12] Block[B12] - Block Predecessors: [B11] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'step1') Value: IParameterReferenceOperation: step1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'step1') Next (Regular) Block[B14] Entering: {R5} Block[B13] - Block Predecessors: [B11] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'step2') Value: IParameterReferenceOperation: step2 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'step2') Next (Regular) Block[B14] Entering: {R5} .locals {R5} { CaptureIds: [6] Block[B14] - Block Predecessors: [B12] [B13] Statements (1) IFlowCaptureOperation: 6 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1') Jump if True (Regular) to Block[B16] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Leaving: {R5} Next (Regular) Block[B15] Block[B15] - Block Predecessors: [B14] Statements (1) IFlowCaptureOperation: 7 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B17] Leaving: {R5} } Block[B16] - Block Predecessors: [B14] Statements (1) IFlowCaptureOperation: 7 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2') Next (Regular) Block[B17] Block[B17] - Block Predecessors: [B15] [B16] Statements (0) Jump if False (Regular) to Block[B27] IInvocationOperation (Function Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl.ForLoopInitObj(Counter As System.Object, Start As System.Object, Limit As System.Object, StepValue As System.Object, ByRef LoopForResult As System.Object, ByRef CounterResult As System.Object) As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)') Instance Receiver: null Arguments(6): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Counter) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i') IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'If(c1, c2).i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Start) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'If(bInit, init1, init2)') IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'If(bInit, init1, init2)') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Limit) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)') IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: StepValue) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'If(bStep, step1, step2)') IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'If(bStep, step1, step2)') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: LoopForResult) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i') ILocalReferenceOperation: (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'If(c1, c2).i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: CounterResult) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i') IFieldReferenceOperation: C.i As System.Object (OperationKind.FieldReference, Type: System.Object, IsImplicit) (Syntax: 'If(c1, c2).i') Instance Receiver: IFlowCaptureReferenceOperation: 7 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Leaving: {R2} {R1} Next (Regular) Block[B26] Leaving: {R2} } .locals {R6} { CaptureIds: [10] [12] .locals {R7} { CaptureIds: [9] .locals {R8} { CaptureIds: [8] Block[B18] - Block Predecessors: [B26] Statements (1) IFlowCaptureOperation: 8 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1') Jump if True (Regular) to Block[B20] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 8 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Leaving: {R8} Next (Regular) Block[B19] Block[B19] - Block Predecessors: [B18] Statements (1) IFlowCaptureOperation: 9 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 8 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B21] Leaving: {R8} } Block[B20] - Block Predecessors: [B18] Statements (1) IFlowCaptureOperation: 9 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2') Next (Regular) Block[B21] Block[B21] - Block Predecessors: [B19] [B20] Statements (1) IFlowCaptureOperation: 10 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i') Value: IFieldReferenceOperation: C.i As System.Object (OperationKind.FieldReference, Type: System.Object, IsImplicit) (Syntax: 'If(c1, c2).i') Instance Receiver: IFlowCaptureReferenceOperation: 9 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)') Next (Regular) Block[B22] Leaving: {R7} Entering: {R9} } .locals {R9} { CaptureIds: [11] Block[B22] - Block Predecessors: [B21] Statements (1) IFlowCaptureOperation: 11 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1') Jump if True (Regular) to Block[B24] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 11 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Leaving: {R9} Next (Regular) Block[B23] Block[B23] - Block Predecessors: [B22] Statements (1) IFlowCaptureOperation: 12 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 11 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B25] Leaving: {R9} } Block[B24] - Block Predecessors: [B22] Statements (1) IFlowCaptureOperation: 12 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2') Next (Regular) Block[B25] Block[B25] - Block Predecessors: [B23] [B24] Statements (0) Jump if False (Regular) to Block[B27] IInvocationOperation (Function Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl.ForNextCheckObj(Counter As System.Object, LoopObj As System.Object, ByRef CounterResult As System.Object) As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)') Instance Receiver: null Arguments(3): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Counter) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)') IFlowCaptureReferenceOperation: 10 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'If(c1, c2).i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: LoopObj) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)') ILocalReferenceOperation: (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'If(c1, c2).i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: CounterResult) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)') IFieldReferenceOperation: C.i As System.Object (OperationKind.FieldReference, Type: System.Object, IsImplicit) (Syntax: 'If(c1, c2).i') Instance Receiver: IFlowCaptureReferenceOperation: 12 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Leaving: {R6} {R1} Next (Regular) Block[B26] Leaving: {R6} } Block[B26] - Block Predecessors: [B17] [B25] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = true') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsImplicit) (Syntax: 'result = true') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B18] Entering: {R6} {R7} {R8} } Block[B27] - Exit Predecessors: [B17] [B25] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForToFlow_34() Dim source = <![CDATA[ Imports System Public Class C Sub M(c1 As C, c2 As C, init1 As Object, limit1 As Object, step1 As Object, result As Boolean) 'BIND:"Sub M" For If(c1, c2).i = init1 To limit1 Step step1 result = true Next End Sub Public i As Object End Class ]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} {R3} {R4} .locals {R1} { Locals: [<anonymous local> As System.Object] .locals {R2} { CaptureIds: [2] [3] [4] [5] [7] .locals {R3} { CaptureIds: [1] .locals {R4} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C) (Syntax: 'c1') Jump if True (Regular) to Block[B3] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Leaving: {R4} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B4] Leaving: {R4} } Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C) (Syntax: 'c2') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i') Value: IFieldReferenceOperation: C.i As System.Object (OperationKind.FieldReference, Type: System.Object) (Syntax: 'If(c1, c2).i') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)') Next (Regular) Block[B5] Leaving: {R3} } Block[B5] - Block Predecessors: [B4] Statements (3) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init1') Value: IParameterReferenceOperation: init1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'init1') IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit1') Value: IParameterReferenceOperation: limit1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'limit1') IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'step1') Value: IParameterReferenceOperation: step1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'step1') Next (Regular) Block[B6] Entering: {R5} .locals {R5} { CaptureIds: [6] Block[B6] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 6 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1') Jump if True (Regular) to Block[B8] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Leaving: {R5} Next (Regular) Block[B7] Block[B7] - Block Predecessors: [B6] Statements (1) IFlowCaptureOperation: 7 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B9] Leaving: {R5} } Block[B8] - Block Predecessors: [B6] Statements (1) IFlowCaptureOperation: 7 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2') Next (Regular) Block[B9] Block[B9] - Block Predecessors: [B7] [B8] Statements (0) Jump if False (Regular) to Block[B19] IInvocationOperation (Function Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl.ForLoopInitObj(Counter As System.Object, Start As System.Object, Limit As System.Object, StepValue As System.Object, ByRef LoopForResult As System.Object, ByRef CounterResult As System.Object) As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'limit1') Instance Receiver: null Arguments(6): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Counter) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i') IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'If(c1, c2).i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Start) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'init1') IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'init1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Limit) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'limit1') IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'limit1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: StepValue) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'step1') IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'step1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: LoopForResult) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i') ILocalReferenceOperation: (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'If(c1, c2).i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: CounterResult) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i') IFieldReferenceOperation: C.i As System.Object (OperationKind.FieldReference, Type: System.Object, IsImplicit) (Syntax: 'If(c1, c2).i') Instance Receiver: IFlowCaptureReferenceOperation: 7 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Leaving: {R2} {R1} Next (Regular) Block[B18] Leaving: {R2} } .locals {R6} { CaptureIds: [10] [12] .locals {R7} { CaptureIds: [9] .locals {R8} { CaptureIds: [8] Block[B10] - Block Predecessors: [B18] Statements (1) IFlowCaptureOperation: 8 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1') Jump if True (Regular) to Block[B12] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 8 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Leaving: {R8} Next (Regular) Block[B11] Block[B11] - Block Predecessors: [B10] Statements (1) IFlowCaptureOperation: 9 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 8 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B13] Leaving: {R8} } Block[B12] - Block Predecessors: [B10] Statements (1) IFlowCaptureOperation: 9 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2') Next (Regular) Block[B13] Block[B13] - Block Predecessors: [B11] [B12] Statements (1) IFlowCaptureOperation: 10 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i') Value: IFieldReferenceOperation: C.i As System.Object (OperationKind.FieldReference, Type: System.Object, IsImplicit) (Syntax: 'If(c1, c2).i') Instance Receiver: IFlowCaptureReferenceOperation: 9 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)') Next (Regular) Block[B14] Leaving: {R7} Entering: {R9} } .locals {R9} { CaptureIds: [11] Block[B14] - Block Predecessors: [B13] Statements (1) IFlowCaptureOperation: 11 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1') Jump if True (Regular) to Block[B16] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 11 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Leaving: {R9} Next (Regular) Block[B15] Block[B15] - Block Predecessors: [B14] Statements (1) IFlowCaptureOperation: 12 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 11 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B17] Leaving: {R9} } Block[B16] - Block Predecessors: [B14] Statements (1) IFlowCaptureOperation: 12 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2') Next (Regular) Block[B17] Block[B17] - Block Predecessors: [B15] [B16] Statements (0) Jump if False (Regular) to Block[B19] IInvocationOperation (Function Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl.ForNextCheckObj(Counter As System.Object, LoopObj As System.Object, ByRef CounterResult As System.Object) As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'limit1') Instance Receiver: null Arguments(3): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Counter) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'limit1') IFlowCaptureReferenceOperation: 10 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'If(c1, c2).i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: LoopObj) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'limit1') ILocalReferenceOperation: (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'If(c1, c2).i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: CounterResult) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'limit1') IFieldReferenceOperation: C.i As System.Object (OperationKind.FieldReference, Type: System.Object, IsImplicit) (Syntax: 'If(c1, c2).i') Instance Receiver: IFlowCaptureReferenceOperation: 12 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Leaving: {R6} {R1} Next (Regular) Block[B18] Leaving: {R6} } Block[B18] - Block Predecessors: [B9] [B17] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = true') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsImplicit) (Syntax: 'result = true') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B10] Entering: {R6} {R7} {R8} } Block[B19] - Exit Predecessors: [B9] [B17] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForToFlow_35() Dim source = <![CDATA[ Imports System Public Class C Sub M(i As Object, bInit As Boolean, init1 As Object, init2 As Object, limit1 As Object, step1 As Object, result As Boolean) 'BIND:"Sub M" For i = If(bInit, init1, init2) To limit1 Step step1 result = true Next End Sub End Class ]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous local> As System.Object] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'i') Jump if False (Regular) to Block[B3] IParameterReferenceOperation: bInit (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bInit') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init1') Value: IParameterReferenceOperation: init1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'init1') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init2') Value: IParameterReferenceOperation: init2 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'init2') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (0) Jump if False (Regular) to Block[B6] IInvocationOperation (Function Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl.ForLoopInitObj(Counter As System.Object, Start As System.Object, Limit As System.Object, StepValue As System.Object, ByRef LoopForResult As System.Object, ByRef CounterResult As System.Object) As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'limit1') Instance Receiver: null Arguments(6): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Counter) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i') IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Start) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'If(bInit, init1, init2)') IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'If(bInit, init1, init2)') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Limit) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'limit1') IParameterReferenceOperation: limit1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'limit1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: StepValue) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'step1') IParameterReferenceOperation: step1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'step1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: LoopForResult) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i') ILocalReferenceOperation: (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: CounterResult) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i') IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Object, IsImplicit) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Leaving: {R2} {R1} Next (Regular) Block[B5] Leaving: {R2} } Block[B5] - Block Predecessors: [B4] [B5] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = true') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsImplicit) (Syntax: 'result = true') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Jump if False (Regular) to Block[B6] IInvocationOperation (Function Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl.ForNextCheckObj(Counter As System.Object, LoopObj As System.Object, ByRef CounterResult As System.Object) As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'limit1') Instance Receiver: null Arguments(3): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Counter) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'limit1') IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Object, IsImplicit) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: LoopObj) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'limit1') ILocalReferenceOperation: (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: CounterResult) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'limit1') IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Object, IsImplicit) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Leaving: {R1} Next (Regular) Block[B5] } Block[B6] - Exit Predecessors: [B4] [B5] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForToFlow_36() Dim source = <![CDATA[ Imports System Public Class C Sub M(i As Object, init1 As Object, bLimit As Boolean, limit1 As Object, limit2 As Object, step1 As Object, result As Boolean) 'BIND:"Sub M" For i = init1 To If(bLimit, limit1, limit2) Step step1 result = true Next End Sub End Class ]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous local> As System.Object] .locals {R2} { CaptureIds: [0] [1] [2] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'i') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init1') Value: IParameterReferenceOperation: init1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'init1') Jump if False (Regular) to Block[B3] IParameterReferenceOperation: bLimit (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bLimit') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit1') Value: IParameterReferenceOperation: limit1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'limit1') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit2') Value: IParameterReferenceOperation: limit2 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'limit2') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (0) Jump if False (Regular) to Block[B6] IInvocationOperation (Function Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl.ForLoopInitObj(Counter As System.Object, Start As System.Object, Limit As System.Object, StepValue As System.Object, ByRef LoopForResult As System.Object, ByRef CounterResult As System.Object) As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)') Instance Receiver: null Arguments(6): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Counter) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i') IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Start) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'init1') IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'init1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Limit) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)') IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: StepValue) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'step1') IParameterReferenceOperation: step1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'step1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: LoopForResult) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i') ILocalReferenceOperation: (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: CounterResult) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i') IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Object, IsImplicit) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Leaving: {R2} {R1} Next (Regular) Block[B5] Leaving: {R2} } Block[B5] - Block Predecessors: [B4] [B5] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = true') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsImplicit) (Syntax: 'result = true') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Jump if False (Regular) to Block[B6] IInvocationOperation (Function Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl.ForNextCheckObj(Counter As System.Object, LoopObj As System.Object, ByRef CounterResult As System.Object) As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)') Instance Receiver: null Arguments(3): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Counter) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)') IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Object, IsImplicit) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: LoopObj) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)') ILocalReferenceOperation: (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: CounterResult) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)') IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Object, IsImplicit) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Leaving: {R1} Next (Regular) Block[B5] } Block[B6] - Exit Predecessors: [B4] [B5] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForToFlow_37() Dim source = <![CDATA[ Imports System Public Class C Sub M(i As Object, init1 As Object, limit1 As Object, bStep As Boolean, step1 As Object, step2 As Object, result As Boolean) 'BIND:"Sub M" For i = init1 To limit1 Step If(bStep, step1, step2) result = true Next End Sub End Class ]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous local> As System.Object] .locals {R2} { CaptureIds: [0] [1] [2] [3] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'i') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init1') Value: IParameterReferenceOperation: init1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'init1') IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit1') Value: IParameterReferenceOperation: limit1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'limit1') Jump if False (Regular) to Block[B3] IParameterReferenceOperation: bStep (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bStep') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'step1') Value: IParameterReferenceOperation: step1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'step1') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'step2') Value: IParameterReferenceOperation: step2 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'step2') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (0) Jump if False (Regular) to Block[B6] IInvocationOperation (Function Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl.ForLoopInitObj(Counter As System.Object, Start As System.Object, Limit As System.Object, StepValue As System.Object, ByRef LoopForResult As System.Object, ByRef CounterResult As System.Object) As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'limit1') Instance Receiver: null Arguments(6): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Counter) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i') IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Start) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'init1') IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'init1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Limit) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'limit1') IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'limit1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: StepValue) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'If(bStep, step1, step2)') IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'If(bStep, step1, step2)') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: LoopForResult) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i') ILocalReferenceOperation: (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: CounterResult) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i') IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Object, IsImplicit) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Leaving: {R2} {R1} Next (Regular) Block[B5] Leaving: {R2} } Block[B5] - Block Predecessors: [B4] [B5] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = true') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsImplicit) (Syntax: 'result = true') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Jump if False (Regular) to Block[B6] IInvocationOperation (Function Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl.ForNextCheckObj(Counter As System.Object, LoopObj As System.Object, ByRef CounterResult As System.Object) As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'limit1') Instance Receiver: null Arguments(3): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Counter) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'limit1') IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Object, IsImplicit) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: LoopObj) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'limit1') ILocalReferenceOperation: (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: CounterResult) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'limit1') IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Object, IsImplicit) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Leaving: {R1} Next (Regular) Block[B5] } Block[B6] - Exit Predecessors: [B4] [B5] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForToFlow_38() Dim source = <![CDATA[ Imports System Public Class C Sub M(i As Object, init As Object, limit As Object, result As Object) 'BIND:"Sub M" For i = init To limit result = i Next End Sub End Class ]]>.Value Dim compilation = CreateCompilationWithMscorlib45(source, options:=TestOptions.ReleaseDebugDll) Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [<anonymous local> As System.Object] Block[B1] - Block Predecessors: [B0] Statements (0) Jump if False (Regular) to Block[B3] IInvalidOperation (OperationKind.Invalid, Type: System.Boolean, IsImplicit) (Syntax: 'limit') Children(5): IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'i') IParameterReferenceOperation: init (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'init') IParameterReferenceOperation: limit (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'limit') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'For i = ini ... Next') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (WideningValue) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For i = ini ... Next') ILocalReferenceOperation: (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'i') Leaving: {R1} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] [B2] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object, IsImplicit) (Syntax: 'result = i') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'result') Right: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'i') Jump if False (Regular) to Block[B3] IInvalidOperation (OperationKind.Invalid, Type: System.Boolean, IsImplicit) (Syntax: 'limit') Children(2): IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Object, IsImplicit) (Syntax: 'i') ILocalReferenceOperation: (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'i') Leaving: {R1} Next (Regular) Block[B2] } Block[B3] - Exit Predecessors: [B1] [B2] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(compilation, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForToFlow_39() Dim source = <![CDATA[ Imports System Public Class C Sub M(i As Integer?, init As Integer?, limit As Integer?, [step] As Integer?, result As Integer?) 'BIND:"Sub M" For i = init To limit Step [step] result = i Next End Sub End Class ]]>.Value Dim compilation = CreateCompilationWithMscorlib45(source, options:=TestOptions.ReleaseDebugDll) compilation.MakeMemberMissing(SpecialMember.System_Nullable_T_GetValueOrDefault) Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [2] [3] [4] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (4) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'i') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init') Value: IParameterReferenceOperation: init (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'init') IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit') Value: IParameterReferenceOperation: limit (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'limit') IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '[step]') Value: IParameterReferenceOperation: step (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: '[step]') Jump if False (Regular) to Block[B3] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: '[step]') Operand: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: '[step]') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '[step]') Value: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False, IsImplicit) (Syntax: '[step]') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '[step]') Value: IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '[step]') Left: IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsImplicit) (Syntax: '[step]') Children(1): IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: '[step]') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: '[step]') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'init') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'init') Next (Regular) Block[B5] Leaving: {R2} } Block[B5] - Block Predecessors: [B4] [B11] [B12] Statements (0) Jump if False (Regular) to Block[B6] IBinaryOperation (BinaryOperatorKind.Or) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '[step]') Left: IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'limit') Operand: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'limit') Right: IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'i') Operand: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i') Entering: {R3} Next (Regular) Block[B13] Leaving: {R1} .locals {R3} { CaptureIds: [5] Block[B6] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsImplicit) (Syntax: 'i') Children(1): IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i') Jump if False (Regular) to Block[B8] IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: '[step]') Next (Regular) Block[B7] Block[B7] - Block Predecessors: [B6] Statements (0) Jump if False (Regular) to Block[B13] IBinaryOperation (BinaryOperatorKind.LessThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'limit') Left: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i') Right: IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsImplicit) (Syntax: 'limit') Children(1): IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'limit') Leaving: {R3} {R1} Next (Regular) Block[B9] Leaving: {R3} Block[B8] - Block Predecessors: [B6] Statements (0) Jump if False (Regular) to Block[B13] IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'limit') Left: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i') Right: IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsImplicit) (Syntax: 'limit') Children(1): IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'limit') Leaving: {R3} {R1} Next (Regular) Block[B9] Leaving: {R3} } Block[B9] - Block Predecessors: [B7] [B8] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'result = i') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'result') Right: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'i') Next (Regular) Block[B10] Entering: {R4} .locals {R4} { CaptureIds: [6] Block[B10] - Block Predecessors: [B9] Statements (1) IFlowCaptureOperation: 6 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i') Jump if False (Regular) to Block[B12] IBinaryOperation (BinaryOperatorKind.Or) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '[step]') Left: IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: '[step]') Operand: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: '[step]') Right: IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'i') Operand: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i') Next (Regular) Block[B11] Block[B11] - Block Predecessors: [B10] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'i') Left: IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i') Right: IDefaultValueOperation (OperationKind.DefaultValue, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i') Next (Regular) Block[B5] Leaving: {R4} Block[B12] - Block Predecessors: [B10] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'i') Left: IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: '[step]') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (WideningNullable) Operand: IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32, IsImplicit) (Syntax: '[step]') Left: IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsImplicit) (Syntax: 'i') Children(1): IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i') Right: IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsImplicit) (Syntax: '[step]') Children(1): IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: '[step]') Next (Regular) Block[B5] Leaving: {R4} } } Block[B13] - Exit Predecessors: [B5] [B7] [B8] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(compilation, expectedFlowGraph, expectedDiagnostics) End Sub End Class End Namespace
1
dotnet/roslyn
56,011
React to string comparison changing on .NET Core
The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
jaredpar
"2021-08-30T17:18:52Z"
"2021-08-30T20:20:04Z"
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
4d99cda6e446e77dbb302e26388c1093bd3ef569
React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
./src/Compilers/VisualBasic/Test/Semantic/Binding/BindingErrorTests.vb
' 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.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Imports Roslyn.Test.Utilities.TestMetadata Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests ' this place is dedicated to binding related error tests Public Class BindingErrorTests Inherits BasicTestBase #Region "Targeted Error Tests - please arrange tests in the order of error code" <Fact()> Public Sub BC0ERR_None_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="None"> <file name="a.vb"> Imports System Class TimerState Public Delegate Sub MyEventHandler(ByVal sender As Object, ByVal e As System.EventArgs) Private m_MyEvent As MyEventHandler Public Custom Event MyEvent As MyEventHandler RaiseEvent(ByVal sender As Object, ByVal e As System.EventArgs) m_MyEvent.Invoke(sender, e) End RaiseEvent AddHandler(ByVal value As MyEventHandler) m_MyEvent = DirectCast ( _ [Delegate].Combine(m_MyEvent, value), _ MyEventHandler) : End addHandler RemoveHandler(ByVal value As MyEventHandler) m_MyEvent = DirectCast ( _ [Delegate].RemoveAll(m_MyEvent, value), _ MyEventHandler) End RemoveHandler End Event End Class </file> </compilation>) CompilationUtils.AssertNoErrors(compilation) End Sub <Fact()> Public Sub BC0ERR_None_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="None"> <file name="a.vb"> Class AAA Private _name As String Public ReadOnly Property Name() As String Get Return _name : End Get End Property Private _age As String Public ReadOnly Property Age() As String Get Return _age : End Get End Property End Class </file> </compilation>) CompilationUtils.AssertNoErrors(compilation) End Sub <Fact()> Public Sub BC0ERR_None_3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="None"> <file name="a.vb"> Module M1 Function B As string Dim x = 1: End Function Function C As string Dim x = 2 :End Function End Module </file> </compilation>) CompilationUtils.AssertNoErrors(compilation) End Sub <Fact()> Public Sub BC0ERR_None_4() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="None"> <file name="a.vb"> Public Class S1 Public Sub New() Dim cond = True GoTo l1 If False Then l1: End If End Sub End Class </file> </compilation>) CompilationUtils.AssertNoErrors(compilation) End Sub <Fact()> Public Sub BC0ERR_None_5() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="None"> <file name="a.vb"> Public Structure S1 Function FOO As String Return "h" End Function Sub Main() FOO FOO() End Sub End Structure </file> </compilation>) CompilationUtils.AssertNoErrors(compilation) End Sub <Fact()> Public Sub BC0ERR_None_6() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="None"> <file name="a.vb"> Public Structure S1 Sub Main() dim a?()(,) as integer dim b(2) as integer dim c as integer(,) End Sub End Structure </file> </compilation>) CompilationUtils.AssertNoErrors(compilation) End Sub <Fact()> Public Sub BC0ERR_None_7() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="None"> <file name="a.vb"> Public Class D Public Class Foo Public x As Integer End Class Public Class FooD Inherits Foo Public Sub Baz() End Sub End Class End Class </file> </compilation>) CompilationUtils.AssertNoErrors(compilation) End Sub <Fact()> Public Sub BC0ERR_None_8() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="None"> <file name="a.vb"> Public Class D Public Shared Sub Main() Dim x As Integer = 1 Dim b As Boolean = x = 1 System.Console.Write(b ) Dim l As Long = 5 System.Console.Write(l &gt; 6 ) Dim f As Single = 25 System.Console.Write(f &gt;= 25 ) Dim d As Double = 3 System.Console.Write(d &lt;= f ) End Sub End Class </file> </compilation>) CompilationUtils.AssertNoErrors(compilation) End Sub <Fact()> Public Sub BC0ERR_None_9() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="None"> <file name="a.vb"> Public Class C Public Shared Sub Main() System.Console.Write("{0}{1}{2}{3}{4}{5}", "a", "b", "c", "d", "e", "f" ) End Sub End Class </file> </compilation>) CompilationUtils.AssertNoErrors(compilation) End Sub <Fact()> Public Sub BC0ERR_None_10() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="None"> <file name="a.vb"> Public Class D Public Class Moo(Of T) Public Sub Boo(x As T) Dim local As T = x End Sub End Class End Class </file> </compilation>) CompilationUtils.AssertNoErrors(compilation) End Sub <Fact()> Public Sub BC0ERR_None_11() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="None"> <file name="a.vb"> Public Class C public class Moo public shared S as integer end class Public Shared Sub Main() System.Console.Write(Moo.S ) Moo.S = 42 System.Console.Write(Moo.S ) End Sub End Class </file> </compilation>) CompilationUtils.AssertNoErrors(compilation) End Sub <Fact()> Public Sub BC0ERR_None_12() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="None"> <file name="a.vb"> Public Class C Private Shared Function M(ByVal x As Integer, ByVal y As Integer, ByVal z As Integer) As Integer Return y End Function Public Shared Sub Main() System.Console.Write(M(0, 42, 1)) End Sub End Class </file> </compilation>) CompilationUtils.AssertNoErrors(compilation) End Sub <Fact()> Public Sub BC0ERR_None_13() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="None"> <file name="a.vb"> Public Class C Private Shared Function M() As System.AppDomain dim y as object = System.AppDomain.CreateDomain("qq") dim z as System.AppDomain = ctype(y,System.AppDomain) return z End Function End Class </file> </compilation>) CompilationUtils.AssertNoErrors(compilation) End Sub <Fact()> Public Sub BC0ERR_None_14() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="None"> <file name="a.vb"> Imports System Class Program Public Class C Public Function Foo(ByVal p1 As Short, ByVal p2 As UShort) As UInteger Return CUShort (p1 + p2) End Function Public Function Foo(ByVal p1 As Short, ByVal p2 As String) As UInteger Return CUInt (p1) End Function Public Function Foo(ByVal p1 As Short, ByVal ParamArray p2 As UShort()) As UInteger Return CByte (p2(0) + p2(1)) End Function End Class End Class </file> </compilation>) CompilationUtils.AssertNoErrors(compilation) End Sub <Fact()> Public Sub BC0ERR_None_15() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="None"> <file name="a.vb"> Class C Private Property P As Integer End Class </file> </compilation>) CompilationUtils.AssertNoErrors(compilation) End Sub <Fact()> Public Sub BC0ERR_None_16() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BC0ERR_None_16"> <file name="a.vb"> Class Tests Public Sub New() End Sub Public Sub New(i As Integer) Me.New() End Sub Public Sub New(s As String) : Call Me.New(1) End Sub Public Sub New(s As Double) ' comment Call Me.New(1) End Sub End Class </file> </compilation>) CompilationUtils.AssertNoErrors(compilation) End Sub <Fact()> Public Sub BC0ERR_None_17() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BC0ERR_None_17"> <file name="a.vb"> Class Tests Public Sub New() End Sub Public Sub New(i As Integer) #Const a = 1 Me.New() End Sub End Class </file> </compilation>) CompilationUtils.AssertNoErrors(compilation) End Sub <Fact()> Public Sub BC0ERR_None_18() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BC0ERR_None_18"> <file name="a.vb"> Class Tests Public Sub New() End Sub Public Sub New(i As Integer) #Const a = 1 #If a = 0 Then Me.New() #End If Me.New() End Sub End Class </file> </compilation>) CompilationUtils.AssertNoErrors(compilation) End Sub <Fact()> Public Sub BC0ERR_None_19() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BC0ERR_None_19"> <file name="a.vb"> Class b Public Sub New(ParamArray t() As Integer) End Sub End Class Class d Inherits b Public Sub New() End Sub End Class </file> </compilation>) CompilationUtils.AssertNoErrors(compilation) End Sub <WorkItem(540629, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540629")> <Fact()> Public Sub BC30002ERR_UndefinedType1() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="InvalidModuleAttribute1"> <file name="a.vb"><![CDATA[ Imports System Class Outer <AttributeUsage(AttributeTargets.All)> Class MyAttribute Inherits Attribute End Class End Class <MyAttribute()> Class Test End Class ]]></file> </compilation>). VerifyDiagnostics(Diagnostic(ERRID.ERR_UndefinedType1, "MyAttribute").WithArguments("MyAttribute")) End Sub <Fact()> Public Sub BC30020ERR_IsOperatorRequiresReferenceTypes1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Public Structure zzz Shared Sub Main() Dim a As New yyy Dim b As New yyy System.Console.WriteLine(a Is b) b = a System.Console.WriteLine(a Is b) End Sub End Structure Public Structure yyy Public i As Integer Public Sub abc() System.Console.WriteLine(i) End Sub End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30020: 'Is' operator does not accept operands of type 'yyy'. Operands must be reference or nullable types. System.Console.WriteLine(a Is b) ~ BC30020: 'Is' operator does not accept operands of type 'yyy'. Operands must be reference or nullable types. System.Console.WriteLine(a Is b) ~ BC30020: 'Is' operator does not accept operands of type 'yyy'. Operands must be reference or nullable types. System.Console.WriteLine(a Is b) ~ BC30020: 'Is' operator does not accept operands of type 'yyy'. Operands must be reference or nullable types. System.Console.WriteLine(a Is b) ~ </expected>) End Sub <Fact()> Public Sub BC30020ERR_IsOperatorRequiresReferenceTypes1_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Interface I End Interface Class A End Class Class B(Of T As Structure) End Class Class C Shared Sub M1(Of T1)(_1 As T1) If _1 Is Nothing Then End If If Nothing Is _1 Then End If End Sub Shared Sub M2(Of T2 As Class)(_2 As T2) If _2 Is Nothing Then End If If Nothing Is _2 Then End If End Sub Shared Sub M3(Of T3 As Structure)(_3 As T3) If _3 Is Nothing Then End If If Nothing Is _3 Then End If End Sub Shared Sub M4(Of T4 As New)(_4 As T4) If _4 Is Nothing Then End If If Nothing Is _4 Then End If End Sub Shared Sub M5(Of T5 As I)(_5 As T5) If _5 Is Nothing Then End If If Nothing Is _5 Then End If End Sub Shared Sub M6(Of T6 As A)(_6 As T6) If _6 Is Nothing Then End If If Nothing Is _6 Then End If End Sub Shared Sub M7(Of T7 As U, U)(_7 As T7) If _7 Is Nothing Then End If If Nothing Is _7 Then End If End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30020: 'Is' operator does not accept operands of type 'T3'. Operands must be reference or nullable types. If _3 Is Nothing Then ~~ BC30020: 'Is' operator does not accept operands of type 'T3'. Operands must be reference or nullable types. If Nothing Is _3 Then ~~ </expected>) End Sub <Fact()> Public Sub BC30029ERR_CantRaiseBaseEvent() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="CantRaiseBaseEvent"> <file name="a.vb"> Option Explicit On Class class1 Public Event MyEvent() End Class Class class2 Inherits class1 Sub RaiseEvt() 'COMPILEERROR: BC30029,"MyEvent" RaiseEvent MyEvent() End Sub End Class </file> </compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_CantRaiseBaseEvent, "MyEvent")) End Sub <Fact()> Public Sub BC30030ERR_TryWithoutCatchOrFinally() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="TryWithoutCatchOrFinally"> <file name="a.vb"> Module M1 Sub Scen1() 'COMPILEERROR: BC30030, "Try" Try End Try End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30030: Try must have at least one 'Catch' or a 'Finally'. Try ~~~ </expected>) End Sub <Fact()> Public Sub BC30038ERR_StrictDisallowsObjectOperand1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="StrictDisallowsObjectOperand1"> <file name="a.vb"> Imports System Structure myStruct1 shared result = New Guid() And New Guid() End structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30452: Operator 'And' is not defined for types 'Guid' and 'Guid'. shared result = New Guid() And New Guid() ~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30038ERR_StrictDisallowsObjectOperand1_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="StrictDisallowsObjectOperand1"> <file name="a.vb"> Option Infer Off option Strict on Structure myStruct1 sub foo() Dim x1$ = "hi" Dim [dim] = "hi" &amp; "hello" Dim x31 As integer = x1 &amp; [dim] end sub End structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30209: Option Strict On requires all variable declarations to have an 'As' clause. Dim [dim] = "hi" &amp; "hello" ~~~~~ BC30038: Option Strict On prohibits operands of type Object for operator '&amp;'. Dim x31 As integer = x1 &amp; [dim] ~~~~~ </expected>) End Sub <Fact()> Public Sub BC30038ERR_StrictDisallowsObjectOperand1_1a() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="StrictDisallowsObjectOperand1"> <file name="a.vb"> <![CDATA[ option Strict on Structure myStruct1 sub foo() Dim x1$ = 33 & 2.34 'No inference here end sub End structure ]]> </file> </compilation>) AssertTheseEmitDiagnostics(compilation, <expected><![CDATA[ BC35000: Requested operation is not available because the runtime library function 'Microsoft.VisualBasic.CompilerServices.Conversions.ToString' is not defined. Dim x1$ = 33 & 2.34 'No inference here ~~ BC35000: Requested operation is not available because the runtime library function 'Microsoft.VisualBasic.CompilerServices.Conversions.ToString' is not defined. Dim x1$ = 33 & 2.34 'No inference here ~~~~ ]]></expected>) End Sub <Fact()> Public Sub BC30039ERR_LoopControlMustNotBeProperty() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Module M Sub M() For <x/>.@a = "" To "" Next End Sub End Module ]]></file> </compilation>, references:=XmlReferences) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC30039: Loop control variable cannot be a property or a late-bound indexed array. For <x/>.@a = "" To "" ~~~~~~~ BC30337: 'For' loop control variable cannot be of type 'String' because the type does not support the required operators. For <x/>.@a = "" To "" ~~~~~~~ ]]></errors>) End Sub <Fact()> Public Sub BC30039ERR_LoopControlMustNotBeProperty_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System Class C Property P() As Integer Dim F As Integer Sub Method1(A As Integer, ByRef B As Integer) ' error For Each P In {1} Next ' warning For Each F In {2} Next For Each Me.F In {3} Next For Each A In {4} Next For Each B In {5} Next End Sub Shared Sub Main() End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30039: Loop control variable cannot be a property or a late-bound indexed array. For Each P In {1} ~ </expected>) End Sub <Fact()> Public Sub BC30039ERR_LoopControlMustNotBeProperty_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Option Strict Off Option Infer On Public Class MyClass1 Public Property z As Integer Public Shared Sub Main() End Sub Public Sub Foo() For z = 1 To 10 Next For x = 1 To z Step z Next End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30039: Loop control variable cannot be a property or a late-bound indexed array. For z = 1 To 10 ~ </expected>) End Sub <Fact(), WorkItem(545641, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545641")> Public Sub MissingLatebindingHelpers() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class Program Shared Sub Main() Dim Result As Object For Result = 1 To 2 Next End Sub End Class </file> </compilation>) AssertTheseEmitDiagnostics(compilation, <expected> BC35000: Requested operation is not available because the runtime library function 'Microsoft.VisualBasic.CompilerServices.ObjectFlowControl+ForLoopControl.ForLoopInitObj' is not defined. For Result = 1 To 2 ~~~~~~~~~~~~~~~~~~~~ BC35000: Requested operation is not available because the runtime library function 'Microsoft.VisualBasic.CompilerServices.ObjectFlowControl+ForLoopControl.ForNextCheckObj' is not defined. For Result = 1 To 2 ~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub MissingLatebindingHelpersObjectFor() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Option Strict Off Imports System Class Program Shared Sub Main() Dim obj As Object = New cls1 obj.P1 = 42 ' assignment (Set) obj.P1() ' side-effect (Call) Console.WriteLine(obj.P1) ' value (Get) End Sub Class cls1 Private _p1 As Integer Public Property p1 As Integer Get Console.Write("Get") Return _p1 End Get Set(value As Integer) Console.Write("Set") _p1 = value End Set End Property End Class End Class </file> </compilation>) AssertTheseEmitDiagnostics(compilation, <expected> BC35000: Requested operation is not available because the runtime library function 'Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateSet' is not defined. obj.P1 = 42 ' assignment (Set) ~~~~~~~~~~~ BC35000: Requested operation is not available because the runtime library function 'Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateCall' is not defined. obj.P1() ' side-effect (Call) ~~~~~~ BC35000: Requested operation is not available because the runtime library function 'Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateGet' is not defined. Console.WriteLine(obj.P1) ' value (Get) ~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30043ERR_UseOfKeywordNotInInstanceMethod1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="UseOfKeywordNotInInstanceMethod1"> <file name="a.vb"> Class [ident1] Public k As Short Public Shared Function foo2() As String 'COMPILEERROR: BC30043, "Me" Me.k = 333 Return Nothing End Function End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30043: 'Me' is valid only within an instance method. Me.k = 333 ~~ </expected>) End Sub <Fact()> Public Sub BC30043ERR_UseOfKeywordNotInInstanceMethod1_WithinFieldInitializers() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="FieldsUsingMe"> <file name="a.vb"> Option strict on imports system Class C1 private f1 as integer = 21 private shared f2 as integer = Me.f1 + 1 End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30043: 'Me' is valid only within an instance method. private shared f2 as integer = Me.f1 + 1 ~~ </expected>) End Sub <Fact()> Public Sub BC30043ERR_UseOfKeywordNotInInstanceMethod1_MeInAttribute() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BC30043ERR_UseOfKeywordNotInInstanceMethod1_MeInAttribute"> <file name="a.vb"> Option Strict On Imports System Imports System.Reflection Imports System.Runtime.InteropServices &lt;Assembly: AssemblyCulture(Me.AAA)&gt; &lt;StructLayout(Me.AAA)&gt; Structure S1 End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30043: 'Me' is valid only within an instance method. &lt;Assembly: AssemblyCulture(Me.AAA)&gt; ~~ BC30043: 'Me' is valid only within an instance method. &lt;StructLayout(Me.AAA)&gt; ~~ </expected>) End Sub <Fact()> Public Sub BC30043ERR_UseOfKeywordNotInInstanceMethod1_MyBaseInAttribute() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BC30043ERR_UseOfKeywordNotInInstanceMethod1_MyBaseInAttribute"> <file name="a.vb"> Option Strict On Imports System Imports System.Reflection Imports System.Runtime.InteropServices &lt;Assembly: AssemblyCulture(MyBase.AAA)&gt; &lt;StructLayout(MyBase.AAA)&gt; Structure S1 End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30043: 'MyBase' is valid only within an instance method. &lt;Assembly: AssemblyCulture(MyBase.AAA)&gt; ~~~~~~ BC30043: 'MyBase' is valid only within an instance method. &lt;StructLayout(MyBase.AAA)&gt; ~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30043ERR_UseOfKeywordNotInInstanceMethod1_MyClassInAttribute() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BC30043ERR_UseOfKeywordNotInInstanceMethod1_MyClassInAttribute"> <file name="a.vb"> Option Strict On Imports System Imports System.Reflection Imports System.Runtime.InteropServices &lt;Assembly: AssemblyCulture(MyClass.AAA)&gt; &lt;StructLayout(MyClass.AAA)&gt; Structure S1 End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30043: 'MyClass' is valid only within an instance method. &lt;Assembly: AssemblyCulture(MyClass.AAA)&gt; ~~~~~~~ BC30043: 'MyClass' is valid only within an instance method. &lt;StructLayout(MyClass.AAA)&gt; ~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30043ERR_UseOfKeywordNotInInstanceMethod1_WithinFieldInitializers_MyBase() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BC30043ERR_UseOfKeywordNotInInstanceMethod1_WithinFieldInitializers_MyBase"> <file name="a.vb"> Option strict on imports system Class Base Shared Function GetBar(i As Integer) As Integer Return Nothing End Function End Class Class C2 Inherits Base Public Shared f As Func(Of Func(Of Integer, Integer)) = Function() New Func(Of Integer, Integer)(AddressOf MyBase.GetBar) Public Shared Property P As Integer = MyBase.GetBar(1) End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30043: 'MyBase' is valid only within an instance method. Function() New Func(Of Integer, Integer)(AddressOf MyBase.GetBar) ~~~~~~ BC30043: 'MyBase' is valid only within an instance method. Public Shared Property P As Integer = MyBase.GetBar(1) ~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30043ERR_UseOfKeywordNotInInstanceMethod1_WithinFieldInitializers_MyClass() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BC30043ERR_UseOfKeywordNotInInstanceMethod1_WithinFieldInitializers_MyClass"> <file name="a.vb"> Option strict on imports system Class C2 Shared Function GetBar(i As Integer) As Integer Return Nothing End Function Public Shared f As Func(Of Func(Of Integer, Integer)) = Function() New Func(Of Integer, Integer)(AddressOf MyClass.GetBar) Public Shared Property P As Integer = MyClass.GetBar(1) End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30043: 'MyClass' is valid only within an instance method. Function() New Func(Of Integer, Integer)(AddressOf MyClass.GetBar) ~~~~~~~ BC30043: 'MyClass' is valid only within an instance method. Public Shared Property P As Integer = MyClass.GetBar(1) ~~~~~~~ </expected>) End Sub <WorkItem(542958, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542958")> <Fact()> Public Sub BC30043ERR_UseOfKeywordNotInInstanceMethod1_MyClassInAttribute_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BC30043ERR_UseOfKeywordNotInInstanceMethod1_MyClassInAttribute"> <file name="a.vb"> Option Strict On Imports System Imports System.Runtime.InteropServices Public Class S1 Const str As String = "" &lt;MyAttribute(MyClass.color.blue)&gt; Sub foo() End Sub Shared Sub main() End Sub Enum color blue End Enum End Class Class MyAttribute Inherits Attribute Sub New(str As S1.color) End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30043: 'MyClass' is valid only within an instance method. &lt;MyAttribute(MyClass.color.blue)&gt; ~~~~~~~ </expected>) End Sub <WorkItem(542958, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542958")> <Fact()> Public Sub BC30043ERR_UseOfKeywordNotInInstanceMethod1_MeInAttribute_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BC30043ERR_UseOfKeywordNotInInstanceMethod1_MeInAttribute"> <file name="a.vb"> Option Strict On Imports System Imports System.Runtime.InteropServices Public Class S1 Const str As String = "" &lt;MyAttribute(Me.color.blue)&gt; Sub foo() End Sub Shared Sub main() End Sub Enum color blue End Enum End Class Class MyAttribute Inherits Attribute Sub New(str As S1.color) End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30043: 'Me' is valid only within an instance method. &lt;MyAttribute(Me.color.blue)&gt; ~~ </expected>) End Sub <WorkItem(542958, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542958")> <Fact()> Public Sub BC30043ERR_UseOfKeywordNotInInstanceMethod1_MyBaseInAttribute_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BC30043ERR_UseOfKeywordNotInInstanceMethod1_MyBaseInAttribute"> <file name="a.vb"> Option Strict On Imports System Imports System.Runtime.InteropServices Public Class BaseClass Enum color blue End Enum End Class Public Class S1 Inherits BaseClass &lt;MyAttribute(MyBase.color.blue)&gt; Sub foo() End Sub Shared Sub main() End Sub End Class Class MyAttribute Inherits Attribute Sub New(x As S1.color) End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30043: 'MyBase' is valid only within an instance method. &lt;MyAttribute(MyBase.color.blue)&gt; ~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30044ERR_UseOfKeywordFromStructure1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="UseOfKeywordFromStructure1"> <file name="a.vb"> Module M1 Structure S Public Overrides Function ToString() As String Return MyBase.ToString() End Function End Structure End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30044: 'MyBase' is not valid within a structure. Return MyBase.ToString() ~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30045ERR_BadAttributeConstructor1() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="BadAttributeConstructor1"> <file name="a.vb"><![CDATA[ Imports System Module M1 Class myattr1 Inherits Attribute Sub New(ByVal o() As c1) Me.o = o End Sub Public o() As c1 End Class Public Class c1 End Class <myattr1(Nothing)> Class Scen18 End Class Class myattr2 Inherits Attribute Sub New(ByVal o() As delegate1) Me.o = o End Sub Public o() As delegate1 End Class Delegate Sub delegate1() <myattr2(Nothing)> Class Scen20 End Class End Module ]]></file> </compilation>). VerifyDiagnostics(Diagnostic(ERRID.ERR_BadAttributeConstructor1, "myattr1").WithArguments("M1.c1()"), Diagnostic(ERRID.ERR_BadAttributeConstructor1, "myattr2").WithArguments("M1.delegate1()")) Dim scen18 = compilation.GlobalNamespace.GetTypeMember("M1").GetTypeMember("Scen18") Dim attribute = scen18.GetAttributes().Single() Assert.Equal("M1.myattr1(Nothing)", attribute.ToString()) Dim argument = attribute.CommonConstructorArguments(0) Assert.Null(argument.Type) End Sub <Fact, WorkItem(3380, "DevDiv_Projects/Roslyn")> Public Sub BC30046ERR_ParamArrayWithOptArgs() CreateCompilationWithMscorlib40(<compilation name="ERR_ParamArrayWithOptArgs"> <file name="a.vb"><![CDATA[ Class C1 Shared Sub Main() End Sub sub abc( optional k as string = "hi", paramarray s() as integer ) End Sub End Class ]]></file> </compilation>).VerifyDiagnostics( Diagnostic(ERRID.ERR_ParamArrayWithOptArgs, "s")) End Sub <Fact()> Public Sub BC30049ERR_ExpectedArray1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ExpectedArray1"> <file name="a.vb"> Module M1 Sub Main() Dim boolVar_12 As Boolean 'COMPILEERROR: BC30049, "boolVar_12" ReDim boolVar_12(120) 'COMPILEERROR: BC30049, "boolVar_12", BC30811, "as" ReDim boolVar_12(120, 130) End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30049: 'Redim' statement requires an array. ReDim boolVar_12(120) ~~~~~~~~~~ BC30049: 'Redim' statement requires an array. ReDim boolVar_12(120, 130) ~~~~~~~~~~ </expected>) End Sub <WorkItem(542209, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542209")> <Fact()> Public Sub BC30052ERR_ArrayRankLimit() CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="ArrayRankLimit"> <file name="a.vb"> Public Class C1 Dim S1(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32) As Byte Dim S2(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33) As Byte End Class </file> </compilation>).VerifyDiagnostics( Diagnostic(ERRID.ERR_ArrayRankLimit, "(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33)")) End Sub <Fact, WorkItem(2424, "https://github.com/dotnet/roslyn/issues/2424")> Public Sub BC30053ERR_AsNewArray_01() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="AsNewArray"> <file name="a.vb"> Module M1 Sub Foo() Dim c() As New System.Exception Dim d(), e() As New System.Exception Dim f(), g As New System.Exception Dim h, i() As New System.Exception End Sub Dim x() As New System.Exception Dim y(), z() As New System.Exception Dim u(), v As New System.Exception Dim w, q() As New System.Exception End Module </file> </compilation>) Dim expectedErrors1 = <errors> BC30053: Arrays cannot be declared with 'New'. Dim c() As New System.Exception ~~~ BC30053: Arrays cannot be declared with 'New'. Dim d(), e() As New System.Exception ~~~ BC30053: Arrays cannot be declared with 'New'. Dim d(), e() As New System.Exception ~~~ BC30053: Arrays cannot be declared with 'New'. Dim f(), g As New System.Exception ~~~ BC30053: Arrays cannot be declared with 'New'. Dim h, i() As New System.Exception ~~~ BC30053: Arrays cannot be declared with 'New'. Dim x() As New System.Exception ~~~ BC30053: Arrays cannot be declared with 'New'. Dim y(), z() As New System.Exception ~~~ BC30053: Arrays cannot be declared with 'New'. Dim y(), z() As New System.Exception ~~~ BC30053: Arrays cannot be declared with 'New'. Dim u(), v As New System.Exception ~~~ BC30053: Arrays cannot be declared with 'New'. Dim w, q() As New System.Exception ~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact, WorkItem(2424, "https://github.com/dotnet/roslyn/issues/2424")> Public Sub BC30053ERR_AsNewArray_02() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="AsNewArray"> <file name="a.vb"> Module M1 Sub Foo() Dim c(1) As New System.Exception Dim d(1), e(1) As New System.Exception Dim f(1), g As New System.Exception Dim h, i(1) As New System.Exception End Sub Dim x(1) As New System.Exception Dim y(1), z(1) As New System.Exception Dim u(1), v As New System.Exception Dim w, q(1) As New System.Exception End Module </file> </compilation>) Dim expectedErrors1 = <errors> BC30053: Arrays cannot be declared with 'New'. Dim c(1) As New System.Exception ~~~ BC30053: Arrays cannot be declared with 'New'. Dim d(1), e(1) As New System.Exception ~~~ BC30053: Arrays cannot be declared with 'New'. Dim d(1), e(1) As New System.Exception ~~~ BC30053: Arrays cannot be declared with 'New'. Dim f(1), g As New System.Exception ~~~ BC30053: Arrays cannot be declared with 'New'. Dim h, i(1) As New System.Exception ~~~ BC30053: Arrays cannot be declared with 'New'. Dim x(1) As New System.Exception ~~~~ BC30053: Arrays cannot be declared with 'New'. Dim y(1), z(1) As New System.Exception ~~~~ BC30053: Arrays cannot be declared with 'New'. Dim y(1), z(1) As New System.Exception ~~~~ BC30053: Arrays cannot be declared with 'New'. Dim u(1), v As New System.Exception ~~~~ BC30053: Arrays cannot be declared with 'New'. Dim w, q(1) As New System.Exception ~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC30057ERR_TooManyArgs1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="TooManyArgs1"> <file name="a.vb"> Module M1 Sub Main() test("CC", 15, 45) End Sub Sub test(ByVal name As String, ByVal age As Integer) End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30057: Too many arguments to 'Public Sub test(name As String, age As Integer)'. test("CC", 15, 45) ~~ </expected>) End Sub ' 30057 is better here <WorkItem(528720, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528720")> <Fact()> Public Sub BC30057ERR_TooManyArgs1_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ConstructorNotFound1"> <file name="a.vb"> Module M1 Sub FOO() Dim DynamicArray_2() As Byte Dim DynamicArray_3() As Long 'COMPILEERROR: BC30251, "New Byte(1, 2, 3, 4)" DynamicArray_2 = New Byte(1, 2, 3, 4) 'COMPILEERROR: BC30251, "New Byte(1)" DynamicArray_3 = New Long(1) Exit Sub End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30057: Too many arguments to 'Public Sub New()'. DynamicArray_2 = New Byte(1, 2, 3, 4) ~ BC30057: Too many arguments to 'Public Sub New()'. DynamicArray_3 = New Long(1) ~ </expected>) End Sub <Fact()> Public Sub BC30057ERR_TooManyArgs1_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ConstructorNotFound1"> <file name="a.vb"> Option Infer On Imports System Module Module1 Sub Main() Dim arr16 As New Integer(2, 3) { {1, 2}, {2, 1} }' Invalid End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30057: Too many arguments to 'Public Sub New()'. Dim arr16 As New Integer(2, 3) { {1, 2}, {2, 1} }' Invalid ~ BC30205: End of statement expected. Dim arr16 As New Integer(2, 3) { {1, 2}, {2, 1} }' Invalid ~ </expected>) End Sub <Fact()> Public Sub BC30057ERR_TooManyArgs1_3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ConstructorNotFound1"> <file name="a.vb"> Option Strict On Imports System Module Module1 Sub Main() Dim myArray8 As Integer(,) = New Integer(,) 1,2,3,4,5 End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30057: Too many arguments to 'Public Sub New()'. Dim myArray8 As Integer(,) = New Integer(,) 1,2,3,4,5 ~ BC30205: End of statement expected. Dim myArray8 As Integer(,) = New Integer(,) 1,2,3,4,5 ~ </expected>) End Sub <Fact()> Public Sub BC30059ERR_RequiredConstExpr_fields() Dim source = <compilation> <file name="a.vb"> Option Strict On option Infer On imports system Imports microsoft.visualbasic.strings Class A Public Const X As Integer = 1 End Class Class B Sub New(x As Action) End Sub Sub New(x As Integer) End Sub Public Const X As Integer = 2 End Class Class C Sub New(x As Integer) End Sub Public Const X As Integer = 3 End Class Class D Sub New(x As Func(Of Integer)) End Sub Public Const X As Integer = 4 End Class Class C1 Public Delegate Sub SubDel(p as integer) Public Shared Sub foo(p as Integer) Console.WriteLine("DelegateField works :) " + p.ToString()) End Sub public shared function f() as integer return 23 end function ' should work because of const propagation public const f1 as integer = 1 + 1 '' should not work Public const f2 as SubDel = AddressOf C1.foo public const f3 as integer = C1.f() public const f4,f5 as integer = C1.f() '' should also give a BC30059 for inferred types public const f6 as object = new C1() public const f7 = new C1() public const f8 as integer = Asc(chrW(255)) ' > 127 are not const public const f9() as integer = new integer() {1, 2} public const f10 = new integer() {1, 2} public const f11 = GetType(Integer) public const f12 as system.type = GetType(Integer) public const f13 as integer = cint(cint(cbyte("1"))) public const f14 as integer = cint(cint(cbyte(1))) ' works public const f15 as long = clng(cint(cbyte("1"))) public const f16 as long = clng(cint(cbyte(1))) ' works public const ValueWorks1 as Integer = new C(23).X public const ValueWorks2 as Integer = new A().X public const ValueWorks3 as Integer = 23 + new A().X public const ValueWorks4 as Integer = if(nothing, 23) public const ValueWorks5 as Integer = if(23 = 42, 23, 42) public const ValueWorks6 as Integer = if(new A().X = 0, 23, 42) public const ValueWorks7 as Integer = if(new A(), nothing).X public const ValueWorks8 as Integer = if(23 = 42, 23, new A().X) public const ValueWorks9 as Integer = if(23 = 42, new A().X, 42) public const ValueWorks10 as Integer = CType("12", Integer).MaxValue ' needs option strict off ... public const ValueWorks11 as Integer = New B(Sub() Exit Sub).X public const ValueWorks12 = New D(Function() 23).X public const ValueDoesntWork1 as Integer = f() public const ValueDoesntWork2 as Integer = 1 + f() public const ValueDoesntWork3 as Integer = f() + 1 Public shared Sub Main(args() as string) End sub End Class </file> </compilation> Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) CompilationUtils.AssertTheseDiagnostics(c1, <expected> BC30424: Constants must be of an intrinsic or enumerated type, not a class, structure, type parameter, or array type. Public const f2 as SubDel = AddressOf C1.foo ~~~~~~ BC30059: Constant expression is required. public const f3 as integer = C1.f() ~~~~~~ BC30671: Explicit initialization is not permitted with multiple variables declared with a single type specifier. public const f4,f5 as integer = C1.f() ~~~~~~~~~~~~~~~~~~~~~~~~~ BC30059: Constant expression is required. public const f4,f5 as integer = C1.f() ~~~~~~ BC30059: Constant expression is required. public const f6 as object = new C1() ~~~~~~~~ BC30059: Constant expression is required. public const f7 = new C1() ~~~~~~~~ BC30059: Constant expression is required. public const f8 as integer = Asc(chrW(255)) ' > 127 are not const ~~~~~~~~~~~~~~ BC30424: Constants must be of an intrinsic or enumerated type, not a class, structure, type parameter, or array type. public const f9() as integer = new integer() {1, 2} ~~ BC30059: Constant expression is required. public const f10 = new integer() {1, 2} ~~~~~~~~~~~~~~~~~~~~ BC30059: Constant expression is required. public const f11 = GetType(Integer) ~~~~~~~~~~~~~~~~ BC30424: Constants must be of an intrinsic or enumerated type, not a class, structure, type parameter, or array type. public const f12 as system.type = GetType(Integer) ~~~~~~~~~~~ BC30060: Conversion from 'String' to 'Byte' cannot occur in a constant expression. public const f13 as integer = cint(cint(cbyte("1"))) ~~~ BC30060: Conversion from 'String' to 'Byte' cannot occur in a constant expression. public const f15 as long = clng(cint(cbyte("1"))) ~~~ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. public const ValueWorks1 as Integer = new C(23).X ~~~~~~~~~~~ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. public const ValueWorks2 as Integer = new A().X ~~~~~~~~~ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. public const ValueWorks3 as Integer = 23 + new A().X ~~~~~~~~~ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. public const ValueWorks6 as Integer = if(new A().X = 0, 23, 42) ~~~~~~~~~ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. public const ValueWorks7 as Integer = if(new A(), nothing).X ~~~~~~~~~~~~~~~~~~~~~~ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. public const ValueWorks8 as Integer = if(23 = 42, 23, new A().X) ~~~~~~~~~ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. public const ValueWorks9 as Integer = if(23 = 42, new A().X, 42) ~~~~~~~~~ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. public const ValueWorks10 as Integer = CType("12", Integer).MaxValue ' needs option strict off ... ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. public const ValueWorks11 as Integer = New B(Sub() Exit Sub).X ~~~~~~~~~~~~~~~~~~~~~~~ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. public const ValueWorks12 = New D(Function() 23).X ~~~~~~~~~~~~~~~~~~~~~~ BC30059: Constant expression is required. public const ValueDoesntWork1 as Integer = f() ~~~ BC30059: Constant expression is required. public const ValueDoesntWork2 as Integer = 1 + f() ~~~ BC30059: Constant expression is required. public const ValueDoesntWork3 as Integer = f() + 1 ~~~ </expected>) End Sub ' The non-constant initializer should result in ' a single error, even if declaring multiple fields. <Fact()> Public Sub BC30059ERR_RequiredConstExpr_2() Dim source = <compilation> <file name="a.vb"> Option Strict On Module M Const A, B As Integer = F() Function F() As Integer Return 0 End Function End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) compilation.AssertTheseDiagnostics( <expected> BC30671: Explicit initialization is not permitted with multiple variables declared with a single type specifier. Const A, B As Integer = F() ~~~~~~~~~~~~~~~~~~~~~ BC30059: Constant expression is required. Const A, B As Integer = F() ~~~ </expected>) End Sub <Fact()> Public Sub BC30059ERR_RequiredConstExpr_locals() Dim source = <compilation> <file name="a.vb"> Option strict off imports system Imports microsoft.visualbasic.strings Class A Public Const X As Integer = 1 End Class Class B Sub New(x As Action) End Sub Sub New(x As Integer) End Sub Public Const X As Integer = 2 End Class Class C Sub New(x As Integer) End Sub Public Const X As Integer = 3 End Class Class D Sub New(x As Func(Of Integer)) End Sub Public Const X As Integer = 4 End Class Class C1 Public Delegate Sub SubDel(p as integer) Public Shared Sub foo(p as Integer) Console.WriteLine("DelegateField works :) " + p.ToString()) End Sub public shared function f() as integer return 23 end function Public Sub Main() ' should work because of const propagation const f1 as integer = 1 + 1 ' should not work const f2 as SubDel = AddressOf C1.foo const f3 as integer = C1.f() const f4,f5 as integer = C1.f() ' should also give a BC30059 for inferred types const f6 as object = new C1() const f7 = new C1() const f8 as integer = Asc(chrW(255)) ' > 127 are not const const f9() as integer = new integer() {1, 2} const f10 = new integer() {1, 2} const f11 = GetType(Integer) const f12 as system.type = GetType(Integer) const f13 as integer = cint(cint(cbyte("1"))) const f14 as integer = cint(cint(cbyte(1))) ' works const f15 as long = clng(cint(cbyte("1"))) const f16 as long = clng(cint(cbyte(1))) ' works const ValueWorks1 as Integer = new C(23).X const ValueWorks2 as Integer = new A().X const ValueWorks3 as Integer = 23 + new A().X const ValueWorks4 as Integer = if(nothing, 23) const ValueWorks5 as Integer = if(23 = 42, 23, 42) const ValueWorks6 as Integer = if(new A().X = 0, 23, 42) const ValueWorks7 as Integer = if(new A(), nothing).X const ValueWorks8 as Integer = if(23 = 42, 23, new A().X) const ValueWorks9 as Integer = if(23 = 42, new A().X, 42) const ValueWorks10 as Integer = CType("12", Integer).MaxValue ' needs option strict off ... const ValueWorks11 as Integer = New B(Sub() Exit Sub).X const ValueWorks12 as Integer = New D(Function() 23).X const ValueDoesntWork1 as Integer = f() Dim makeThemUsed as long = f1 + f3 + f4 + f5 + f8 + f13 + f14 + f15 + f16 + ValueWorks1 + ValueWorks2 + ValueWorks3 + ValueWorks4 + ValueWorks5 + ValueWorks6 + ValueWorks7 + ValueWorks8 + ValueWorks9 + ValueWorks10 + ValueWorks11 + ValueWorks12 End Sub End Class </file> </compilation> Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) CompilationUtils.AssertTheseDiagnostics(c1, <expected> BC30424: Constants must be of an intrinsic or enumerated type, not a class, structure, type parameter, or array type. const f2 as SubDel = AddressOf C1.foo ~~~~~~ BC30059: Constant expression is required. const f3 as integer = C1.f() ~~~~~~ BC30438: Constants must have a value. const f4,f5 as integer = C1.f() ~~ BC30671: Explicit initialization is not permitted with multiple variables declared with a single type specifier. const f4,f5 as integer = C1.f() ~~~~~~~~~~~~~~~~~~~~~~~~~ BC30059: Constant expression is required. const f4,f5 as integer = C1.f() ~~~~~~ BC30059: Constant expression is required. const f6 as object = new C1() ~~~~~~~~ BC30059: Constant expression is required. const f7 = new C1() ~~~~~~~~ BC30059: Constant expression is required. const f8 as integer = Asc(chrW(255)) ' > 127 are not const ~~~~~~~~~~~~~~ BC30424: Constants must be of an intrinsic or enumerated type, not a class, structure, type parameter, or array type. const f9() as integer = new integer() {1, 2} ~~~~ BC30059: Constant expression is required. const f10 = new integer() {1, 2} ~~~~~~~~~~~~~~~~~~~~ BC30059: Constant expression is required. const f11 = GetType(Integer) ~~~~~~~~~~~~~~~~ BC30424: Constants must be of an intrinsic or enumerated type, not a class, structure, type parameter, or array type. const f12 as system.type = GetType(Integer) ~~~~~~~~~~~ BC30060: Conversion from 'String' to 'Byte' cannot occur in a constant expression. const f13 as integer = cint(cint(cbyte("1"))) ~~~ BC30060: Conversion from 'String' to 'Byte' cannot occur in a constant expression. const f15 as long = clng(cint(cbyte("1"))) ~~~ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. const ValueWorks1 as Integer = new C(23).X ~~~~~~~~~~~ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. const ValueWorks2 as Integer = new A().X ~~~~~~~~~ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. const ValueWorks3 as Integer = 23 + new A().X ~~~~~~~~~ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. const ValueWorks6 as Integer = if(new A().X = 0, 23, 42) ~~~~~~~~~ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. const ValueWorks7 as Integer = if(new A(), nothing).X ~~~~~~~~~~~~~~~~~~~~~~ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. const ValueWorks8 as Integer = if(23 = 42, 23, new A().X) ~~~~~~~~~ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. const ValueWorks9 as Integer = if(23 = 42, new A().X, 42) ~~~~~~~~~ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. const ValueWorks10 as Integer = CType("12", Integer).MaxValue ' needs option strict off ... ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. const ValueWorks11 as Integer = New B(Sub() Exit Sub).X ~~~~~~~~~~~~~~~~~~~~~~~ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. const ValueWorks12 as Integer = New D(Function() 23).X ~~~~~~~~~~~~~~~~~~~~~~ BC30059: Constant expression is required. const ValueDoesntWork1 as Integer = f() ~~~ </expected>) End Sub <Fact()> Public Sub BC30059ERR_RequiredConstExpr_3() Dim source = <compilation> <file name="a.vb"> Option strict on Option Infer On imports system Class C1 Public Delegate Sub SubDel(p as integer) Public Shared Sub foo(p as Integer) Console.WriteLine("DelegateField works :) " + p.ToString()) End Sub public shared function f() as integer return 23 end function public shared function g(p as integer) as integer return 23 end function ' should not work Public const f2 = AddressOf C1.foo Public const f3 as object = AddressOf C1.foo public const f4 as integer = 1 + 2 + 3 + f() public const f5 as boolean = not (f() = 23) public const f6 as integer = f() + f() + f() public const f7 as integer = g(1 + 2 + f()) Public shared Sub Main(args() as string) End sub End Class </file> </compilation> Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) CompilationUtils.AssertTheseDiagnostics(c1, <expected> BC30059: Constant expression is required. Public const f2 = AddressOf C1.foo ~~~~~~~~~~~~~~~~ BC30059: Constant expression is required. Public const f3 as object = AddressOf C1.foo ~~~~~~~~~~~~~~~~ BC30059: Constant expression is required. public const f4 as integer = 1 + 2 + 3 + f() ~~~ BC30059: Constant expression is required. public const f5 as boolean = not (f() = 23) ~~~ BC30059: Constant expression is required. public const f6 as integer = f() + f() + f() ~~~ BC30059: Constant expression is required. public const f6 as integer = f() + f() + f() ~~~ BC30059: Constant expression is required. public const f6 as integer = f() + f() + f() ~~~ BC30059: Constant expression is required. public const f7 as integer = g(1 + 2 + f()) ~~~~~~~~~~~~~~ </expected>) End Sub <Fact> Public Sub TestArrayLocalConst() Dim source = <compilation> <file name="a.vb"> Imports System Module C Sub Main() Const A As Integer() = Nothing Console.Write(A) End Sub End Module </file> </compilation> Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) CompilationUtils.AssertTheseDiagnostics(c1, <expected> BC30424: Constants must be of an intrinsic or enumerated type, not a class, structure, type parameter, or array type. Const A As Integer() = Nothing ~ </expected>) End Sub <Fact()> Public Sub BC30059ERR_RequiredConstExpr_Attr() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="ERR_RequiredConstExpr_Attr"> <file name="at30059.vb"><![CDATA[ Imports System <AttributeUsage(AttributeTargets.All)> Public Class MyAttribute Inherits Attribute Public Sub New(p As ULong) End Sub End Class <My(Foo.FG)> Public Class Foo Public Shared FG As ULong = 12345 Public Function F() As Byte Dim x As Byte = 1 Return x End Function End Class ]]></file> </compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_RequiredConstExpr, "Foo.FG")) End Sub <WorkItem(542967, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542967")> <Fact()> Public Sub BC30059ERR_RequiredConstExpr_QueryInAttr() CompilationUtils.CreateCompilationWithMscorlib40AndReferences( <compilation name="ERR_RequiredConstExpr_Attr"> <file name="at30059.vb"><![CDATA[ Imports System Imports System.Linq Class Program Const q As String = "" Sub Main(args As String()) End Sub <My((From x In q Select x).Count())> Shared Sub sum() End Sub End Class Class MyAttribute Inherits Attribute Sub New(s As Integer) End Sub End Class ]]></file> </compilation>, references:={Net40.SystemCore}).VerifyDiagnostics(Diagnostic(ERRID.ERR_RequiredConstExpr, "(From x In q Select x).Count()")) End Sub <WorkItem(542967, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542967")> <Fact()> Public Sub BC30059ERR_RequiredConstExpr_QueryInAttr_2() CompilationUtils.CreateCompilationWithMscorlib40AndReferences( <compilation name="ERR_RequiredConstExpr_Attr"> <file name="at30059.vb"><![CDATA[ Imports System Imports System.Linq Class Program Const q As String = "" Sub Main(args As String()) End Sub Public F1 As Object <My((From x In q Select F1).Count())> Shared Sub sum() End Sub End Class Class MyAttribute Inherits Attribute Sub New(s As Integer) End Sub End Class ]]></file> </compilation>, references:={Net40.SystemCore}).VerifyDiagnostics(Diagnostic(ERRID.ERR_BadInstanceMemberAccess, "F1")) End Sub <WorkItem(542967, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542967")> <Fact()> Public Sub BC30059ERR_RequiredConstExpr_QueryInAttr_3() CompilationUtils.CreateCompilationWithMscorlib40AndReferences( <compilation name="ERR_RequiredConstExpr_Attr"> <file name="at30059.vb"><![CDATA[ Imports System Imports System.Linq <My((From x In "s" Select x).Count())> Class Program Public F1 As Integer End Class <My((From x In "s" Select Program.F1).Count())> Class Program2 End Class Class MyAttribute Inherits Attribute Sub New(s As Integer) End Sub End Class ]]></file> </compilation>, references:={Net40.SystemCore}).VerifyDiagnostics({Diagnostic(ERRID.ERR_RequiredConstExpr, "(From x In ""s"" Select x).Count()"), Diagnostic(ERRID.ERR_ObjectReferenceNotSupplied, "Program.F1")}) End Sub <Fact()> Public Sub BC30059ERR_RequiredConstExpr_XmlEmbeddedExpression() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Module M Private Const F1 = Nothing Private Const F2 As String = "v2" Private Const F3 = <%= Nothing %> Private Const F4 = <%= "v4" %> Private Const F5 As String = <%= "v5" %> Private F6 As Object = <x a0=<%= "v0" %> a1=<%= F1 %> a2=<%= F2 %> a3=<%= F3 %> a4=<%= F4 %> a5=<%= F5 %>/> End Module ]]></file> </compilation>, references:=XmlReferences) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC30059: Constant expression is required. Private Const F3 = <%= Nothing %> ~~~~~~~~~~~~~~ BC31172: An embedded expression cannot be used here. Private Const F3 = <%= Nothing %> ~~~~~~~~~~~~~~ BC30059: Constant expression is required. Private Const F4 = <%= "v4" %> ~~~~~~~~~~~ BC31172: An embedded expression cannot be used here. Private Const F4 = <%= "v4" %> ~~~~~~~~~~~ BC30059: Constant expression is required. Private Const F5 As String = <%= "v5" %> ~~~~~~~~~~~ BC31172: An embedded expression cannot be used here. Private Const F5 As String = <%= "v5" %> ~~~~~~~~~~~ ]]></errors>) End Sub <Fact()> Public Sub BC30060ERR_RequiredConstConversion2() Dim source = <compilation> <file name="a.vb"> Option strict on imports system Class C1 ' should show issues public const f1 as integer = CInt("23") public const f2 as integer = CType("23", integer) public const f3 as byte = CType(300, byte) public const f4 as byte = CType(300, BORG) public const f5 as byte = 300 public const f6 as string = 23 public const f10 as date = CDate("November 04, 2008") public const f13 as decimal = Ctype("20100607",decimal) ' should not show issues public const f7 as integer = CInt(23) public const f8 as integer = CType(23, integer) public const f9 as byte = CType(254, byte) public const f11 as date = Ctype(#06/07/2010#,date) public const f12 as decimal = Ctype(20100607,decimal) Public shared Sub Main(args() as string) End sub End Class </file> </compilation> Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) CompilationUtils.AssertTheseDiagnostics(c1, <expected> BC30060: Conversion from 'String' to 'Integer' cannot occur in a constant expression. public const f1 as integer = CInt("23") ~~~~ BC30060: Conversion from 'String' to 'Integer' cannot occur in a constant expression. public const f2 as integer = CType("23", integer) ~~~~ BC30439: Constant expression not representable in type 'Byte'. public const f3 as byte = CType(300, byte) ~~~ BC30002: Type 'BORG' is not defined. public const f4 as byte = CType(300, BORG) ~~~~ BC30439: Constant expression not representable in type 'Byte'. public const f5 as byte = 300 ~~~ BC30512: Option Strict On disallows implicit conversions from 'Integer' to 'String'. public const f6 as string = 23 ~~ BC30060: Conversion from 'String' to 'Date' cannot occur in a constant expression. public const f10 as date = CDate("November 04, 2008") ~~~~~~~~~~~~~~~~~~~ BC30060: Conversion from 'String' to 'Decimal' cannot occur in a constant expression. public const f13 as decimal = Ctype("20100607",decimal) ~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30060ERR_RequiredConstConversion2_StrictOff() Dim source = <compilation> <file name="a.vb"> Option strict off imports system Class C1 public const f6 as string = 23 public const f7 as string = CType(23,string) Public shared Sub Main(args() as string) End sub End Class </file> </compilation> Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) CompilationUtils.AssertTheseDiagnostics(c1, <expected> BC30060: Conversion from 'Integer' to 'String' cannot occur in a constant expression. public const f6 as string = 23 ~~ BC30060: Conversion from 'Integer' to 'String' cannot occur in a constant expression. public const f7 as string = CType(23,string) ~~ </expected>) End Sub <Fact()> Public Sub BC30064ERR_ReadOnlyAssignment() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ReadOnlyAssignment"> <file name="a.vb"> Imports System Module M1 Class ReferenceType Implements IDisposable Dim dummy As Integer Public Sub Dispose() Implements System.IDisposable.Dispose End Sub End Class Class TestClass ReadOnly Name As String = "Cici" Sub test() Name = "string" ' variables declared in a using statement are considered read only as well Using a As New ReferenceType(), b As New ReferenceType() a = New ReferenceType() b = New ReferenceType() End Using End Sub End Class End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30064: 'ReadOnly' variable cannot be the target of an assignment. Name = "string" ~~~~ BC30064: 'ReadOnly' variable cannot be the target of an assignment. a = New ReferenceType() ~ BC30064: 'ReadOnly' variable cannot be the target of an assignment. b = New ReferenceType() ~ </expected>) End Sub <Fact()> Public Sub BC30065ERR_ExitSubOfFunc_1() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="ExitSubOfFunc"> <file name="a.vb"> Public Class C1 Function FOO() If (True) Exit Sub End If Return Nothing End Function End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC30065: 'Exit Sub' is not valid in a Function or Property. Exit Sub ~~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC30067ERR_ExitFuncOfSub_1() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="ExitFuncOfSub"> <file name="a.vb"> Public Class C1 Sub FOO() If (True) lb1: Exit Function End If End Sub End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC30067: 'Exit Function' is not valid in a Sub or Property. lb1: Exit Function ~~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC30068ERR_LValueRequired() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="LValueRequired"> <file name="a.vb"> Module M1 Class TestClass ReadOnly Name As String = "Cici" Sub test() Dim obj As Cls1 obj.Test = 1 obj.Test() = 1 End Sub End Class Class Cls1 Public Overridable Sub Test() End Sub End Class End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42104: Variable 'obj' is used before it has been assigned a value. A null reference exception could result at runtime. obj.Test = 1 ~~~ BC30068: Expression is a value and therefore cannot be the target of an assignment. obj.Test = 1 ~~~~~~~~ BC30068: Expression is a value and therefore cannot be the target of an assignment. obj.Test() = 1 ~~~~~~~~~~ </expected>) End Sub <WorkItem(575055, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/575055")> <Fact> Public Sub BC30068ERR_IdentifierWithSameNameDifferentScope() Dim source = <compilation> <file name="DuplicateID.vb"><![CDATA[ Module Module1 Dim list2 As Integer() = {1} Dim ddd = From i In list2 Where i > Foo(Function(m1) If(True, Sub(m2) Call Function(m3) Return Sub() If True Then For Each i In list2 : m1 = i : Exit Sub : Exit For : Next End Function(m2), Sub(m2) Call Function(m3) Return Sub() If True Then For Each i In list2 : m1 = i : Exit Sub : Exit For : Next End Function(m2))) Sub Main() End Sub Function Foo(ByVal x) Return x.Invoke(1) End Function End Module ]]></file></compilation> CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_ExpectedQueryableSource, "list2").WithArguments("Integer()"), Diagnostic(ERRID.ERR_LValueRequired, "i"), Diagnostic(ERRID.ERR_LValueRequired, "i")) End Sub ' change error 30098 to 30068 <WorkItem(538107, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538107")> <Fact()> Public Sub BC30068ERR_LValueRequired_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ReadOnlyProperty1"> <file name="a.vb"> Module SB008mod Public ReadOnly Name As String Public ReadOnly Name1 As Struct1 Public ReadOnly Name2 As Class1 Sub SB008() Name = "15" Name1.Field = "15" Name2.Field = "15" System.TypeCode.Boolean=0 A().Field="15" End Sub Function A() As Struct1 Return Nothing End Function End Module Structure Struct1 Public Field As String End Structure Class Class1 Public Field As String End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30064: 'ReadOnly' variable cannot be the target of an assignment. Name = "15" ~~~~ BC30064: 'ReadOnly' variable cannot be the target of an assignment. Name1.Field = "15" ~~~~~~~~~~~ BC30074: Constant cannot be the target of an assignment. System.TypeCode.Boolean=0 ~~~~~~~~~~~~~~~~~~~~~~~ BC30068: Expression is a value and therefore cannot be the target of an assignment. A().Field="15" ~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30068ERR_LValueRequired_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="LValueRequired"> <file name="a.vb"> Class A Property P Shared Property Q End Class Structure B Property P Shared Property Q End Structure Class C Property P As A Property Q As B Sub M() P.P = Nothing ' no error Q.P = Nothing ' BC30068 A.Q = Nothing ' no error B.Q = Nothing ' no error End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30068: Expression is a value and therefore cannot be the target of an assignment. Q.P = Nothing ' BC30068 ~~~ </expected>) End Sub <Fact()> Public Sub BC30069ERR_ForIndexInUse1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ForIndexInUse1"> <file name="a.vb"> Module A Sub TEST() Dim n(3) As Integer Dim u As Integer For u = n(0) To n(3) Step n(0) ' BC30069: For loop control variable 'u' already in use by an enclosing For loop. For u = 1 To 9 Next Next End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30069: For loop control variable 'u' already in use by an enclosing For loop. For u = 1 To 9 ~ </expected>) End Sub <Fact()> Public Sub BC30070ERR_NextForMismatch1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="NextForMismatch1"> <file name="a.vb"> Module A Sub TEST() Dim n(3) As Integer Dim u As Integer Dim k As Integer For u = n(0) To n(3) Step n(0) For k = 1 To 9 Next u Next k End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30070: Next control variable does not match For loop control variable 'k'. Next u ~ BC30070: Next control variable does not match For loop control variable 'u'. Next k ~ </expected>) End Sub <Fact()> Public Sub BC30070ERR_NextForMismatch1_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="NextForMismatch1"> <file name="a.vb"> Class C Public Shared Sub Main() Dim S As String = "ABC" Dim T As String = "XYZ" For Each x As Char In S For Each y As Char In T Next y, x For Each x As Char In S For Each y As Char In T Next x, y End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30070: Next control variable does not match For loop control variable 'y'. Next x, y ~ BC30451: 'y' is not declared. It may be inaccessible due to its protection level. Next x, y ~ </expected>) End Sub <Fact()> Public Sub BC30074ERR_CantAssignToConst() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="CantAssignToConst"> <file name="a.vb"> Class c1_0 Public foo As Byte End Class Class c2_1 Inherits c1_0 Public Shadows Const foo As Short = 15 Sub test() 'COMPILEERROR: BC30074, "foo" foo = 1 End Sub End Class Class c3_1 Inherits c1_0 Public Shadows Const foo As Short = 15 End Class Class c2_2 Sub test() Dim obj As c3_1 obj.foo = 10 End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30074: Constant cannot be the target of an assignment. foo = 1 ~~~ BC30074: Constant cannot be the target of an assignment. obj.foo = 10 ~~~~~~~ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. obj.foo = 10 ~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30075ERR_NamedSubscript() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="NamedSubscript"> <file name="a.vb"> Class c1 Sub test() Dim Array As Integer() = new integer(){1} Array(Index:=10) = 1 End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30075: Named arguments are not valid as array subscripts. Array(Index:=10) = 1 ~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30089ERR_ExitDoNotWithinDo() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ERR_ExitDoNotWithinDo"> <file name="a.vb"> Structure myStruct1 Public Sub m(ByVal s As String) Select Case s Case "userID" Exit do End Select End Sub End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30089: 'Exit Do' can only appear inside a 'Do' statement. Exit do ~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30089ERR_ExitDoNotWithinDo_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ERR_ExitDoNotWithinDo"> <file name="a.vb"> Structure myStruct1 Public Sub m(ByVal s As String) If s Then Exit Do Else End If End Sub End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30089: 'Exit Do' can only appear inside a 'Do' statement. Exit Do ~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30094ERR_MultiplyDefined1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="MultiplyDefined1"> <file name="a.vb"> Module M1 Sub Main() SB008() End Sub Sub SB008() [cc]: 'COMPILEERROR: BC30094, "cc" cc: Exit Sub End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30094: Label 'cc' is already defined in the current method. cc: ~~ </expected>) End Sub <Fact()> Public Sub Bug585223_notMultiplyDefined() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="MultiplyDefined1"> <file name="a.vb"> <![CDATA[ Module Program Sub Main() &H100000000: &H000000000: End Sub End Module ]]> </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> </expected>) End Sub <Fact()> Public Sub Bug585223_notMultiplyDefined_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="MultiplyDefined1"> <file name="a.vb"> <![CDATA[ Module Program Sub Main() &HF: &HFF: &HFFF: &HFFFF: &HFFFFF: &HFFFFFF: &HFFFFFFF: &HFFFFFFFF: &HFFFFFFFFF: &HFFFFFFFFFF: &HFFFFFFFFFFF: &HFFFFFFFFFFFF: &HFFFFFFFFFFFFF: &HFFFFFFFFFFFFFF: &HFFFFFFFFFFFFFFF: &HFFFFFFFFFFFFFFFF: End Sub End Module ]]> </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> </expected>) End Sub <Fact()> Public Sub BC30096ERR_ExitForNotWithinFor() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ExitForNotWithinFor"> <file name="a.vb"> Structure myStruct1 Public Sub m(ByVal s As String) Select Case s Case "userID" Exit For End Select End Sub End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30096: 'Exit For' can only appear inside a 'For' statement. Exit For ~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30096ERR_ExitForNotWithinFor_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ExitForNotWithinFor"> <file name="a.vb"> Structure myStruct1 Public Sub m(ByVal s As String) If s Then Exit For Else End If End Sub End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30096: 'Exit For' can only appear inside a 'For' statement. Exit For ~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30097ERR_ExitWhileNotWithinWhile() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ExitWhileNotWithinWhile"> <file name="a.vb"> Structure myStruct1 Public Sub m(ByVal s As String) Select Case s Case "userID" Exit While End Select End Sub End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30097: 'Exit While' can only appear inside a 'While' statement. Exit While ~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30097ERR_ExitWhileNotWithinWhile_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ExitWhileNotWithinWhile"> <file name="a.vb"> Structure myStruct1 Public Sub m(ByVal s As String) If s Then Exit While Else End If End Sub End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30097: 'Exit While' can only appear inside a 'While' statement. Exit While ~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30099ERR_ExitSelectNotWithinSelect() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ExitSelectNotWithinSelect"> <file name="a.vb"> Structure myStruct1 Public Sub m(ByVal s As String) If s Then Exit Select Else End If End Sub End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30099: 'Exit Select' can only appear inside a 'Select' statement. Exit Select ~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30101ERR_BranchOutOfFinally() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="BranchOutOfFinally"> <file name="a.vb"> Imports System Module M1 Sub Foo() Try Try Label1: Catch Finally GoTo Label1 End Try Catch Finally End Try Exit Sub End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30101: Branching out of a 'Finally' is not valid. GoTo Label1 ~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30101ERR_BranchOutOfFinally2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="BC30101ERR_BranchOutOfFinally2"> <file name="a.vb"> Imports System Module M1 Sub Foo() Try Try Catch Finally Label2: GoTo Label2 End Try Catch Finally End Try Exit Sub End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) End Sub <Fact()> Public Sub BC30101ERR_BranchOutOfFinally3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="BC30101ERR_BranchOutOfFinally3"> <file name="a.vb"> Imports System Module M1 Sub Foo() Try Catch Finally Label2: GoTo Label2 End Try End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) End Sub <Fact()> Public Sub BC30101ERR_BranchOutOfFinally4() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="BC30101ERR_BranchOutOfFinally4"> <file name="a.vb"> Imports System Module M1 Sub Foo() Try Catch Finally GoTo L2 L2: GoTo L2 End Try End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) End Sub <Fact()> Public Sub BC30103ERR_QualNotObjectRecord1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System Enum E A End Enum Class C Shared Sub M(Of T)() Dim [object] As Object = Nothing M([object]!P) Dim [enum] As E = E.A M([enum]!P) Dim [boolean] As Boolean = False M([boolean]!P) Dim [char] As Char = Nothing M([char]!P) Dim [sbyte] As SByte = Nothing M([sbyte]!P) Dim [byte] As Byte = Nothing M([byte]!P) Dim [int16] As Int16 = Nothing M([int16]!P) Dim [uint16] As UInt16 = Nothing M([uint16]!P) Dim [int32] As Int32 = Nothing M([int32]!P) Dim [uint32] As UInt32 = Nothing M([uint32]!P) Dim [int64] As Int64 = Nothing M([int64]!P) Dim [uint64] As UInt64 = Nothing M([uint64]!P) Dim [decimal] As Decimal = Nothing M([decimal]!P) Dim [single] As Single = Nothing M([single]!P) Dim [double] As Double = Nothing M([double]!P) Dim [type] As Type = Nothing M([type]!P) Dim [array] As Integer() = Nothing M([array]!P) Dim [nullable] As Nullable(Of Integer) = Nothing M([nullable]!P) Dim [datetime] As DateTime = Nothing M([datetime]!P) Dim [action] As Action = Nothing M([action]!P) Dim tp As T = Nothing M(tp!P) End Sub Shared Sub M(o) End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30103: '!' requires its left operand to have a type parameter, class or interface type, but this operand has the type 'E'. M([enum]!P) ~~~~~~ BC30103: '!' requires its left operand to have a type parameter, class or interface type, but this operand has the type 'Boolean'. M([boolean]!P) ~~~~~~~~~ BC30103: '!' requires its left operand to have a type parameter, class or interface type, but this operand has the type 'Char'. M([char]!P) ~~~~~~ BC30103: '!' requires its left operand to have a type parameter, class or interface type, but this operand has the type 'SByte'. M([sbyte]!P) ~~~~~~~ BC30103: '!' requires its left operand to have a type parameter, class or interface type, but this operand has the type 'Byte'. M([byte]!P) ~~~~~~ BC30103: '!' requires its left operand to have a type parameter, class or interface type, but this operand has the type 'Short'. M([int16]!P) ~~~~~~~ BC30103: '!' requires its left operand to have a type parameter, class or interface type, but this operand has the type 'UShort'. M([uint16]!P) ~~~~~~~~ BC30103: '!' requires its left operand to have a type parameter, class or interface type, but this operand has the type 'Integer'. M([int32]!P) ~~~~~~~ BC30103: '!' requires its left operand to have a type parameter, class or interface type, but this operand has the type 'UInteger'. M([uint32]!P) ~~~~~~~~ BC30103: '!' requires its left operand to have a type parameter, class or interface type, but this operand has the type 'Long'. M([int64]!P) ~~~~~~~ BC30103: '!' requires its left operand to have a type parameter, class or interface type, but this operand has the type 'ULong'. M([uint64]!P) ~~~~~~~~ BC30103: '!' requires its left operand to have a type parameter, class or interface type, but this operand has the type 'Decimal'. M([decimal]!P) ~~~~~~~~~ BC30103: '!' requires its left operand to have a type parameter, class or interface type, but this operand has the type 'Single'. M([single]!P) ~~~~~~~~ BC30103: '!' requires its left operand to have a type parameter, class or interface type, but this operand has the type 'Double'. M([double]!P) ~~~~~~~~ BC30367: Class 'Type' cannot be indexed because it has no default property. M([type]!P) ~~~~~~ BC30103: '!' requires its left operand to have a type parameter, class or interface type, but this operand has the type 'Integer()'. M([array]!P) ~~~~~~~ BC30690: Structure 'Integer?' cannot be indexed because it has no default property. M([nullable]!P) ~~~~~~~~~~ BC30103: '!' requires its left operand to have a type parameter, class or interface type, but this operand has the type 'Date'. M([datetime]!P) ~~~~~~~~~~ BC30555: Default member of 'Action' is not a property. M([action]!P) ~~~~~~~~ BC30547: 'T' cannot be indexed because it has no default property. M(tp!P) ~~ </expected>) End Sub <Fact()> Public Sub BC30103ERR_QualNotObjectRecord1a() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Enum E A End Enum Class C Shared Sub M(Of T)() Dim [string] As String = Nothing M([string]!P) End Sub Shared Sub M(o) End Sub End Class </file> </compilation>) compilation.VerifyEmitDiagnostics( Diagnostic(ERRID.ERR_MissingRuntimeHelper, "P").WithArguments("Microsoft.VisualBasic.CompilerServices.Conversions.ToInteger")) End Sub <Fact()> Public Sub BC30103ERR_QualNotObjectRecord2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="QualNotObjectRecord1"> <file name="a.vb"> Imports System Module BitOp001mod Sub BitOp001() Dim b As Byte = 2 Dim c As Byte = 3 Dim s As Short = 2 Dim t As Short = 3 Dim i As Integer = 2 Dim j As Integer = 3 Dim l As Long = 2 Dim m As Long = 3 b = b!c s = s!t i = i!j l = l!m End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30103: '!' requires its left operand to have a type parameter, class or interface type, but this operand has the type 'Byte'. b = b!c ~ BC30103: '!' requires its left operand to have a type parameter, class or interface type, but this operand has the type 'Short'. s = s!t ~ BC30103: '!' requires its left operand to have a type parameter, class or interface type, but this operand has the type 'Integer'. i = i!j ~ BC30103: '!' requires its left operand to have a type parameter, class or interface type, but this operand has the type 'Long'. l = l!m ~ </expected>) End Sub <Fact()> Public Sub BC30105ERR_TooFewIndices() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="TooFewIndices"> <file name="a.vb"> Imports System Module M1 Sub AryChg001() Dim a() As Integer = New Integer() {9, 10} ReDim a(10) Dim a8() As Integer = New Integer() {1, 2} Dim b8() As Integer = New Integer() {3, 4} Dim c8 As Integer a8() = b8 b8 = a() a8() = c8 c8 = a8() End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30105: Number of indices is less than the number of dimensions of the indexed array. a8() = b8 ~~ BC30105: Number of indices is less than the number of dimensions of the indexed array. b8 = a() ~~ BC30105: Number of indices is less than the number of dimensions of the indexed array. a8() = c8 ~~ BC30105: Number of indices is less than the number of dimensions of the indexed array. c8 = a8() ~~ </expected>) End Sub <Fact()> Public Sub BC30106ERR_TooManyIndices() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="TooManyIndices"> <file name="a.vb"> Imports System Module M1 Sub AryChg001() Dim a() As Integer = New Integer() {9, 10} ReDim a(10) Dim a8() As Integer = New Integer() {1, 2} Dim b8() As Integer = New Integer() {3, 4} Dim c8 As Integer a8(1, 2) = b8(1) b8 = a(0, 4) a8(4, 5, 6) = c8 c8 = a8(1, 2) End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30106: Number of indices exceeds the number of dimensions of the indexed array. a8(1, 2) = b8(1) ~~~~~~ BC30106: Number of indices exceeds the number of dimensions of the indexed array. b8 = a(0, 4) ~~~~~~ BC30106: Number of indices exceeds the number of dimensions of the indexed array. a8(4, 5, 6) = c8 ~~~~~~~~~ BC30106: Number of indices exceeds the number of dimensions of the indexed array. c8 = a8(1, 2) ~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30107ERR_EnumNotExpression1() CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="EnumNotExpression1"> <file name="a.vb"> Option Strict On Module BitOp001mod1 Sub BitOp001() Dim b As Byte = 2 Dim c As Byte = 3 Dim s As Short = 2 Dim t As Short = 3 Dim i As Integer = 2 Dim j As Integer = 3 Dim l As Long = 2 Dim m As Long = 3 b = b &amp; c b = b ^ c s = s &amp; t s = s ^ t i = i &amp; j i = i ^ j l = l &amp; m l = l ^ m Exit Sub End Sub End Module </file> </compilation>).VerifyDiagnostics( Diagnostic(ERRID.ERR_NarrowingConversionDisallowed2, "b & c").WithArguments("String", "Byte"), Diagnostic(ERRID.ERR_NarrowingConversionDisallowed2, "b ^ c").WithArguments("Double", "Byte"), Diagnostic(ERRID.ERR_NarrowingConversionDisallowed2, "s & t").WithArguments("String", "Short"), Diagnostic(ERRID.ERR_NarrowingConversionDisallowed2, "s ^ t").WithArguments("Double", "Short"), Diagnostic(ERRID.ERR_NarrowingConversionDisallowed2, "i & j").WithArguments("String", "Integer"), Diagnostic(ERRID.ERR_NarrowingConversionDisallowed2, "i ^ j").WithArguments("Double", "Integer"), Diagnostic(ERRID.ERR_NarrowingConversionDisallowed2, "l & m").WithArguments("String", "Long"), Diagnostic(ERRID.ERR_NarrowingConversionDisallowed2, "l ^ m").WithArguments("Double", "Long")) End Sub <Fact()> Public Sub BC30108ERR_TypeNotExpression1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="TypeNotExpression1"> <file name="a.vb"> Module Module1 Sub Main() Module1 End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30108: 'Module1' is a type and cannot be used as an expression. Module1 ~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30108ERR_TypeNotExpression1_1() CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="TypeNotExpression1"> <file name="a.vb"> Imports System.Collections.Generic Module Program Sub Main() Dim lst As New List(Of String) From {Program, "abc", "def", "ghi"} End Sub End Module </file> </compilation>).VerifyDiagnostics( Diagnostic(ERRID.ERR_TypeNotExpression1, "Program").WithArguments("Program")) End Sub <WorkItem(545166, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545166")> <Fact()> Public Sub BC30109ERR_ClassNotExpression1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ClassNotExpression1"> <file name="a.vb"> Imports System Module M1 Sub FOO() Dim c As Object c = String(3, "Hai123") c = String End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30109: 'String' is a class type and cannot be used as an expression. c = String(3, "Hai123") ~~~~~~ BC30109: 'String' is a class type and cannot be used as an expression. c = String ~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30110ERR_StructureNotExpression1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="StructureNotExpression1"> <file name="a.vb"> Imports System Structure S1 End Structure Module M1 Sub FOO() Dim c As Object c = S1(3, "Hai123") c = S1 End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30110: 'S1' is a structure type and cannot be used as an expression. c = S1(3, "Hai123") ~~ BC30110: 'S1' is a structure type and cannot be used as an expression. c = S1 ~~ </expected>) End Sub <Fact()> Public Sub BC30111ERR_InterfaceNotExpression1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="StructureNotExpression1"> <file name="a.vb"> Imports System Interface S1 End Interface Module M1 Sub FOO() Dim c As Object c = S1(3, "Hai123") c = S1 End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30111: 'S1' is an interface type and cannot be used as an expression. c = S1(3, "Hai123") ~~ BC30111: 'S1' is an interface type and cannot be used as an expression. c = S1 ~~ </expected>) End Sub <Fact()> Public Sub BC30112ERR_NamespaceNotExpression1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="NamespaceNotExpression1"> <file name="a.vb"> Imports System Module M1 Sub Foo() 'COMPILEERROR: BC30112, "Text$" Text$ End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30112: 'System.Text' is a namespace and cannot be used as an expression. Text$ ~~~~~ </expected>) End Sub <Fact()> Public Sub BC30112ERR_NamespaceNotExpression2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="NamespaceNotExpression1"> <file name="a.vb"> Option Infer On Namespace X Class Program Sub Main() 'COMPILEERROR: BC30112, "x" For Each x In "" Next End Sub End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30112: 'X' is a namespace and cannot be used as an expression. For Each x In "" ~ </expected>) End Sub <Fact()> Public Sub BC30114ERR_XmlPrefixNotExpression() Dim options = TestOptions.ReleaseDll.WithGlobalImports(GlobalImport.Parse({"<xmlns:p1=""..."">"})) Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports System Imports <xmlns:p2="..."> Imports <xmlns:p4="..."> Module M Private F1 As Object = p1 Private F2 As Object = P1 Private F3 As Object = xml Private F4 As Object = XML Private F5 As Object = xmlns Private F6 As Object = XMLNS Private F7 As Object = <x xmlns:p3="..."> <%= p2 %> <%= p3 %> <%= xmlns %> </x> Private Function F8(p1 As Object) As Object Return p1 End Function Private Function F9(xmlns As Object) As Object Return p2 End Function Private F10 As Object = p4 End Module ]]></file> <file name="b.vb"><![CDATA[ Class p4 End Class ]]></file> </compilation>, references:=XmlReferences, options:=options) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC30114: 'p1' is an XML prefix and cannot be used as an expression. Use the GetXmlNamespace operator to create a namespace object. Private F1 As Object = p1 ~~ BC30451: 'P1' is not declared. It may be inaccessible due to its protection level. Private F2 As Object = P1 ~~ BC30112: 'System.Xml' is a namespace and cannot be used as an expression. Private F3 As Object = xml ~~~ BC30112: 'System.Xml' is a namespace and cannot be used as an expression. Private F4 As Object = XML ~~~ BC30114: 'xmlns' is an XML prefix and cannot be used as an expression. Use the GetXmlNamespace operator to create a namespace object. Private F5 As Object = xmlns ~~~~~ BC30451: 'XMLNS' is not declared. It may be inaccessible due to its protection level. Private F6 As Object = XMLNS ~~~~~ BC30114: 'p2' is an XML prefix and cannot be used as an expression. Use the GetXmlNamespace operator to create a namespace object. <%= p2 %> ~~ BC30451: 'p3' is not declared. It may be inaccessible due to its protection level. <%= p3 %> ~~ BC30114: 'xmlns' is an XML prefix and cannot be used as an expression. Use the GetXmlNamespace operator to create a namespace object. <%= xmlns %> ~~~~~ BC30114: 'p2' is an XML prefix and cannot be used as an expression. Use the GetXmlNamespace operator to create a namespace object. Return p2 ~~ BC30109: 'p4' is a class type and cannot be used as an expression. Private F10 As Object = p4 ~~ ]]></errors>) End Sub <Fact()> Public Sub BC30131ERR_ModuleSecurityAttributeNotAllowed1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="BC30131ERR_ModuleSecurityAttributeNotAllowed1"> <file name="a.vb"> <![CDATA[ Imports System Imports System.Security.Permissions Imports System.Security.Principal <Module: MySecurity(Security.Permissions.SecurityAction.Assert)> <AttributeUsage(AttributeTargets.Module)> Class MySecurityAttribute Inherits SecurityAttribute Public Sub New(action As SecurityAction) MyBase.New(action) End Sub Public Overrides Function CreatePermission() As Security.IPermission Return Nothing End Function End Class Module Foo Public Sub main() End Sub End Module ]]> </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected><![CDATA[ BC36979: Security attribute 'MySecurityAttribute' is not valid on this declaration type. Security attributes are only valid on assembly, type and method declarations. <Module: MySecurity(Security.Permissions.SecurityAction.Assert)> ~~~~~~~~~~ ]]> </expected>) End Sub <Fact()> Public Sub BC30132ERR_LabelNotDefined1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="LabelNotDefined1"> <file name="a.vb"> Module Implicitmod Sub Implicit() 'COMPILEERROR: BC30132, "ns1" GoTo ns1 End Sub Sub Test() ns1: End Sub End Module Namespace NS2 Module Implicitmod Sub Implicit() ns1: End Sub End Module End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30132: Label 'ns1' is not defined. GoTo ns1 ~~~ </expected>) End Sub <Fact()> Public Sub BC30148ERR_RequiredNewCall2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="RequiredNewCall2"> <file name="a.vb"> Imports System Module Test Class clsTest0 Sub New(ByVal strTest As String) End Sub End Class Class clsTest1 Inherits clsTest0 Private strTest As String = "Hello" Sub New(ByVal ArgX As String) 'COMPILEERROR: BC30148, "Console.WriteLine(ArgX)" Console.WriteLine(ArgX) End Sub End Class End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30148: First statement of this 'Sub New' must be a call to 'MyBase.New' or 'MyClass.New' because base class 'Test.clsTest0' of 'Test.clsTest1' does not have an accessible 'Sub New' that can be called with no arguments. Sub New(ByVal ArgX As String) ~~~ </expected>) End Sub <Fact()> Public Sub BC30157ERR_BadWithRef() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Module M1 Sub Main() .xxx = 3 End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30157: Leading '.' or '!' can only appear inside a 'With' statement. .xxx = 3 ~~~~ </expected>) End Sub <Fact()> Public Sub BC30157ERR_BadWithRef_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C Default Property P(x As String) Get Return Nothing End Get Set(value) End Set End Property Sub M() !A = Me!B Me!A = !B End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30157: Leading '.' or '!' can only appear inside a 'With' statement. !A = Me!B ~~ BC30157: Leading '.' or '!' can only appear inside a 'With' statement. Me!A = !B ~~ </expected>) End Sub <Fact()> Public Sub BC30157ERR_BadWithRef_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Module M Sub M() Dim o As Object o = .<x> o = ...<x> .@a = .@<a> End Sub End Module ]]></file> </compilation>, references:=XmlReferences) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC30157: Leading '.' or '!' can only appear inside a 'With' statement. o = .<x> ~~~~ BC30157: Leading '.' or '!' can only appear inside a 'With' statement. o = ...<x> ~~~~~~ BC30157: Leading '.' or '!' can only appear inside a 'With' statement. .@a = .@<a> ~~~ BC30157: Leading '.' or '!' can only appear inside a 'With' statement. .@a = .@<a> ~~~~~ ]]></errors>) End Sub <Fact()> Public Sub BC30182_ERR_UnrecognizedType_2() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="UnrecognizedType"> <file name="a.vb"> Namespace NS Class C1 Sub FOO() Dim v = 1 Dim s = CType(v, NS) End Sub End Class End Namespace </file> </compilation>) Dim expectedErrors1 = <errors> BC30182: Type expected. Dim s = CType(v, NS) ~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC30203ERR_ExpectedIdentifier() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BC30203ERR_ExpectedIdentifier"> <file name="a.vb"> Option Strict On Class C1 Public Property Public Property _ as Integer Shared Public End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC30203: Identifier expected. Public Property ~ BC30301: 'Public Property As Object' and 'Public Property As Integer' cannot overload each other because they differ only by return types. Public Property ~ BC30203: Identifier expected. Public Property _ as Integer ~ BC30203: Identifier expected. Shared Public ~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC30209ERR_StrictDisallowImplicitObject() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="StrictDisallowImplicitObject"> <file name="a.vb"> Option Strict On Structure myStruct Dim s End Structure </file> </compilation>) Dim expectedErrors1 = <errors> BC30209: Option Strict On requires all variable declarations to have an 'As' clause. Dim s ~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC30209ERR_StrictDisallowImplicitObject_1() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="StrictDisallowImplicitObject"> <file name="a.vb"> Option Strict On Structure myStruct Sub Scen1() 'COMPILEERROR: BC30209, "i" Dim i End Sub End Structure </file> </compilation>) Dim expectedErrors1 = <errors> BC30209: Option Strict On requires all variable declarations to have an 'As' clause. Dim i ~ BC42024: Unused local variable: 'i'. Dim i ~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact(), WorkItem(528749, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528749")> Public Sub BC30209ERR_StrictDisallowImplicitObject_3() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="StrictDisallowImplicitObject"> <file name="a.vb"> Option strict on option infer off imports system Class C1 Public Const f1 = "foo" Public Const f2 As Object = "foo" Public Const f3 = 23 Public Const f4 As Object = 42 Public Shared Sub Main(args() As String) console.writeline(f1) console.writeline(f2) console.writeline(f3) console.writeline(f4) End Sub End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC30209: Option Strict On requires all variable declarations to have an 'As' clause. Public Const f1 = "foo" ~~ BC30209: Option Strict On requires all variable declarations to have an 'As' clause. Public Const f3 = 23 ~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC30239ERR_ExpectedRelational_SelectCase() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="StrictDisallowImplicitObject"> <file name="a.vb"> <file name="a.vb"><![CDATA[ Imports System Module M1 Sub Main() Select Case 0 Case Is << 1 End Select End Sub End Module ]]></file> </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected><![CDATA[ BC30239: Relational operator expected. Case Is << 1 ~ ]]></expected>) End Sub <Fact()> Public Sub BC30272ERR_NamedParamNotFound2() CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="NamedParamNotFound2"> <file name="a.vb"> Module Module1 Class C0(Of T) Public whichOne As String Sub Foo(ByVal t1 As T) whichOne = "T" End Sub End Class Class C1(Of T, Y) Inherits C0(Of T) Overloads Sub Foo(ByVal y1 As Y) whichOne = "Y" End Sub End Class Sub GenUnif0060() Dim tc1 As New C1(Of Integer, Integer) ' BC30272: 't1' is not a parameter of 'Public Overloads Sub Foo(y1 As Y)'. Call tc1.Foo(t1:=1000) End Sub End Module </file> </compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_NamedParamNotFound2, "t1").WithArguments("t1", "Public Overloads Sub Foo(y1 As Integer)"), Diagnostic(ERRID.ERR_OmittedArgument2, "Foo").WithArguments("y1", "Public Overloads Sub Foo(y1 As Integer)")) End Sub <Fact()> Public Sub BC30274ERR_NamedArgUsedTwice2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="NamedArgUsedTwice2"> <file name="a.vb"> Module Module1 Class C0 Public whichOne As String Sub Foo(ByVal t1 As String) whichOne = "T" End Sub End Class Class C1 Inherits C0 Overloads Sub Foo(ByVal y1 As String) whichOne = "Y" End Sub End Class Sub test() Dim [ident1] As C0 = New C0() Dim clsNarg2get As C1 = New C1() Dim str1 As String = "Visual Basic" 'COMPILEERROR: BC30274, "y" [ident1].Foo(1, t1:=2) = str1 'COMPILEERROR: BC30274, "x" [ident1].Foo(t1:=1, t1:=1) = str1 End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30274: Parameter 't1' of 'Public Sub Foo(t1 As String)' already has a matching argument. [ident1].Foo(1, t1:=2) = str1 ~~ BC30274: Parameter 't1' of 'Public Sub Foo(t1 As String)' already has a matching argument. [ident1].Foo(t1:=1, t1:=1) = str1 ~~ </expected>) End Sub <Fact()> Public Sub BC30277ERR_TypecharNoMatch2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="TypecharNoMatch2"> <file name="a.vb"> Imports Microsoft.VisualBasic.Information Namespace NS30277 Public Class genClass1(Of CT) Public Function genFun7(Of T)(ByVal x As T) As T() Dim t1(2) As T Return t1 End Function End Class Module MD30277 Sub GenMethod9102() Const uiConst As UInteger = 1000 Dim o As New genClass1(Of Object) Dim objTmp As Object = CShort(10) ' BC30277: type character does not match declared data type. o.genFun7%(1&amp;) ' BC30277: type character does not match declared data type. o.genFun7%(True) ' BC30277: type character does not match declared data type. o.genFun7%((True And False)) ' BC30277: type character does not match declared data type. o.genFun7%(CDbl(1)) ' BC30277: type character does not match declared data type. o.genFun7%(Fun1) ' BC30277: type character does not match declared data type. o.genFun7%(TypeName(o)) ' BC30277: type character does not match declared data type. o.genFun7%(uiConst) ' BC30277: type character does not match declared data type. o.genFun7%(objTmp) End Sub Function Fun1() As Byte Return 1 End Function End Module End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30277: Type character '%' does not match declared data type 'Long'. o.genFun7%(1&amp;) ~~~~~~~~~~~~~~ BC30277: Type character '%' does not match declared data type 'Boolean'. o.genFun7%(True) ~~~~~~~~~~~~~~~~ BC30277: Type character '%' does not match declared data type 'Boolean'. o.genFun7%((True And False)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30277: Type character '%' does not match declared data type 'Double'. o.genFun7%(CDbl(1)) ~~~~~~~~~~~~~~~~~~~ BC30277: Type character '%' does not match declared data type 'Byte'. o.genFun7%(Fun1) ~~~~~~~~~~~~~~~~ BC30277: Type character '%' does not match declared data type 'String'. o.genFun7%(TypeName(o)) ~~~~~~~~~~~~~~~~~~~~~~~ BC30277: Type character '%' does not match declared data type 'UInteger'. o.genFun7%(uiConst) ~~~~~~~~~~~~~~~~~~~ BC30277: Type character '%' does not match declared data type 'Object'. o.genFun7%(objTmp) ~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30277ERR_TypecharNoMatch2_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="TypecharNoMatch2"> <file name="a.vb"> Class C Public Shared Sub Main() 'declare with explicit type, use in next with a type char") For Each x As Integer In New Integer() {1, 1, 1} 'COMPILEERROR: BC30277, "x#" Next x# For Each [me] As Integer In New Integer() {1, 1, 1} Next me% End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30277: Type character '#' does not match declared data type 'Integer'. Next x# ~~ </expected>) End Sub <WorkItem(528681, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528681")> <Fact()> Public Sub BC30277ERR_TypecharNoMatch2_3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="TypecharNoMatch2"> <file name="a.vb"> Public Class MyClass1 Public Shared Sub Main() For ivar% As Long = 1 To 10 Next For dvar# As Single = 1 To 10 Next For cvar@ As Decimal = 1 To 10 Next End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30302: Type character '%' cannot be used in a declaration with an explicit type. For ivar% As Long = 1 To 10 ~~~~~ BC30302: Type character '#' cannot be used in a declaration with an explicit type. For dvar# As Single = 1 To 10 ~~~~~ BC30302: Type character '@' cannot be used in a declaration with an explicit type. For cvar@ As Decimal = 1 To 10 ~~~~~ </expected>) End Sub <Fact()> Public Sub BC30282ERR_InvalidConstructorCall1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="InvalidConstructorCall1"> <file name="a.vb"> Module Error30282 Class Class1 Sub New() End Sub End Class Class Class2 Inherits Class1 Sub New() 'COMPILEERROR: BC30282, "Class1.New" Class1.New() End Sub End Class End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30282: Constructor call is valid only as the first statement in an instance constructor. Class1.New() ~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30282ERR_InvalidConstructorCall2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="InvalidConstructorCall2"> <file name="a.vb"> Imports System Class C Sub New(x As Integer) Me.New(Of Integer) End Sub Sub New End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30282: Constructor call is valid only as the first statement in an instance constructor. Me.New(Of Integer) ~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30282ERR_InvalidConstructorCall3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="InvalidConstructorCall3"> <file name="a.vb"> Imports System Class C Sub New(x As Integer) Me.New Me.New(Of Integer) End Sub Sub New End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30282: Constructor call is valid only as the first statement in an instance constructor. Me.New(Of Integer) ~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30282ERR_InvalidConstructorCall4() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="InvalidConstructorCall4"> <file name="a.vb"> Imports System Class C Sub New(x As Integer) Me.New(Of Integer)(1.ToString(123, 2, 3, 4)) End Sub Sub New End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30282: Constructor call is valid only as the first statement in an instance constructor. Me.New(Of Integer)(1.ToString(123, 2, 3, 4)) ~~~~~~~~~~~~~~~~~~ BC30516: Overload resolution failed because no accessible 'ToString' accepts this number of arguments. Me.New(Of Integer)(1.ToString(123, 2, 3, 4)) ~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30282ERR_InvalidConstructorCall5() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="InvalidConstructorCall5"> <file name="a.vb"> Imports System Class C Sub New(x As Integer) Dim a = 1 + Me.New(Of Integer) End Sub Sub New End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30282: Constructor call is valid only as the first statement in an instance constructor. Dim a = 1 + Me.New(Of Integer) ~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30282ERR_ConstructorCallIsValidOnlyAsTheFirstStatementInAnInstanceConstructor_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BC30282ERR_ConstructorCallIsValidOnlyAsTheFirstStatementInAnInstanceConstructor_1"> <file name="a.vb"> Class Tests Public Sub New() End Sub Public Sub New(i As Integer) Me.New() End Sub Public Sub New(t As Tests) t.New(1) End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> BC30282: Constructor call is valid only as the first statement in an instance constructor. t.New(1) ~~~~~ </errors>) End Sub <Fact()> Public Sub BC30282ERR_ConstructorCallIsValidOnlyAsTheFirstStatementInAnInstanceConstructor_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BC30282ERR_ConstructorCallIsValidOnlyAsTheFirstStatementInAnInstanceConstructor_2"> <file name="a.vb"> Class Tests Public Sub New() End Sub Public Sub New(i As Integer) Me.New() Me.New() End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> BC30282: Constructor call is valid only as the first statement in an instance constructor. Me.New() ~~~~~~ </errors>) End Sub <Fact()> Public Sub BC30282ERR_ConstructorCallIsValidOnlyAsTheFirstStatementInAnInstanceConstructor_3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BC30282ERR_ConstructorCallIsValidOnlyAsTheFirstStatementInAnInstanceConstructor_3"> <file name="a.vb"> Class Tests Public Sub New() End Sub Public Sub New(i As Integer) l1: Me.New() End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> BC30282: Constructor call is valid only as the first statement in an instance constructor. Me.New() ~~~~~~ </errors>) End Sub <Fact()> Public Sub BC30282ERR_ConstructorCallIsValidOnlyAsTheFirstStatementInAnInstanceConstructor_4() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BC30282ERR_ConstructorCallIsValidOnlyAsTheFirstStatementInAnInstanceConstructor_4"> <file name="a.vb"> Class Tests Public Sub New() End Sub Public Sub New2() Me.New() End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> BC30282: Constructor call is valid only as the first statement in an instance constructor. Me.New() ~~~~~~ </errors>) End Sub <Fact()> Public Sub BC30282ERR_ConstructorCallIsValidOnlyAsTheFirstStatementInAnInstanceConstructor_5() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BC30282ERR_ConstructorCallIsValidOnlyAsTheFirstStatementInAnInstanceConstructor_5"> <file name="a.vb"> Class Tests Public Sub New() End Sub Public Sub New(i As Integer) #Const a = 1 #If a = 1 Then Me.New() #End If Me.New() End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> BC30282: Constructor call is valid only as the first statement in an instance constructor. Me.New() ~~~~~~ </errors>) End Sub <Fact()> Public Sub BC30282ERR_ConstructorCallIsValidOnlyAsTheFirstStatementInAnInstanceConstructor_6() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BC30282ERR_ConstructorCallIsValidOnlyAsTheFirstStatementInAnInstanceConstructor_6"> <file name="a.vb"> Class Tests Public Sub New() End Sub Public Sub New(i As Integer) Dim a As Integer = 1 + Me.New() + Me.New End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> BC30282: Constructor call is valid only as the first statement in an instance constructor. Dim a As Integer = 1 + Me.New() + Me.New ~~~~~~ BC30282: Constructor call is valid only as the first statement in an instance constructor. Dim a As Integer = 1 + Me.New() + Me.New ~~~~~~ </errors>) End Sub <Fact()> Public Sub BC30282ERR_ConstructorCallIsValidOnlyAsTheFirstStatementInAnInstanceConstructor_7() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BC30282ERR_ConstructorCallIsValidOnlyAsTheFirstStatementInAnInstanceConstructor_7"> <file name="a.vb"> Class Tests Public Sub New(i As String) End Sub Public Sub New(i As Integer) Dim a As Integer = 1 + Me.New(1, 2) + Me.New End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> BC30282: Constructor call is valid only as the first statement in an instance constructor. Dim a As Integer = 1 + Me.New(1, 2) + Me.New ~~~~~~ BC30282: Constructor call is valid only as the first statement in an instance constructor. Dim a As Integer = 1 + Me.New(1, 2) + Me.New ~~~~~~ </errors>) End Sub <Fact()> Public Sub BC30282ERR_ConstructorCallIsValidOnlyAsTheFirstStatementInAnInstanceConstructor_8() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BC30282ERR_ConstructorCallIsValidOnlyAsTheFirstStatementInAnInstanceConstructor_8"> <file name="a.vb"> Class Tests Public Sub New(i As String) End Sub Public Sub New(i As Integer) Tests.New(1, 2) End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> BC30282: Constructor call is valid only as the first statement in an instance constructor. Tests.New(1, 2) ~~~~~~~~~ </errors>) End Sub <WorkItem(541012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541012")> <Fact()> Public Sub BC30283ERR_CantOverrideConstructor() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="CantOverrideConstructor"> <file name="a.vb"> Module Error30283 Class Class1 mustoverride Sub New() End Sub End Class End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30364: 'Sub New' cannot be declared 'mustoverride'. mustoverride Sub New() ~~~~~~~~~~~~ BC30429: 'End Sub' must be preceded by a matching 'Sub'. End Sub ~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30288ERR_DuplicateLocals1() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="DuplicateLocals1"> <file name="a.vb"> Public Class Class1 Public Sub foo(ByVal val As Short) Dim i As Integer Dim i As String End Sub End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC42024: Unused local variable: 'i'. Dim i As Integer ~ BC30288: Local variable 'i' is already declared in the current block. Dim i As String ~ BC42024: Unused local variable: 'i'. Dim i As String ~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact(), WorkItem(531346, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531346")> Public Sub UnicodeCaseInsensitiveLocals() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="UnicodeCaseInsensitiveLocals"> <file name="a.vb"> Public Class Class1 Public Sub foo() Dim X&#x130; 'COMPILEERROR:BC30288, "xi" Dim xi Dim &#x130; 'COMPILEERROR:BC30288, "i" Dim i End Sub End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC42024: Unused local variable: 'X&#x130;'. Dim X&#x130; ~~ BC30288: Local variable 'xi' is already declared in the current block. Dim xi ~~ BC42024: Unused local variable: 'xi'. Dim xi ~~ BC42024: Unused local variable: '&#x130;'. Dim &#x130; ~ BC30288: Local variable 'i' is already declared in the current block. Dim i ~ BC42024: Unused local variable: 'i'. Dim i ~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC30290ERR_LocalSameAsFunc() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="LocalSameAsFunc"> <file name="a.vb"> Module Error30290 Class Class1 Function Foo(ByVal Name As String) 'COMPILEERROR : BC30290, "Foo" Dim Foo As Date Return Name End Function End Class End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30290: Local variable cannot have the same name as the function containing it. Dim Foo As Date ~~~ BC42024: Unused local variable: 'Foo'. Dim Foo As Date ~~~ </expected>) End Sub <Fact()> Public Sub BC30290ERR_LocalSameAsFunc_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="LocalSameAsFunc"> <file name="a.vb"> Class C Shared Sub Main() End Sub Function foo() as Object 'COMPILEERROR: BC30290, For Each foo As Integer In New Integer() {1, 2, 3} Next return nothing End Function Sub foo1() For Each foo1 As Integer In New Integer() {1, 2, 3} Next End SUB End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30290: Local variable cannot have the same name as the function containing it. For Each foo As Integer In New Integer() {1, 2, 3} ~~~ </expected>) End Sub <Fact()> Public Sub BC30297ERR_ConstructorCannotCallItself_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BC30297ERR_ConstructorCannotCallItself_1"> <file name="a.vb"> Imports System Class Tests Public Sub New(i As Integer) Me.New("") End Sub Public Sub New(i As String) Me.New(1) End Sub Public Sub New(i As DateTime) Me.New(1) End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> BC30298: Constructor 'Public Sub New(i As Integer)' cannot call itself: 'Public Sub New(i As Integer)' calls 'Public Sub New(i As String)'. 'Public Sub New(i As String)' calls 'Public Sub New(i As Integer)'. Public Sub New(i As Integer) ~~~ BC30298: Constructor 'Public Sub New(i As String)' cannot call itself: 'Public Sub New(i As String)' calls 'Public Sub New(i As Integer)'. 'Public Sub New(i As Integer)' calls 'Public Sub New(i As String)'. Public Sub New(i As String) ~~~ </errors>) End Sub <Fact()> Public Sub BC30297ERR_ConstructorCannotCallItself_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BC30297ERR_ConstructorCannotCallItself_2"> <file name="a.vb"> Imports System Class Tests Public Sub New(i As Byte) Me.New(CType(i, Int16)) End Sub Public Sub New(i As Int16) Me.New(DateTime.Now) End Sub Public Sub New(i As DateTime) Me.New(DateTime.Now) End Sub Public Sub New(i As Int64) Me.New("") End Sub Public Sub New(i As Int32) Me.New(ctype(1, UInt32)) End Sub Public Sub New(i As UInt32) Me.New("") End Sub Public Sub New(i As String) Me.New(cint(1)) End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> BC30298: Constructor 'Public Sub New(i As Date)' cannot call itself: 'Public Sub New(i As Date)' calls 'Public Sub New(i As Date)'. Public Sub New(i As DateTime) ~~~ BC30298: Constructor 'Public Sub New(i As Integer)' cannot call itself: 'Public Sub New(i As Integer)' calls 'Public Sub New(i As UInteger)'. 'Public Sub New(i As UInteger)' calls 'Public Sub New(i As String)'. 'Public Sub New(i As String)' calls 'Public Sub New(i As Integer)'. Public Sub New(i As Int32) ~~~ BC30298: Constructor 'Public Sub New(i As UInteger)' cannot call itself: 'Public Sub New(i As UInteger)' calls 'Public Sub New(i As String)'. 'Public Sub New(i As String)' calls 'Public Sub New(i As Integer)'. 'Public Sub New(i As Integer)' calls 'Public Sub New(i As UInteger)'. Public Sub New(i As UInt32) ~~~ BC30298: Constructor 'Public Sub New(i As String)' cannot call itself: 'Public Sub New(i As String)' calls 'Public Sub New(i As Integer)'. 'Public Sub New(i As Integer)' calls 'Public Sub New(i As UInteger)'. 'Public Sub New(i As UInteger)' calls 'Public Sub New(i As String)'. Public Sub New(i As String) ~~~ </errors>) End Sub <Fact()> Public Sub BC30297ERR_ConstructorCannotCallItself_3() ' NOTE: Test case ensures that the error in calling the ' constructor suppresses the cycle detection Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BC30297ERR_ConstructorCannotCallItself_3"> <file name="a.vb"> Imports System Class Tests Public Sub New(i As Integer) Me.New("") End Sub Public Sub New(i As String) Me.New(qqq) End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> BC30451: 'qqq' is not declared. It may be inaccessible due to its protection level. Me.New(qqq) ~~~ </errors>) End Sub <Fact()> Public Sub BC30306ERR_MissingSubscript() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="MissingSubscript"> <file name="a.vb"> Module Mod30306 Sub ArExtFrErr002() Dim scen1(,) As Integer ReDim scen1(2, 2) Dim scen4() As Integer 'COMPILEERROR: BC30306, "(", BC30306, "," ReDim scen4(, ) Dim scen8a(,,) As Integer 'COMPILEERROR: BC30306, "(", BC30306, ",", BC30306, "," ReDim scen8a(, , ) Dim Scen8b(,,) As Integer 'COMPILEERROR: BC30306, ",", BC30306, "," ReDim Scen8b(5, , ) Dim scen8c(,,) As Integer 'COMPILEERROR: BC30306, "(", BC30306, "," ReDim scen8c(, , 5) Exit Sub End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30306: Array subscript expression missing. ReDim scen4(, ) ~ BC30306: Array subscript expression missing. ReDim scen4(, ) ~ BC30306: Array subscript expression missing. ReDim scen8a(, , ) ~ BC30306: Array subscript expression missing. ReDim scen8a(, , ) ~ BC30306: Array subscript expression missing. ReDim scen8a(, , ) ~ BC30306: Array subscript expression missing. ReDim Scen8b(5, , ) ~ BC30306: Array subscript expression missing. ReDim Scen8b(5, , ) ~ BC30306: Array subscript expression missing. ReDim scen8c(, , 5) ~ BC30306: Array subscript expression missing. ReDim scen8c(, , 5) ~ </expected>) End Sub ' <Fact()> ' Public Sub BC30310ERR_FieldOfValueFieldOfMarshalByRef3() ' Dim compilation = CompilationUtils.CreateCompilationWithMscorlib( '<compilation name="FieldOfValueFieldOfMarshalByRef3"> ' <file name="a.vb"> ' </file> '</compilation>) ' CompilationUtils.AssertTheseErrors(compilation, '<expected> 'BC30310: Local variable cannot have the same name as the function containing it. ' Dim Foo As Date ' ~~~~ 'BC30310: Local variable cannot have the same name as the function containing it. ' Dim scen16 = 3 ' ~~~~ '</expected>) ' End Sub <Fact()> Public Sub BC30311ERR_TypeMismatch2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System Public Class C Sub FOO() Dim a As S1? Dim b As E1? Dim c As System.Exception Dim d As I1 Dim e As C1.C2 Dim f As C1.C2(,) Dim z = DirectCast (b, S1?) z = DirectCast (b, System.Nullable) z = DirectCast (a, E1?) z = DirectCast (a, System.Nullable) z = DirectCast (c, S1?) z = DirectCast (c, E1?) z = DirectCast (c, System.Nullable) z = DirectCast (d, S1?) z = DirectCast (d, E1?) z = DirectCast (d, System.Nullable) z = DirectCast (d, System.ValueType) z = DirectCast (e, S1?) z = DirectCast (e, E1?) z = DirectCast (e, System.Nullable) z = DirectCast (e, System.ValueType) z = DirectCast (f, S1?) z = DirectCast (f, E1?) z = DirectCast (f, System.Nullable) z = DirectCast (f, System.ValueType) End Sub End Class Structure S1 End Structure Enum E1 one End Enum Interface I1 End Interface Class C1 Public Class C2 End Class End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30311: Value of type 'E1?' cannot be converted to 'S1?'. Dim z = DirectCast (b, S1?) ~ BC30311: Value of type 'E1?' cannot be converted to 'Nullable'. z = DirectCast (b, System.Nullable) ~ BC30311: Value of type 'S1?' cannot be converted to 'E1?'. z = DirectCast (a, E1?) ~ BC30311: Value of type 'S1?' cannot be converted to 'Nullable'. z = DirectCast (a, System.Nullable) ~ BC30311: Value of type 'Exception' cannot be converted to 'S1?'. z = DirectCast (c, S1?) ~ BC42104: Variable 'c' is used before it has been assigned a value. A null reference exception could result at runtime. z = DirectCast (c, S1?) ~ BC30311: Value of type 'Exception' cannot be converted to 'E1?'. z = DirectCast (c, E1?) ~ BC30311: Value of type 'Exception' cannot be converted to 'Nullable'. z = DirectCast (c, System.Nullable) ~ BC30311: Value of type 'I1' cannot be converted to 'S1?'. z = DirectCast (d, S1?) ~ BC42104: Variable 'd' is used before it has been assigned a value. A null reference exception could result at runtime. z = DirectCast (d, S1?) ~ BC30311: Value of type 'I1' cannot be converted to 'E1?'. z = DirectCast (d, E1?) ~ BC30311: Value of type 'Nullable' cannot be converted to 'S1?'. z = DirectCast (d, System.Nullable) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42322: Runtime errors might occur when converting 'I1' to 'Nullable'. z = DirectCast (d, System.Nullable) ~ BC30311: Value of type 'C1.C2' cannot be converted to 'S1?'. z = DirectCast (e, S1?) ~ BC42104: Variable 'e' is used before it has been assigned a value. A null reference exception could result at runtime. z = DirectCast (e, S1?) ~ BC30311: Value of type 'C1.C2' cannot be converted to 'E1?'. z = DirectCast (e, E1?) ~ BC30311: Value of type 'C1.C2' cannot be converted to 'Nullable'. z = DirectCast (e, System.Nullable) ~ BC30311: Value of type 'C1.C2' cannot be converted to 'ValueType'. z = DirectCast (e, System.ValueType) ~ BC30311: Value of type 'C1.C2(*,*)' cannot be converted to 'S1?'. z = DirectCast (f, S1?) ~ BC42104: Variable 'f' is used before it has been assigned a value. A null reference exception could result at runtime. z = DirectCast (f, S1?) ~ BC30311: Value of type 'C1.C2(*,*)' cannot be converted to 'E1?'. z = DirectCast (f, E1?) ~ BC30311: Value of type 'C1.C2(*,*)' cannot be converted to 'Nullable'. z = DirectCast (f, System.Nullable) ~ BC30311: Value of type 'C1.C2(*,*)' cannot be converted to 'ValueType'. z = DirectCast (f, System.ValueType) ~ </expected>) End Sub <Fact()> Public Sub BC30311ERR_TypeMismatch2_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System Class C Shared Sub Main() For Each x As Integer In New Exception() {Nothing, Nothing} Next End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30311: Value of type 'Exception' cannot be converted to 'Integer'. For Each x As Integer In New Exception() {Nothing, Nothing} ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30311ERR_TypeMismatch2_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C Public Shared Sub Main() Dim numbers2D As Integer()() = New Integer()() {New Integer() {1, 2}, New Integer() {1, 2}} For Each i As Integer In numbers2D System.Console.Write("{0} ", i) Next End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30311: Value of type 'Integer()' cannot be converted to 'Integer'. For Each i As Integer In numbers2D ~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30311ERR_TypeMismatch2_3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Module Program Sub Main(args As String()) End Sub Private Function fun(Of T)(Parm1 As T) As T Dim temp As T Return If(temp, temp, 1) End Function End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30311: Value of type 'T' cannot be converted to 'Boolean'. Return If(temp, temp, 1) ~~~~ </expected>) End Sub <Fact()> Public Sub BC30311ERR_TypeMismatch2_4() CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Public Class Test Public Sub Test() Dim at1 = New With {.f1 = Nothing, .f2 = String.Empty} Dim at2 = New With {.f2 = String.Empty, .f1 = Nothing} at1 = at2 End Sub End Class </file> </compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_TypeMismatch2, "at2").WithArguments("<anonymous type: f2 As String, f1 As Object>", "<anonymous type: f1 As Object, f2 As String>")) End Sub <Fact()> Public Sub BC30311ERR_TypeMismatch2_5() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Module Program Public Sub Main() Dim arr1 As Integer(,) = New Integer(2, 1) {{1, 2}, {3, 4}, {5, 6}} arr1 = 0 ' Invalid End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30311: Value of type 'Integer' cannot be converted to 'Integer(*,*)'. arr1 = 0 ' Invalid ~ </expected>) End Sub <Fact()> Public Sub BC30311ERR_TypeMismatch2_6() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module Program Public Sub Main() Dim arr As Integer(,) = New Integer(2, 1) {{6, 7}, {5, 8}, {8, 10}} Dim x As Integer x = arr 'Invalid arr = x 'Invalid End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30311: Value of type 'Integer(*,*)' cannot be converted to 'Integer'. x = arr 'Invalid ~~~ BC30311: Value of type 'Integer' cannot be converted to 'Integer(*,*)'. arr = x 'Invalid ~ </expected>) End Sub <Fact()> Public Sub BC30311ERR_TypeMismatch2_7() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Option Strict Off Option Infer On Class B Public Shared Sub Main() End Sub Private Sub Foo(Of T)() Dim x As T(,) = New T(1, 2) {} Dim Y As T(,) = New T(1, 2) {{1, 2, 3}, {1, 2, 3}} ' invalid End Sub End Class Public Class Class1(Of T) Private x As T(,) = New T(1, 2) {} Private Y As T(,) = New T(1, 2) {{1, 2, 3}, {1, 2, 3}} ' invalid Private Sub Foo() Dim x As T(,) = New T(1, 2) {} Dim Y As T(,) = New T(1, 2) {{1, 2, 3}, {1, 2, 3}} ' invalid End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30311: Value of type 'Integer' cannot be converted to 'T'. Dim Y As T(,) = New T(1, 2) {{1, 2, 3}, {1, 2, 3}} ' invalid ~ BC30311: Value of type 'Integer' cannot be converted to 'T'. Dim Y As T(,) = New T(1, 2) {{1, 2, 3}, {1, 2, 3}} ' invalid ~ BC30311: Value of type 'Integer' cannot be converted to 'T'. Dim Y As T(,) = New T(1, 2) {{1, 2, 3}, {1, 2, 3}} ' invalid ~ BC30311: Value of type 'Integer' cannot be converted to 'T'. Dim Y As T(,) = New T(1, 2) {{1, 2, 3}, {1, 2, 3}} ' invalid ~ BC30311: Value of type 'Integer' cannot be converted to 'T'. Dim Y As T(,) = New T(1, 2) {{1, 2, 3}, {1, 2, 3}} ' invalid ~ BC30311: Value of type 'Integer' cannot be converted to 'T'. Dim Y As T(,) = New T(1, 2) {{1, 2, 3}, {1, 2, 3}} ' invalid ~ BC30311: Value of type 'Integer' cannot be converted to 'T'. Private Y As T(,) = New T(1, 2) {{1, 2, 3}, {1, 2, 3}} ' invalid ~ BC30311: Value of type 'Integer' cannot be converted to 'T'. Private Y As T(,) = New T(1, 2) {{1, 2, 3}, {1, 2, 3}} ' invalid ~ BC30311: Value of type 'Integer' cannot be converted to 'T'. Private Y As T(,) = New T(1, 2) {{1, 2, 3}, {1, 2, 3}} ' invalid ~ BC30311: Value of type 'Integer' cannot be converted to 'T'. Private Y As T(,) = New T(1, 2) {{1, 2, 3}, {1, 2, 3}} ' invalid ~ BC30311: Value of type 'Integer' cannot be converted to 'T'. Private Y As T(,) = New T(1, 2) {{1, 2, 3}, {1, 2, 3}} ' invalid ~ BC30311: Value of type 'Integer' cannot be converted to 'T'. Private Y As T(,) = New T(1, 2) {{1, 2, 3}, {1, 2, 3}} ' invalid ~ BC30311: Value of type 'Integer' cannot be converted to 'T'. Dim Y As T(,) = New T(1, 2) {{1, 2, 3}, {1, 2, 3}} ' invalid ~ BC30311: Value of type 'Integer' cannot be converted to 'T'. Dim Y As T(,) = New T(1, 2) {{1, 2, 3}, {1, 2, 3}} ' invalid ~ BC30311: Value of type 'Integer' cannot be converted to 'T'. Dim Y As T(,) = New T(1, 2) {{1, 2, 3}, {1, 2, 3}} ' invalid ~ BC30311: Value of type 'Integer' cannot be converted to 'T'. Dim Y As T(,) = New T(1, 2) {{1, 2, 3}, {1, 2, 3}} ' invalid ~ BC30311: Value of type 'Integer' cannot be converted to 'T'. Dim Y As T(,) = New T(1, 2) {{1, 2, 3}, {1, 2, 3}} ' invalid ~ BC30311: Value of type 'Integer' cannot be converted to 'T'. Dim Y As T(,) = New T(1, 2) {{1, 2, 3}, {1, 2, 3}} ' invalid ~ </expected>) End Sub <Fact()> Public Sub BC30332ERR_ConvertArrayMismatch4() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ConvertArrayMismatch4"> <file name="a.vb"> Module M1 Class Cls2_1 End Class Class Cls2_2 End Class Sub Main() Dim Ary1_1() As Integer Dim Ary1_2() As Long = New Long() {1, 2} 'COMPILEERROR: BC30332, "Ary1_2" Ary1_1 = CType(Ary1_2, Integer()) Dim Ary2_1() As Cls2_1 = New Cls2_1() {} Dim Ary2_2(,) As Cls2_2 'COMPILEERROR: BC30332, "Ary2_1" Ary2_2 = CType(Ary2_1, Cls2_2()) Dim Ary3_1(,) As Double = New Double(,) {} Dim Ary3_2(,) As Cls2_2 'COMPILEERROR: BC30332, "Ary3_1" Ary3_2 = CType(Ary3_1, Cls2_2(,)) 'COMPILEERROR: BC30332, "Ary3_2" Ary3_1 = CType(Ary3_2, Double(,)) Dim Ary4_1() As Integer Dim Ary4_2() As Object = New Object() {} Ary4_1 = CType(Ary4_2, Integer()) End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30332: Value of type 'Long()' cannot be converted to 'Integer()' because 'Long' is not derived from 'Integer'. Ary1_1 = CType(Ary1_2, Integer()) ~~~~~~ BC30332: Value of type 'M1.Cls2_1()' cannot be converted to 'M1.Cls2_2()' because 'M1.Cls2_1' is not derived from 'M1.Cls2_2'. Ary2_2 = CType(Ary2_1, Cls2_2()) ~~~~~~ BC30332: Value of type 'Double(*,*)' cannot be converted to 'M1.Cls2_2(*,*)' because 'Double' is not derived from 'M1.Cls2_2'. Ary3_2 = CType(Ary3_1, Cls2_2(,)) ~~~~~~ BC30332: Value of type 'M1.Cls2_2(*,*)' cannot be converted to 'Double(*,*)' because 'M1.Cls2_2' is not derived from 'Double'. Ary3_1 = CType(Ary3_2, Double(,)) ~~~~~~ BC30332: Value of type 'Object()' cannot be converted to 'Integer()' because 'Object' is not derived from 'Integer'. Ary4_1 = CType(Ary4_2, Integer()) ~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30332ERR_ConvertArrayMismatch4_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ConvertArrayMismatch4"> <file name="a.vb"> Option Strict On Imports System Module Module1 Sub Main() Dim arrString$(,) = New Decimal(1, 2) {} ' Invalid Dim arrInteger%(,) = New Decimal(1, 2) {} ' Invalid Dim arrLong&amp;(,) = New Decimal(1, 2) {} ' Invalid Dim arrSingle!(,) = New Decimal(1, 2) {} ' Invalid End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30332: Value of type 'Decimal(*,*)' cannot be converted to 'String(*,*)' because 'Decimal' is not derived from 'String'. Dim arrString$(,) = New Decimal(1, 2) {} ' Invalid ~~~~~~~~~~~~~~~~~~~~ BC30332: Value of type 'Decimal(*,*)' cannot be converted to 'Integer(*,*)' because 'Decimal' is not derived from 'Integer'. Dim arrInteger%(,) = New Decimal(1, 2) {} ' Invalid ~~~~~~~~~~~~~~~~~~~~ BC30332: Value of type 'Decimal(*,*)' cannot be converted to 'Long(*,*)' because 'Decimal' is not derived from 'Long'. Dim arrLong&amp;(,) = New Decimal(1, 2) {} ' Invalid ~~~~~~~~~~~~~~~~~~~~ BC30332: Value of type 'Decimal(*,*)' cannot be converted to 'Single(*,*)' because 'Decimal' is not derived from 'Single'. Dim arrSingle!(,) = New Decimal(1, 2) {} ' Invalid ~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30333ERR_ConvertObjectArrayMismatch3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ConvertObjectArrayMismatch3"> <file name="a.vb"> Module M1 Sub Main() Dim Ary1() As Integer = New Integer() {} Dim Ary2() As Object Ary2 = CType(Ary1, Object()) End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30333: Value of type 'Integer()' cannot be converted to 'Object()' because 'Integer' is not a reference type. Ary2 = CType(Ary1, Object()) ~~~~ </expected>) End Sub <WorkItem(579764, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/579764")> <Fact()> Public Sub BC30311ERR_WithArray_ParseAndDeclarationErrors() 'This test is because previously in native command line compiler we would produce errors for both parsing and binding errors, now ' we won't produce the binding if parsing was not successful from the command line. However, the diagnostics will display both messages and ' hence the need for two tests to verify this behavior. Dim source = <compilation> <file name="ParseErrorOnly.vb"> Module M Dim x As Integer() {1, 2, 3} Dim y = CType({1, 2, 3}, System.Collections.Generic.List(Of Integer)) Sub main End Sub End Module </file> </compilation> CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_ExpectedEOS, "{"), Diagnostic(ERRID.ERR_TypeMismatch2, "{1, 2, 3}").WithArguments("Integer()", "System.Collections.Generic.List(Of Integer)")) ' This 2nd scenario will produce 1 error because it passed the parsing stage and now ' fails in the binding source = <compilation> <file name="ParseOK.vb"> Module M Dim x As Integer() = {1, 2, 3} Dim y = CType({1, 2, 3}, System.Collections.Generic.List(Of Integer)) Sub main End Sub End Module </file> </compilation> CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_TypeMismatch2, "{1, 2, 3}").WithArguments("Integer()", "System.Collections.Generic.List(Of Integer)")) End Sub <Fact(), WorkItem(542069, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542069")> Public Sub BC30337ERR_ForLoopType1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ForLoopType1"> <file name="a.vb"> Module M1 Sub Test() 'COMPILEERROR : BC30337, "i" For i = New base To New first() Next For j = New base To New first() step new second() Next End Sub End Module Class base End Class Class first Inherits base Overloads Shared Widening Operator CType(ByVal d As first) As second Return New second() End Operator End Class Class second Inherits base Overloads Shared Widening Operator CType(ByVal d As second) As first Return New first() End Operator End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30311: Value of type 'Integer' cannot be converted to 'base'. For i = New base To New first() ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC33038: Type 'base' must define operator '-' to be used in a 'For' statement. For j = New base To New first() step new second() ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC33038: Type 'base' must define operator '+' to be used in a 'For' statement. For j = New base To New first() step new second() ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC33038: Type 'base' must define operator '&lt;=' to be used in a 'For' statement. For j = New base To New first() step new second() ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC33038: Type 'base' must define operator '>=' to be used in a 'For' statement. For j = New base To New first() step new second() ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact(), WorkItem(542069, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542069")> Public Sub BC30337ERR_ForLoopType1_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ForLoopType1"> <file name="a.vb"> Option Strict On Option Infer Off Module Program Sub Main(args As String()) For x As Date = #1/2/0003# To 10 Next End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30337: 'For' loop control variable cannot be of type 'Date' because the type does not support the required operators. For x As Date = #1/2/0003# To 10 ~~~~~~~~~ </expected>) End Sub <Fact(), WorkItem(542069, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542069"), WorkItem(544464, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544464")> Public Sub BC30337ERR_ForLoopType1_3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ForLoopType1"> <file name="a.vb"> Option Strict On Option Infer Off Interface IFoo End Interface Module Program Sub Main(args As String()) For x As Boolean = False To True Next Dim foo as Boolean For foo = False To True Next for z as IFoo = nothing to nothing next End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30337: 'For' loop control variable cannot be of type 'Boolean' because the type does not support the required operators. For x As Boolean = False To True ~~~~~~~~~~~~ BC30337: 'For' loop control variable cannot be of type 'Boolean' because the type does not support the required operators. For foo = False To True ~~~ BC30337: 'For' loop control variable cannot be of type 'IFoo' because the type does not support the required operators. for z as IFoo = nothing to nothing ~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30367ERR_NoDefaultNotExtend1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C Shared Sub M(Of T)(x As C, y As T) N(x(0)) N(x!P) x(0) N(y(1)) N(y!Q) y(1) End Sub Shared Sub N(o As Object) End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30367: Class 'C' cannot be indexed because it has no default property. N(x(0)) ~ BC30367: Class 'C' cannot be indexed because it has no default property. N(x!P) ~ BC30454: Expression is not a method. x(0) ~ BC30547: 'T' cannot be indexed because it has no default property. N(y(1)) ~ BC30547: 'T' cannot be indexed because it has no default property. N(y!Q) ~ BC30454: Expression is not a method. y(1) ~ </expected>) End Sub <Fact()> Public Sub BC30369ERR_BadInstanceMemberAccess_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Structure S1 Dim b3 As Integer() Public Shared Sub Scenario_6() dim b4 = b3 End Sub shared Function foo() As Integer() Return b3 End Function End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30369: Cannot refer to an instance member of a class from within a shared method or shared member initializer without an explicit instance of the class. dim b4 = b3 ~~ BC30369: Cannot refer to an instance member of a class from within a shared method or shared member initializer without an explicit instance of the class. Return b3 ~~ </expected>) End Sub <Fact()> Public Sub BC30369ERR_BadInstanceMemberAccess_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C Property P Get Return Nothing End Get Set End Set End Property Shared Sub M() Dim o = P P = o End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30369: Cannot refer to an instance member of a class from within a shared method or shared member initializer without an explicit instance of the class. Dim o = P ~ BC30369: Cannot refer to an instance member of a class from within a shared method or shared member initializer without an explicit instance of the class. P = o ~ </expected>) End Sub <Fact()> Public Sub BC30369ERR_BadInstanceMemberAccess_3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C Shared Sub Main() For Each x As Integer In F(x) Next End Sub Private Sub F(x As Integer) End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30369: Cannot refer to an instance member of a class from within a shared method or shared member initializer without an explicit instance of the class. For Each x As Integer In F(x) ~ </expected>) End Sub <Fact()> Public Sub BC30369ERR_BadInstanceMemberAccess_4() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C Shared Sub Main() For Each x As Integer In F(x) Next End Sub Private Function F(x As Integer) As Object Return New Object() End Function End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30369: Cannot refer to an instance member of a class from within a shared method or shared member initializer without an explicit instance of the class. For Each x As Integer In F(x) ~ </expected>) End Sub <Fact()> Public Sub BC30369ERR_BadInstanceMemberAccess_5() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C Property P1(ByVal x As Integer) As integer Get Return x +5 End Get Set(ByVal Value As integer) End Set End Property Public Shared Sub Main() For Each x As integer In New integer() {P1(x), P1(x), P1(x)} Next End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30369: Cannot refer to an instance member of a class from within a shared method or shared member initializer without an explicit instance of the class. For Each x As integer In New integer() {P1(x), P1(x), P1(x)} ~~ BC30369: Cannot refer to an instance member of a class from within a shared method or shared member initializer without an explicit instance of the class. For Each x As integer In New integer() {P1(x), P1(x), P1(x)} ~~ BC30369: Cannot refer to an instance member of a class from within a shared method or shared member initializer without an explicit instance of the class. For Each x As integer In New integer() {P1(x), P1(x), P1(x)} ~~ </expected>) End Sub <Fact()> Public Sub BC30369ERR_BadInstanceMemberAccess_6() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C Public Shared Sub Main() For Each x As Integer In New Integer() {foo(x), foo(x), foo(x)} Next End Sub Function foo(ByRef x As Integer) As Integer x = 10 Return x + 10 End Function End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30369: Cannot refer to an instance member of a class from within a shared method or shared member initializer without an explicit instance of the class. For Each x As Integer In New Integer() {foo(x), foo(x), foo(x)} ~~~ BC30369: Cannot refer to an instance member of a class from within a shared method or shared member initializer without an explicit instance of the class. For Each x As Integer In New Integer() {foo(x), foo(x), foo(x)} ~~~ BC30369: Cannot refer to an instance member of a class from within a shared method or shared member initializer without an explicit instance of the class. For Each x As Integer In New Integer() {foo(x), foo(x), foo(x)} ~~~ </expected>) End Sub <Fact()> Public Sub BC30369ERR_BadInstanceMemberAccess_7() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Option Strict Off Option Infer On Public Class MyClass1 Dim global_x As Integer = 10 Const global_y As Long = 20 Public Shared Sub Main() For global_x = global_y To 10 Next End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30369: Cannot refer to an instance member of a class from within a shared method or shared member initializer without an explicit instance of the class. For global_x = global_y To 10 ~~~~~~~~ </expected>) End Sub <Fact, WorkItem(529193, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529193")> Public Sub BC30369ERR_BadInstanceMemberAccess_8() CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class derive Shared Sub main() TestEvents End Sub Shared Sub TestEvents() Dim Obj As New Class1 RemoveHandler Obj.MyEvent, AddressOf EventHandler End Sub Function EventHandler() Return Nothing End Function Public Class Class1 Public Event MyEvent(ByRef x As Decimal) Sub CauseSomeEvent() RaiseEvent MyEvent(x:=1) End Sub End Class End Class </file> </compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_BadInstanceMemberAccess, "AddressOf EventHandler")) End Sub <Fact()> Public Sub BC30375ERR_NewIfNullOnNonClass() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="NewIfNullOnNonClass"> <file name="a.vb"> Module M1 Sub Foo() Dim interf1 As New Interface1() Dim interf2 = New Interface1() End Sub End Module Interface Interface1 End Interface </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30375: 'New' cannot be used on an interface. Dim interf1 As New Interface1() ~~~~~~~~~~~~~~~~ BC30375: 'New' cannot be used on an interface. Dim interf2 = New Interface1() ~~~~~~~~~~~~~~~~ </expected>) End Sub ''' We decided to not implement this for Roslyn as BC30569 and BC31411 cover the scenarios that BC30376 addresses. <Fact()> Public Sub BC30376ERR_NewIfNullOnAbstractClass1() CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="NewIfNullOnAbstractClass1"> <file name="a.vb"> Module M1 Sub Foo() Throw (New C1) End Sub End Module MustInherit Class C1 MustOverride Sub foo() End Class </file> </compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_NewOnAbstractClass, "New C1"), Diagnostic(ERRID.ERR_CantThrowNonException, "Throw (New C1)").WithArguments("C1")) End Sub <Fact(), WorkItem(999399, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/999399")> Public Sub BC30387ERR_NoConstructorOnBase2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="NoConstructorOnBase2"> <file name="a.vb"> Module M1 Class Base Sub New(ByVal x As Integer) End Sub End Class Class c1 Inherits Base End Class End Module </file> </compilation>) Dim expected = <expected> BC30387: Class 'M1.c1' must declare a 'Sub New' because its base class 'M1.Base' does not have an accessible 'Sub New' that can be called with no arguments. Class c1 ~~ </expected> CompilationUtils.AssertTheseDiagnostics(compilation, expected) CompilationUtils.AssertTheseDiagnostics(compilation.GetDiagnosticsForSyntaxTree(CompilationStage.Compile, compilation.SyntaxTrees.Single()), expected) End Sub <Fact()> Public Sub BC30389ERR_InaccessibleSymbol2() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module mod30389 Sub foo() 'COMPILEERROR: BC30389, "Namespace1.Module1.Class1.Struct1" Dim Scen3 As Namespace1.Module1.Class1.Struct1 Exit Sub End Sub End Module Namespace Namespace1 Module Module1 Private Class Class1 Public Structure Struct1 Public Int As Integer End Structure End Class End Module End Namespace </file> </compilation>) Dim expectedErrors1 = <errors> BC42024: Unused local variable: 'Scen3'. Dim Scen3 As Namespace1.Module1.Class1.Struct1 ~~~~~ BC30389: 'Namespace1.Module1.Class1' is not accessible in this context because it is 'Private'. Dim Scen3 As Namespace1.Module1.Class1.Struct1 ~~~~~~~~~~~~~~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC30389ERR_InaccessibleSymbol2_1() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C Protected Structure S End Structure Private F As Integer Private Property P As Integer Protected Shared ReadOnly Property Q(o) Get Return Nothing End Get End Property End Class Class D Shared Sub M(o) Dim x As C = Nothing M(New C.S()) M(x.F) M(x.P) M(C.Q(Nothing)) End Sub End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC30389: 'C.S' is not accessible in this context because it is 'Protected'. M(New C.S()) ~~~ BC30389: 'C.F' is not accessible in this context because it is 'Private'. M(x.F) ~~~ BC30389: 'C.P' is not accessible in this context because it is 'Private'. M(x.P) ~~~ BC30389: 'C.Q(o As Object)' is not accessible in this context because it is 'Protected'. M(C.Q(Nothing)) ~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC30390ERR_InaccessibleMember3() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C Protected Shared Function F() Return Nothing End Function Private Sub M(o) End Sub End Class Class D Shared Sub M(x As C) x.M(C.F()) End Sub End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC30390: 'C.Private Sub M(o As Object)' is not accessible in this context because it is 'Private'. x.M(C.F()) ~~~ BC30390: 'C.Protected Shared Function F() As Object' is not accessible in this context because it is 'Protected'. x.M(C.F()) ~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC30390ERR_InaccessibleMember3_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Class C1 Public Delegate Sub myDelegate() private shared sub mySub() end sub End Class Module M1 Sub Main() Dim d1 As C1.myDelegate d1 = New C1.myDelegate(addressof C1.mySub) d1 = addressof C1.mysub End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30390: 'C1.Private Shared Sub mySub()' is not accessible in this context because it is 'Private'. d1 = New C1.myDelegate(addressof C1.mySub) ~~~~~~~~ BC30390: 'C1.Private Shared Sub mySub()' is not accessible in this context because it is 'Private'. d1 = addressof C1.mysub ~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30390ERR_InaccessibleMember3_2a() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="BC30390ERR_InaccessibleMember3_2a"> <file name="a.vb"> Imports System Module M1 Class B Private Sub M() Console.WriteLine("B.M()") End Sub End Class Class D Inherits B Public Sub M() Console.WriteLine("D.M()") End Sub Public Sub Test() MyBase.M() Me.M() End Sub End Class Public Sub Main() Call (New D()).Test() End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30390: 'B.Private Sub M()' is not accessible in this context because it is 'Private'. MyBase.M() ~~~~~~~~ </expected>) End Sub <WorkItem(540640, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540640")> <Fact()> Public Sub BC30390ERR_InaccessibleMember3_3() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BC30390ERR_InaccessibleMember3_3"> <file name="a.vb"><![CDATA[ Imports System Namespace AttrRegress001 Public Class Attr Inherits Attribute Public Property PriSet() As Short Get Return 1 End Get Private Set(ByVal value As Short) End Set End Property Public Property ProSet() As Short Get Return 2 End Get Protected Set(ByVal value As Short) End Set End Property End Class 'COMPILEERROR: BC30390, "foo1" <Attr(PriSet:=1)> Class Scen2 End Class 'COMPILEERROR: BC30390, "foo2" <Attr(ProSet:=1)> Class Scen3 End Class End Namespace ]]></file> </compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_InaccessibleMember3, "PriSet").WithArguments("AttrRegress001.Attr", "Public Property PriSet As Short", "Private"), Diagnostic(ERRID.ERR_InaccessibleMember3, "ProSet").WithArguments("AttrRegress001.Attr", "Public Property ProSet As Short", "Protected")) End Sub <Fact()> Public Sub BC30392ERR_CatchNotException1() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="CatchNotException1"> <file name="a.vb"> Module M1 Sub Foo() Try Catch o As Object Throw End Try End Sub End Module </file> </compilation>) Dim expectedErrors1 = <errors> BC30392: 'Catch' cannot catch type 'Object' because it is not 'System.Exception' or a class that inherits from 'System.Exception'. Catch o As Object ~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC30393ERR_ExitTryNotWithinTry() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="ExitTryNotWithinTry"> <file name="a.vb"> Class S1 sub FOO() if (true) exit try End If End sub End CLASS </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30393: 'Exit Try' can only appear inside a 'Try' statement. exit try ~~~~~~~~ </expected>) End Sub <WorkItem(542801, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542801")> <Fact()> Public Sub BC30393ERR_ExitTryNotWithinTry_ExitFromFinally() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndReferences( <compilation name="ExitTryNotWithinTry"> <file name="a.vb"> Imports System Imports System.Linq Class BaseClass Function Method() As String Dim x = New Integer() {} x.Where(Function(y) Try Exit Try Catch ex1 As Exception When True Exit Try Finally Exit Try End Try Return y = "" End Function) Return "x" End Function End Class Class DerivedClass Inherits BaseClass Shared Sub Main() End Sub End Class </file> </compilation>, {Net40.SystemCore}) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30393: 'Exit Try' can only appear inside a 'Try' statement. Exit Try ~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30399ERR_MyBaseAbstractCall1_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> MustInherit Class Base MustOverride Sub Pearl() End Class MustInherit Class C2 Inherits Base Sub foo() Call MyBase.Pearl() End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30399: 'MyBase' cannot be used with method 'Public MustOverride Sub Pearl()' because it is declared 'MustOverride'. Call MyBase.Pearl() ~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30399ERR_MyBaseAbstractCall1_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> MustInherit Class A MustOverride Property P End Class Class B Inherits A Overrides Property P Get Return Nothing End Get Set(ByVal value As Object) End Set End Property Sub M() MyBase.P = MyBase.P End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30399: 'MyBase' cannot be used with method 'Public MustOverride Property P As Object' because it is declared 'MustOverride'. MyBase.P = MyBase.P ~~~~~~~~ BC30399: 'MyBase' cannot be used with method 'Public MustOverride Property P As Object' because it is declared 'MustOverride'. MyBase.P = MyBase.P ~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30399ERR_MyBaseAbstractCall1_3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System MustInherit Class Base MustOverride Sub Pearl() End Class MustInherit Class C2 Inherits Base Sub foo() Dim _action As Action = AddressOf MyBase.Pearl End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30399: 'MyBase' cannot be used with method 'Public MustOverride Sub Pearl()' because it is declared 'MustOverride'. Dim _action As Action = AddressOf MyBase.Pearl ~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30399ERR_MyBaseAbstractCall1_4() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System MustInherit Class Base MustOverride Function GetBar(i As Integer) As Integer End Class MustInherit Class C2 Inherits Base Sub foo() Dim f As Func(Of Func(Of Integer, String)) = Function() New Func(Of Integer, String)(AddressOf MyBase.GetBar) End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30399: 'MyBase' cannot be used with method 'Public MustOverride Function GetBar(i As Integer) As Integer' because it is declared 'MustOverride'. Dim f As Func(Of Func(Of Integer, String)) = Function() New Func(Of Integer, String)(AddressOf MyBase.GetBar) ~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30399ERR_MyBaseAbstractCall1_5() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System MustInherit Class Base MustOverride Function GetBar(i As Integer) As Integer End Class MustInherit Class C2 Inherits Base Public FLD As Func(Of Func(Of Integer, String)) = Function() New Func(Of Integer, String)(AddressOf MyBase.GetBar) Public Property PROP As Func(Of Func(Of Integer, String)) = Function() New Func(Of Integer, String)(AddressOf MyBase.GetBar) Public Overrides Function GetBar(i As Integer) As Integer Return Nothing End Function End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30399: 'MyBase' cannot be used with method 'Public MustOverride Function GetBar(i As Integer) As Integer' because it is declared 'MustOverride'. Function() New Func(Of Integer, String)(AddressOf MyBase.GetBar) ~~~~~~~~~~~~~ BC30399: 'MyBase' cannot be used with method 'Public MustOverride Function GetBar(i As Integer) As Integer' because it is declared 'MustOverride'. Function() New Func(Of Integer, String)(AddressOf MyBase.GetBar) ~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30399ERR_MyBaseAbstractCall1_6() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Class Base Function GetBar(i As Integer) As Integer Return Nothing End Function End Class Class C2 Inherits Base Sub foo() Dim f As Func(Of Func(Of Integer, String)) = Function() New Func(Of Integer, String)(AddressOf MyBase.GetBar) End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <errors></errors>) End Sub <Fact()> Public Sub BC30399ERR_MyBaseAbstractCall1_7() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Class Base Shared Function GetBar(i As Integer) As Integer Return 0 End Function Function GetFoo(i As Integer) As Integer Return 0 End Function End Class MustInherit Class C2 Inherits Base Public FLD As Func(Of Func(Of Integer, String)) = Function() New Func(Of Integer, String)(AddressOf MyBase.GetBar) Public Property PROP As Func(Of Func(Of Integer, String)) = Function() New Func(Of Integer, String)(AddressOf MyBase.GetFoo) End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <errors></errors>) End Sub <Fact> Public Sub BC30399ERR_MyBaseAbstractCall1_8() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Imports System.Runtime.CompilerServices MustInherit Class B Sub New() End Sub <DllImport("doo")> Shared Function DllImp(i As Integer) As Integer End Function Declare Function DeclareFtn Lib "foo" (i As Integer) As Integer End Class MustInherit Class C Inherits B Public FLD1 As Func(Of Func(Of Integer, String)) = Function() New Func(Of Integer, String)(AddressOf MyBase.DllImp) Public FLD2 As Func(Of Func(Of Integer, String)) = Function() New Func(Of Integer, String)(AddressOf MyBase.DeclareFtn) End Class ]]> </file> </compilation> CompileAndVerify(source) End Sub <Fact()> Public Sub BC30414ERR_ConvertArrayRankMismatch2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ConvertArrayRankMismatch2"> <file name="a.vb"> Module M1 Sub Main() Dim Ary1() As Integer = New Integer() {1} Dim Ary2 As Integer(,) = CType(Ary1, Integer(,)) End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30414: Value of type 'Integer()' cannot be converted to 'Integer(*,*)' because the array types have different numbers of dimensions. Dim Ary2 As Integer(,) = CType(Ary1, Integer(,)) ~~~~ </expected>) End Sub <Fact()> Public Sub BC30414ERR_ConvertArrayRankMismatch2_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ConvertArrayRankMismatch2"> <file name="a.vb"> Option Strict On Imports System Module Module1 Sub Main() Dim arr1 As Integer(,,) = New Integer(9, 5) {} ' Invalid Dim arr2 As Integer() = New Integer(9, 5) {} ' Invalid Dim arr3() As Integer = New Integer(2, 3) {} ' Invalid Dim arr4(,) As Integer = New Integer(2, 3, 1) {} ' Invalid End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30414: Value of type 'Integer(*,*)' cannot be converted to 'Integer(*,*,*)' because the array types have different numbers of dimensions. Dim arr1 As Integer(,,) = New Integer(9, 5) {} ' Invalid ~~~~~~~~~~~~~~~~~~~~ BC30414: Value of type 'Integer(*,*)' cannot be converted to 'Integer()' because the array types have different numbers of dimensions. Dim arr2 As Integer() = New Integer(9, 5) {} ' Invalid ~~~~~~~~~~~~~~~~~~~~ BC30414: Value of type 'Integer(*,*)' cannot be converted to 'Integer()' because the array types have different numbers of dimensions. Dim arr3() As Integer = New Integer(2, 3) {} ' Invalid ~~~~~~~~~~~~~~~~~~~~ BC30414: Value of type 'Integer(*,*,*)' cannot be converted to 'Integer(*,*)' because the array types have different numbers of dimensions. Dim arr4(,) As Integer = New Integer(2, 3, 1) {} ' Invalid ~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30414ERR_ConvertArrayRankMismatch2_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ConvertArrayRankMismatch2"> <file name="a.vb"> Option Strict On Imports System Module Module1 Sub Main() Dim myArray10 As Integer(,) = {1, 2} ' Invalid Dim myArray11 As Integer(,) = {{{1, 2}}} ' Invalid End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30414: Value of type 'Integer()' cannot be converted to 'Integer(*,*)' because the array types have different numbers of dimensions. Dim myArray10 As Integer(,) = {1, 2} ' Invalid ~~~~~~ BC30414: Value of type 'Integer(*,*,*)' cannot be converted to 'Integer(*,*)' because the array types have different numbers of dimensions. Dim myArray11 As Integer(,) = {{{1, 2}}} ' Invalid ~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30415ERR_RedimRankMismatch() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="RedimRankMismatch"> <file name="a.vb"> Class C1 Sub foo(ByVal Ary() As Date) ReDim Ary(4, 4) End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30415: 'ReDim' cannot change the number of dimensions of an array. ReDim Ary(4, 4) ~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30424ERR_ConstAsNonConstant() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="ConstAsNonConstant"> <file name="a.vb"> Class C1(Of T) Const f As T = Nothing Const c As C1(Of T) = Nothing End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30424: Constants must be of an intrinsic or enumerated type, not a class, structure, type parameter, or array type. Const f As T = Nothing ~ BC30424: Constants must be of an intrinsic or enumerated type, not a class, structure, type parameter, or array type. Const c As C1(Of T) = Nothing ~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30424ERR_ConstAsNonConstant02() Dim source = <compilation> <file name="a.vb"> Option strict on imports system Enum E foo End Enum structure S1 end structure Class C1 ' should work public const f1 as E = E.foo public const f2 as object = nothing public const f3 as boolean = True ' should not work public const f4 as C1 = nothing public const f5 as S1 = nothing public const f6() as integer = {1,2,3} public const f7() as S1 = {new S1(), new S1(), new S1()} Public shared Sub Main(args() as string) End sub End Class </file> </compilation> Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) CompilationUtils.AssertTheseDiagnostics(c1, <expected> BC30424: Constants must be of an intrinsic or enumerated type, not a class, structure, type parameter, or array type. public const f4 as C1 = nothing ~~ BC30424: Constants must be of an intrinsic or enumerated type, not a class, structure, type parameter, or array type. public const f5 as S1 = nothing ~~ BC30424: Constants must be of an intrinsic or enumerated type, not a class, structure, type parameter, or array type. public const f6() as integer = {1,2,3} ~~ BC30424: Constants must be of an intrinsic or enumerated type, not a class, structure, type parameter, or array type. public const f7() as S1 = {new S1(), new S1(), new S1()} ~~ </expected>) ' todo: the last two errors need to be removed once collection initialization is supported End Sub <Fact()> Public Sub BC30438ERR_ConstantWithNoValue() Dim source = <compilation> <file name="a.vb"> Option Strict On Option Infer On imports system Class C1 public const f1 public const f2 as object public const f3 as boolean Public shared Sub Main(args() as string) End sub End Class </file> </compilation> Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) CompilationUtils.AssertTheseDiagnostics(c1, <expected> BC30438: Constants must have a value. public const f1 ~~ BC30438: Constants must have a value. public const f2 as object ~~ BC30438: Constants must have a value. public const f3 as boolean ~~ </expected>) End Sub <Fact()> Public Sub BC30439ERR_ExpressionOverflow1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="ConvertArrayRankMismatch2"> <file name="a.vb"> Public Class C1 Shared Sub Main() Dim i As Integer i = 10000000000000 System.Console.WriteLine(i) End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30439: Constant expression not representable in type 'Integer'. i = 10000000000000 ~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30439ERR_ExpressionOverflow1_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="ConvertArrayRankMismatch2"> <file name="a.vb"> Public Class C1 Shared Sub Main() Dim FIRST As UInteger = (0UI - 860UI) End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30439: Constant expression not representable in type 'UInteger'. Dim FIRST As UInteger = (0UI - 860UI) ~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30451ERR_NameNotDeclared1_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C1 function foo() as integer return 1 End function End Class Class C2 function foo1() as integer dim s = foo() return 1 End function End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30451: 'foo' is not declared. It may be inaccessible due to its protection level. dim s = foo() ~~~ </expected>) End Sub <Fact()> Public Sub BC30451ERR_NameNotDeclared1_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C Shared ReadOnly Property P Get Return Nothing End Get End Property ReadOnly Property Q Get Return Nothing End Get End Property Property R Sub M() set_P(get_P) set_Q(get_Q) set_R(get_R) End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30451: 'set_P' is not declared. It may be inaccessible due to its protection level. set_P(get_P) ~~~~~ BC30451: 'get_P' is not declared. It may be inaccessible due to its protection level. set_P(get_P) ~~~~~ BC30451: 'set_Q' is not declared. It may be inaccessible due to its protection level. set_Q(get_Q) ~~~~~ BC30451: 'get_Q' is not declared. It may be inaccessible due to its protection level. set_Q(get_Q) ~~~~~ BC30451: 'set_R' is not declared. It may be inaccessible due to its protection level. set_R(get_R) ~~~~~ BC30451: 'get_R' is not declared. It may be inaccessible due to its protection level. set_R(get_R) ~~~~~ </expected>) End Sub <Fact()> Public Sub BC30451ERR_NameNotDeclared1_3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="NoDirectDelegateConstruction1"> <file name="a.vb"> Class C1 Public Delegate Sub myDelegate() private shared sub mySub() end sub End Class Module M1 Sub Main() Dim d1 As C1.myDelegate d1 = New C1.myDelegate(addressof BORG) d1 = addressof BORG End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30451: 'BORG' is not declared. It may be inaccessible due to its protection level. d1 = New C1.myDelegate(addressof BORG) ~~~~ BC30451: 'BORG' is not declared. It may be inaccessible due to its protection level. d1 = addressof BORG ~~~~ </expected>) End Sub <Fact()> Public Sub BC30451ERR_NameNotDeclared1_4() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="NoDirectDelegateConstruction1"> <file name="a.vb"> Class C Public Shared Sub Main() For Each x As Integer In New Integer() {1, 1, 1} 'COMPILEERROR: BC30451, "y" Next y 'escaped vs. nonescaped (should work)" For Each [x] As Integer In New Integer() {1, 1, 1} Next x End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30451: 'y' is not declared. It may be inaccessible due to its protection level. Next y ~ </expected>) End Sub <Fact()> Public Sub BC30451ERR_NameNotDeclared1_5() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="NoDirectDelegateConstruction1"> <file name="a.vb"> Option Infer Off Option Strict On Public Class MyClass1 Public Shared Sub Main() For n = 0 To 2 For m = 1 To 2 Next n Next m End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30451: 'n' is not declared. It may be inaccessible due to its protection level. For n = 0 To 2 ~ BC30451: 'm' is not declared. It may be inaccessible due to its protection level. For m = 1 To 2 ~ BC30451: 'n' is not declared. It may be inaccessible due to its protection level. Next n ~ BC30451: 'm' is not declared. It may be inaccessible due to its protection level. Next m ~ </expected>) End Sub <Fact()> Public Sub BC30451ERR_NameNotDeclared1_NoErrorDuplicationForObjectInitializer() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="BC30451ERR_NameNotDeclared1_NoErrorDuplicationForObjectInitializer"> <file name="a.vb"> Imports System Imports System.Collections.Generic Class S Public Y As Object End Class Public Module Program Public Sub Main(args() As String) Dim a, b, c As New S() With {.Y = aaa} End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30451: 'aaa' is not declared. It may be inaccessible due to its protection level. Dim a, b, c As New S() With {.Y = aaa} ~~~ </expected>) End Sub <Fact()> Public Sub BC30451ERR_NameNotDeclared1_NoWarningDuplicationForObjectInitializer() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="BC30451ERR_NameNotDeclared1_NoWarningDuplicationForObjectInitializer"> <file name="a.vb"> Option Strict On Imports System Class S Public Y As Byte End Class Public Module Program Public Sub Main(args() As String) Dim x As Integer = 1 Dim a, b, c As New S() With {.Y = x} End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30512: Option Strict On disallows implicit conversions from 'Integer' to 'Byte'. Dim a, b, c As New S() With {.Y = x} ~ </expected>) End Sub <Fact()> Public Sub BC30452ERR_BinaryOperands3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BinaryOperands3"> <file name="a.vb"> option infer on Class C1 dim d = new c1() + new c1.c2() function foo() as integer return 1 End function Class C2 function foo1() as integer dim d1 = new c1() dim d2 = new c2() dim d3 = d1 + d2 return 1 End function End Class End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30452: Operator '+' is not defined for types 'C1' and 'C1.C2'. dim d = new c1() + new c1.c2() ~~~~~~~~~~~~~~~~~~~~~~ BC30452: Operator '+' is not defined for types 'C1' and 'C1.C2'. dim d3 = d1 + d2 ~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30452ERR_BinaryOperands3_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BinaryOperands3"> <file name="a.vb"> Class C1 Class C2 function foo1(byval d1 as c1, byval d2 as c2 )as integer dim d3 as object = d1 + d2 return 1 End function End Class End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30452: Operator '+' is not defined for types 'C1' and 'C1.C2'. dim d3 as object = d1 + d2 ~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30452ERR_BinaryOperands3_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="None"> <file name="a.vb"> Imports System class myClass1 shared result = New Guid() And New Guid() End class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30452: Operator 'And' is not defined for types 'Guid' and 'Guid'. shared result = New Guid() And New Guid() ~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30452ERR_BinaryOperands3_3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="None"> <file name="a.vb"> Imports System Module Program Sub Main(args As String()) Dim f1 As New Foo(), f2 As New Foo(), f3 As New Foo() Dim b As Boolean = True f3 = If(b, f1 = New Foo(), f2 = New Foo()) b = False f3 = If(b, f1 = New Foo(), f2 = New Foo()) End Sub End Module Class Foo Public i As Integer End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30452: Operator '=' is not defined for types 'Foo' and 'Foo'. f3 = If(b, f1 = New Foo(), f2 = New Foo()) ~~~~~~~~~~~~~~ BC30452: Operator '=' is not defined for types 'Foo' and 'Foo'. f3 = If(b, f1 = New Foo(), f2 = New Foo()) ~~~~~~~~~~~~~~ BC30452: Operator '=' is not defined for types 'Foo' and 'Foo'. f3 = If(b, f1 = New Foo(), f2 = New Foo()) ~~~~~~~~~~~~~~ BC30452: Operator '=' is not defined for types 'Foo' and 'Foo'. f3 = If(b, f1 = New Foo(), f2 = New Foo()) ~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30452ERR_BinaryOperands3_4() CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="None"> <file name="a.vb"><![CDATA[ Module Program Sub Main() Dim First = New With {.a = 1, .b = 2} Dim Second = New With {.a = 1, .b = 2} 'COMPILEERROR: BC30452, "first = second" If first = second Then ElseIf second <> first Then End If End Sub End Module ]]></file> </compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_BinaryOperands3, "first = second").WithArguments("=", "<anonymous type: a As Integer, b As Integer>", "<anonymous type: a As Integer, b As Integer>"), Diagnostic(ERRID.ERR_BinaryOperands3, "second <> first").WithArguments("<>", "<anonymous type: a As Integer, b As Integer>", "<anonymous type: a As Integer, b As Integer>")) End Sub <Fact()> Public Sub BC30452ERR_BinaryOperands3_4a() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="BC30452ERR_BinaryOperands3_4a"> <file name="a.vb"><![CDATA[ Imports System Module Program Sub Main() 'COMPILEERROR: BC30452, "first = second" If New With {.a = 1, .b = 2} = New With {.a = 1, .b = 2} Then ElseIf New With {.a = 1, .b = 2} <> New With {.a = 1, .b = 2} Then End If End Sub End Module ]]></file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected><![CDATA[ BC30452: Operator '=' is not defined for types '<anonymous type: a As Integer, b As Integer>' and '<anonymous type: a As Integer, b As Integer>'. If New With {.a = 1, .b = 2} = New With {.a = 1, .b = 2} Then ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30452: Operator '<>' is not defined for types '<anonymous type: a As Integer, b As Integer>' and '<anonymous type: a As Integer, b As Integer>'. ElseIf New With {.a = 1, .b = 2} <> New With {.a = 1, .b = 2} Then ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></expected>) End Sub <Fact()> Public Sub BC30454ERR_ExpectedProcedure() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ExpectedProcedure"> <file name="a.vb"> Module IsNotError001mod Sub foo(byval value as integer()) value() exit sub End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30454: Expression is not a method. value() ~~~~~ </expected>) End Sub <Fact()> Public Sub BC30454ERR_ExpectedProcedure_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="ExpectedProcedure"> <file name="a.vb"> Class C Private s As String Shared Sub M(x As C, y() As Integer) Dim o As Object o = x.s(3) N(x.s(3)) x.s(3) ' BC30454 o = y(3) N(y(3)) y(3) ' BC30454 End Sub Shared Sub N(o) End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30454: Expression is not a method. x.s(3) ' BC30454 ~~~ BC30454: Expression is not a method. y(3) ' BC30454 ~ </expected>) End Sub <Fact()> Public Sub BC30455ERR_OmittedArgument2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C Default ReadOnly Property P(x, y) Get Return Nothing End Get End Property Shared Sub M(x As C) N(x!Q) End Sub Shared Sub N(o As Object) End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30455: Argument not specified for parameter 'y' of 'Public ReadOnly Default Property P(x As Object, y As Object) As Object'. N(x!Q) ~~~ </expected>) End Sub <Fact()> Public Sub BC30455ERR_OmittedArgument2_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Structure C1 &lt;System.Runtime.InteropServices.FieldOffset()&gt; Dim i As Integer End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30455: Argument not specified for parameter 'offset' of 'Public Overloads Sub New(offset As Integer)'. &lt;System.Runtime.InteropServices.FieldOffset()&gt; ~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30456ERR_NameNotMember2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class Class1 Private Shared foo As S1 Class Class2 Sub Test() foo.bar1() End Sub End Class End Class Structure S1 Public shared bar As String = "Hello" End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30456: 'bar1' is not a member of 'S1'. foo.bar1() ~~~~~~~~ </expected>) End Sub <WorkItem(538903, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538903")> <Fact()> Public Sub BC30456ERR_NameNotMember2_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module M1 Sub FOO() My.Application.Exit() End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30451: 'My' is not declared. It may be inaccessible due to its protection level. My.Application.Exit() ~~ </expected>) End Sub <Fact()> Public Sub BC30456ERR_NameNotMember2_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module M1 Sub FOO() Dim blnReturn As Boolean = False Dim x As System.Nullable(Of Integer) blnReturn = system.nullable.hasvalue(x) End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30456: 'hasvalue' is not a member of 'Nullable'. blnReturn = system.nullable.hasvalue(x) ~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30456ERR_NameNotMember2_3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C Shared ReadOnly Property P Get Return Nothing End Get End Property ReadOnly Property Q Get Return Nothing End Get End Property Sub M() C.set_P(C.get_P) Me.set_Q(Me.get_Q) End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30456: 'set_P' is not a member of 'C'. C.set_P(C.get_P) ~~~~~~~ BC30456: 'get_P' is not a member of 'C'. C.set_P(C.get_P) ~~~~~~~ BC30456: 'set_Q' is not a member of 'C'. Me.set_Q(Me.get_Q) ~~~~~~~~ BC30456: 'get_Q' is not a member of 'C'. Me.set_Q(Me.get_Q) ~~~~~~~~ </expected>) End Sub <WorkItem(10046, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub BC30456ERR_NameNotMember2_4() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Option Infer On Imports System Class Program Dim x As New Product With {.Name = "paperclips", .price1 = 1.29} End Class Class Product Property price As Double Property Name As String End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30456: 'price1' is not a member of 'Product'. Dim x As New Product With {.Name = "paperclips", .price1 = 1.29} ~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30456ERR_NameNotMember2_5() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="BC30456ERR_NameNotMember2_4"> <file name="a.vb"> Module M1 Class B End Class Class D Inherits B Public Shadows Sub M() End Sub Public Sub Test() MyBase.M() Me.M() End Sub End Class End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30456: 'M' is not a member of 'M1.B'. MyBase.M() ~~~~~~~~ </expected>) End Sub <WorkItem(529710, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529710")> <Fact()> Public Sub BC30456ERR_NameNotMember3_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Namespace N Module X Sub Main() N.Equals("", "") End Sub End Module End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30456: 'Equals' is not a member of 'N'. N.Equals("", "") ~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30469ERR_ObjectReferenceNotSupplied_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C1 function foo() as integer return 1 End function Class C2 function foo1() as integer dim s = foo() return 1 End function End Class End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30469: Reference to a non-shared member requires an object reference. dim s = foo() ~~~ </expected>) End Sub <Fact()> Public Sub BC30469ERR_ObjectReferenceNotSupplied_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="ObjectReferenceNotSupplied"> <file name="a.vb"> Class P(Of T) Public ReadOnly son As T Class P1 Sub New1(ByVal tval As T) son = tval End Sub End Class End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30469: Reference to a non-shared member requires an object reference. son = tval ~~~ </expected>) End Sub <Fact()> Public Sub BC30469ERR_ObjectReferenceNotSupplied_3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C Property P Get Return Nothing End Get Set(ByVal value) End Set End Property Shared Sub M() Dim o = C.P C.P = o End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30469: Reference to a non-shared member requires an object reference. Dim o = C.P ~~~ BC30469: Reference to a non-shared member requires an object reference. C.P = o ~~~ </expected>) End Sub <Fact()> Public Sub BC30469ERR_ObjectReferenceNotSupplied_4() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class A Property P Get Return Nothing End Get Set(ByVal value) End Set End Property Class B Sub M(ByVal value) P = value value = P End Sub End Class End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30469: Reference to a non-shared member requires an object reference. P = value ~ BC30469: Reference to a non-shared member requires an object reference. value = P ~ </expected>) End Sub <Fact()> Public Sub BC30469ERR_ObjectReferenceNotSupplied_FieldInitializers() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C1 public f1 as integer public shared f2 as integer = C1.f1 End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30469: Reference to a non-shared member requires an object reference. public shared f2 as integer = C1.f1 ~~~~~ </expected>) End Sub <Fact()> Public Sub BC30469ERR_ObjectReferenceNotSupplied_DelegateCreation() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="NoDirectDelegateConstruction1"> <file name="a.vb"> Class C1 Public Delegate Sub myDelegate() public sub mySub() end sub End Class Module M1 Sub foo() Dim d1 As C1.myDelegate d1 = New C1.myDelegate(addressof C1.mySub) End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30469: Reference to a non-shared member requires an object reference. d1 = New C1.myDelegate(addressof C1.mySub) ~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30470ERR_MyClassNotInClass() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="MyClassNotInClass"> <file name="a.vb"> Module M1 Sub FOO() MyClass.New() End Sub Sub New() End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30470: 'MyClass' cannot be used outside of a class. MyClass.New() ~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30487ERR_UnaryOperand2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="UnaryOperand2"> <file name="a.vb"> Class C1 Shared Sub FOO() Dim expr As c2 = new c2() expr = -expr End Sub End Class Class C2 End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30487: Operator '-' is not defined for type 'C2'. expr = -expr ~~~~~ </expected>) End Sub <Fact()> Public Sub BC30491ERR_VoidValue() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="VoidValue"> <file name="a.vb"> Structure C1 Sub FOO() 'Dim a1 = If (True, New Object, TestMethod) 'Dim a2 = If (True, {TestMethod()}, {TestMethod()}) Dim a3 = TestMethod() = TestMethod() End Sub Sub TestMethod() End Sub End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30491: Expression does not produce a value. Dim a3 = TestMethod() = TestMethod() ~~~~~~~~~~~~ BC30491: Expression does not produce a value. Dim a3 = TestMethod() = TestMethod() ~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30491ERR_VoidValue_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="VoidValue"> <file name="a.vb"> Imports System Module Program Sub Main(args As String()) Dim x = If(True, Console.WriteLine(0), Console.WriteLine(1)) Dim y = If(True, fun_void(), fun_int(1)) Dim z = If(True, fun_Exception(1), fun_int(1)) Dim r = If(True, fun_long(0), fun_int(1)) Dim s = If(False, fun_long(0), fun_int(1)) End Sub Private Sub fun_void() Return End Sub Private Function fun_int(x As Integer) As Integer Return x End Function Private Function fun_long(x As Integer) As Long Return CLng(x) End Function Private Function fun_Exception(x As Integer) As Exception Return New Exception() End Function End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30491: Expression does not produce a value. Dim x = If(True, Console.WriteLine(0), Console.WriteLine(1)) ~~~~~~~~~~~~~~~~~~~~ BC30491: Expression does not produce a value. Dim x = If(True, Console.WriteLine(0), Console.WriteLine(1)) ~~~~~~~~~~~~~~~~~~~~ BC30491: Expression does not produce a value. Dim y = If(True, fun_void(), fun_int(1)) ~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30491ERR_VoidValue_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="VoidValue"> <file name="a.vb"> Imports System Module Program Sub Main(args As String()) Dim x As Integer = 1 Dim y As Object = 0 Dim s = If(True, fun(x), y) Dim s1 = If(False, sub1(x), y) End Sub Private Function fun(Of T)(Parm1 As T) As T Return Parm1 End Function Private Sub sub1(Of T)(Parm1 As T) End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30491: Expression does not produce a value. Dim s1 = If(False, sub1(x), y) ~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30491ERR_VoidValue_SelectCase() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="VoidValue"> <file name="a.vb"> Structure C1 Sub Foo() Select Case TestMethod() End Select End Sub Sub TestMethod() End Sub End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30491: Expression does not produce a value. Select Case TestMethod() ~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30500ERR_CircularEvaluation1() Dim source = <compilation> <file name="a.vb"> Option strict on imports system Class C1 Enum E A = A End Enum public const f1 as integer = f2 public const f2 as integer = f1 Public shared Sub Main(args() as string) Console.WriteLine(E.A) End sub End Class </file> </compilation> Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) CompilationUtils.AssertTheseDiagnostics(c1, <expected> BC30500: Constant 'A' cannot depend on its own value. A = A ~ BC30500: Constant 'f1' cannot depend on its own value. public const f1 as integer = f2 ~~ </expected>) End Sub <Fact()> Public Sub BC30500ERR_CircularEvaluation1_02() Dim source = <compilation> <file name="a.vb"> Option Strict On Option Infer On imports system Class C1 private const f1 = f2 private const f2 = f1 Public shared Sub Main(args() as string) console.writeline(f1) console.writeline(f2) End sub End Class </file> </compilation> Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) CompilationUtils.AssertTheseDiagnostics(c1, <expected> BC30500: Constant 'f1' cannot depend on its own value. private const f1 = f2 ~~ </expected>) End Sub <Fact(), WorkItem(528728, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528728")> Public Sub BC30500ERR_CircularEvaluation1_03() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="CircularEvaluation1"> <file name="a.vb"> Module M1 Sub New() Const Val As Integer = Val End Sub End Module </file> </compilation>) compilation.AssertTheseDiagnostics( <expected> BC30500: Constant 'Val' cannot depend on its own value. Const Val As Integer = Val ~~~ </expected>) End Sub <Fact()> Public Sub BC30500ERR_CircularEvaluation1_04() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C Const c0, c1 = c2 + 1 Const c2, c3 = c0 + 1 End Class </file> </compilation>) compilation.AssertTheseDiagnostics( <expected> BC30500: Constant 'c0' cannot depend on its own value. Const c0, c1 = c2 + 1 ~~ BC30671: Explicit initialization is not permitted with multiple variables declared with a single type specifier. Const c0, c1 = c2 + 1 ~~~~~~~~~~~~~~~ BC30671: Explicit initialization is not permitted with multiple variables declared with a single type specifier. Const c2, c3 = c0 + 1 ~~~~~~~~~~~~~~~ BC30060: Conversion from 'Integer' to 'Object' cannot occur in a constant expression. Const c2, c3 = c0 + 1 ~ </expected>) End Sub <Fact()> Public Sub BC30512ERR_NarrowingConversionDisallowed2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="NarrowingConversionDisallowed2"> <file name="a.vb"> Option Strict On Imports System Module M1 Sub Foo() Dim b As Byte = 2 Dim c As Byte = 3 Dim s As Short = 2 Dim t As Short = 3 Dim i As Integer = 2 Dim j As Integer = 3 Dim l As Long = 2 Dim m As Long = 3 b = b &lt; c b = b ^ c s = s &lt; t s = s ^ t i = i &gt; j i = i ^ j l = l &gt; m l = l ^ m End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30512: Option Strict On disallows implicit conversions from 'Boolean' to 'Byte'. b = b &lt; c ~~~~~ BC30512: Option Strict On disallows implicit conversions from 'Double' to 'Byte'. b = b ^ c ~~~~~ BC30512: Option Strict On disallows implicit conversions from 'Boolean' to 'Short'. s = s &lt; t ~~~~~ BC30512: Option Strict On disallows implicit conversions from 'Double' to 'Short'. s = s ^ t ~~~~~ BC30512: Option Strict On disallows implicit conversions from 'Boolean' to 'Integer'. i = i &gt; j ~~~~~ BC30512: Option Strict On disallows implicit conversions from 'Double' to 'Integer'. i = i ^ j ~~~~~ BC30512: Option Strict On disallows implicit conversions from 'Boolean' to 'Long'. l = l &gt; m ~~~~~ BC30512: Option Strict On disallows implicit conversions from 'Double' to 'Long'. l = l ^ m ~~~~~ </expected>) End Sub <Fact()> Public Sub BC30512ERR_NarrowingConversionDisallowed2_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Option Strict On Class C Default ReadOnly Property P(i As Integer) As Object Get Return Nothing End Get End Property Shared Sub M(x As C) N(x("Q")) N(x!Q) End Sub Shared Sub N(o As Object) End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30512: Option Strict On disallows implicit conversions from 'String' to 'Integer'. N(x("Q")) ~~~ BC30512: Option Strict On disallows implicit conversions from 'String' to 'Integer'. N(x!Q) ~ </expected>) End Sub <Fact()> Public Sub BC30512ERR_NarrowingConversionDisallowed2_2() CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict On Module Program Sub Main(args As String()) Dim S1 As String = "3" Dim S1_b As Object = If(S1, 3, 2) Dim S2 As SByte = 4 Dim S2_b As Object = If(S2, 4, 2) Dim S3 As Byte = 5 Dim S3_b As Object = If(S3, 5, 2) Dim S4 As Short = 6 Dim S4_b As Object = If(S4, 6, 2) Dim S5 As UShort = 7 Dim S5_b As Object = If(S5, 7, 2) Dim S6 As Integer = 8 Dim S6_b As Object = If(S6, 8, 2) Dim S7 As UInteger = 9 Dim S7_b As Object = If(S7, 9, 2) Dim S8 As Long = 10 Dim S8_b As Object = If(S8, 10, 2) Dim S9 As Short? = 5 Dim S9_b As Object = If(S9, 3, 2) Dim S10 As Integer? = 51 Dim S10_b As Object = If(S10, 3, 2) Dim S11 As Boolean? = Nothing Dim S11_b As Object = If(S11, 3, 2) End Sub End Module </file> </compilation>).VerifyDiagnostics( Diagnostic(ERRID.ERR_NarrowingConversionDisallowed2, "S1").WithArguments("String", "Boolean"), Diagnostic(ERRID.ERR_NarrowingConversionDisallowed2, "S2").WithArguments("SByte", "Boolean"), Diagnostic(ERRID.ERR_NarrowingConversionDisallowed2, "S3").WithArguments("Byte", "Boolean"), Diagnostic(ERRID.ERR_NarrowingConversionDisallowed2, "S4").WithArguments("Short", "Boolean"), Diagnostic(ERRID.ERR_NarrowingConversionDisallowed2, "S5").WithArguments("UShort", "Boolean"), Diagnostic(ERRID.ERR_NarrowingConversionDisallowed2, "S6").WithArguments("Integer", "Boolean"), Diagnostic(ERRID.ERR_NarrowingConversionDisallowed2, "S7").WithArguments("UInteger", "Boolean"), Diagnostic(ERRID.ERR_NarrowingConversionDisallowed2, "S8").WithArguments("Long", "Boolean"), Diagnostic(ERRID.ERR_NarrowingConversionDisallowed2, "S9").WithArguments("Short?", "Boolean?"), Diagnostic(ERRID.ERR_NarrowingConversionDisallowed2, "S10").WithArguments("Integer?", "Boolean?")) End Sub <Fact()> Public Sub BC30512ERR_NarrowingConversionDisallowed2_3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict On Imports System Module Program Sub Main(args As String()) Dim S1_a As Short? = 5 Dim S1_b As Integer? = 51 Dim S1_c As Short? = If(True, S1_a, S1_b) Dim S1_d As Boolean? = If(True, S1_a, S1_b) Dim S2_a As Char Dim S2_b As String = "31" Dim S2_c As String = If(True, S2_a, S2_b) Dim S2_d As Char = If(False, S2_a, S2_b) Dim S2_e As Short = If(False, S2_a, S2_b) End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30512: Option Strict On disallows implicit conversions from 'Integer?' to 'Short?'. Dim S1_c As Short? = If(True, S1_a, S1_b) ~~~~~~~~~~~~~~~~~~~~ BC30512: Option Strict On disallows implicit conversions from 'Integer?' to 'Boolean?'. Dim S1_d As Boolean? = If(True, S1_a, S1_b) ~~~~~~~~~~~~~~~~~~~~ BC30512: Option Strict On disallows implicit conversions from 'String' to 'Char'. Dim S2_d As Char = If(False, S2_a, S2_b) ~~~~~~~~~~~~~~~~~~~~~ BC30512: Option Strict On disallows implicit conversions from 'String' to 'Short'. Dim S2_e As Short = If(False, S2_a, S2_b) ~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30512ERR_NarrowingConversionDisallowed2_4() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Option Strict On Public Class MyClass1 Public Shared Sub Main() For ivar As Integer = 0.1 To 10 Next For dvar As Double = #12:00:00 AM# To 10 Next For dvar As Double = True To 10 Next For dvar1 As Double = 123&amp; To 10 'ok Next End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30512: Option Strict On disallows implicit conversions from 'Double' to 'Integer'. For ivar As Integer = 0.1 To 10 ~~~ BC30532: Conversion from 'Date' to 'Double' requires calling the 'Date.ToOADate' method. For dvar As Double = #12:00:00 AM# To 10 ~~~~~~~~~~~~~ BC30512: Option Strict On disallows implicit conversions from 'Boolean' to 'Double'. For dvar As Double = True To 10 ~~~~ </expected>) End Sub <Fact()> Public Sub BC30512ERR_NarrowingConversionDisallowed2_5() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict On Imports System Module Module1 Sub Main() Dim arr As Integer(,) = New Integer(1.0, 4) {} ' Invalid Dim arr1 As Integer(,) = New Integer(CDbl(5), 4) {} ' Invalid Dim arr2 As Integer(,) = New Integer(CDec(5), 4) {} ' Invalid Dim arr3 As Integer(,) = New Integer(CSng(5), 4) {} ' Invalid Dim x As Double = 5 Dim arr4 As Integer(,) = New Integer(x, 4) {} ' Invalid Dim y As Single = 5 Dim arr5 As Integer(,) = New Integer(y, 4) {} ' Invalid Dim z As Decimal = 5 Dim arr6 As Integer(,) = New Integer(z, 4) {} ' Invalid Dim m As Boolean = True Dim arr7 As Integer(,) = New Integer(m, 4) {} ' Invalid End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30512: Option Strict On disallows implicit conversions from 'Double' to 'Integer'. Dim arr As Integer(,) = New Integer(1.0, 4) {} ' Invalid ~~~ BC30512: Option Strict On disallows implicit conversions from 'Double' to 'Integer'. Dim arr1 As Integer(,) = New Integer(CDbl(5), 4) {} ' Invalid ~~~~~~~ BC30512: Option Strict On disallows implicit conversions from 'Decimal' to 'Integer'. Dim arr2 As Integer(,) = New Integer(CDec(5), 4) {} ' Invalid ~~~~~~~ BC30512: Option Strict On disallows implicit conversions from 'Single' to 'Integer'. Dim arr3 As Integer(,) = New Integer(CSng(5), 4) {} ' Invalid ~~~~~~~ BC30512: Option Strict On disallows implicit conversions from 'Double' to 'Integer'. Dim arr4 As Integer(,) = New Integer(x, 4) {} ' Invalid ~ BC30512: Option Strict On disallows implicit conversions from 'Single' to 'Integer'. Dim arr5 As Integer(,) = New Integer(y, 4) {} ' Invalid ~ BC30512: Option Strict On disallows implicit conversions from 'Decimal' to 'Integer'. Dim arr6 As Integer(,) = New Integer(z, 4) {} ' Invalid ~ BC30512: Option Strict On disallows implicit conversions from 'Boolean' to 'Integer'. Dim arr7 As Integer(,) = New Integer(m, 4) {} ' Invalid ~ </expected>) End Sub <Fact()> Public Sub BC30512ERR_NarrowingConversionDisallowed2_6() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict On Imports System Module Module1 Sub Main() Dim myArray9 As Char(,) = New Char(2, 1) {{"a", "b"}, {"c", "d"}, {"e", "f"}} End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30512: Option Strict On disallows implicit conversions from 'String' to 'Char'. Dim myArray9 As Char(,) = New Char(2, 1) {{"a", "b"}, {"c", "d"}, {"e", "f"}} ~~~ BC30512: Option Strict On disallows implicit conversions from 'String' to 'Char'. Dim myArray9 As Char(,) = New Char(2, 1) {{"a", "b"}, {"c", "d"}, {"e", "f"}} ~~~ BC30512: Option Strict On disallows implicit conversions from 'String' to 'Char'. Dim myArray9 As Char(,) = New Char(2, 1) {{"a", "b"}, {"c", "d"}, {"e", "f"}} ~~~ BC30512: Option Strict On disallows implicit conversions from 'String' to 'Char'. Dim myArray9 As Char(,) = New Char(2, 1) {{"a", "b"}, {"c", "d"}, {"e", "f"}} ~~~ BC30512: Option Strict On disallows implicit conversions from 'String' to 'Char'. Dim myArray9 As Char(,) = New Char(2, 1) {{"a", "b"}, {"c", "d"}, {"e", "f"}} ~~~ BC30512: Option Strict On disallows implicit conversions from 'String' to 'Char'. Dim myArray9 As Char(,) = New Char(2, 1) {{"a", "b"}, {"c", "d"}, {"e", "f"}} ~~~ </expected>) End Sub <Fact()> Public Sub BC30512ERR_NarrowingConversionDisallowed2_7() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Infer On Option Strict On Imports System Imports Microsoft.VisualBasic.Strings Module Module1 Sub Main(args As String()) Dim arr As Integer(,) = New Integer(4, 4) {} Dim x As Integer = 0 Dim idx As Double = 2.0 Dim idx1 As ULong = 0 Dim idx2 As Char = ChrW(3) arr(idx, 3) = 100 ' Invalid arr(idx1, x) = 100 ' Invalid arr(idx2, 3) = 100 'Invalid arr(" "c, 32) = 100 'Invalid Dim arr1 As Integer(,,) = {{{1, 2}, {1, 2}}, {{1, 2}, {1, 2}}} Dim i1 As ULong = 0 Dim i2 As UInteger = 0 Dim i3 As Integer = 0 arr1(i1, i2, i3) = 9 ' Invalid End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30512: Option Strict On disallows implicit conversions from 'Double' to 'Integer'. arr(idx, 3) = 100 ' Invalid ~~~ BC30512: Option Strict On disallows implicit conversions from 'ULong' to 'Integer'. arr(idx1, x) = 100 ' Invalid ~~~~ BC32006: 'Char' values cannot be converted to 'Integer'. Use 'Microsoft.VisualBasic.AscW' to interpret a character as a Unicode value or 'Microsoft.VisualBasic.Val' to interpret it as a digit. arr(idx2, 3) = 100 'Invalid ~~~~ BC32006: 'Char' values cannot be converted to 'Integer'. Use 'Microsoft.VisualBasic.AscW' to interpret a character as a Unicode value or 'Microsoft.VisualBasic.Val' to interpret it as a digit. arr(" "c, 32) = 100 'Invalid ~~~~ BC30512: Option Strict On disallows implicit conversions from 'ULong' to 'Integer'. arr1(i1, i2, i3) = 9 ' Invalid ~~ BC30512: Option Strict On disallows implicit conversions from 'UInteger' to 'Integer'. arr1(i1, i2, i3) = 9 ' Invalid ~~ </expected>) End Sub <WorkItem(528762, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528762")> <Fact> Public Sub BC30512ERR_NarrowingConversionDisallowed2_8() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict On Option Infer On Public Class Class2(Of T As Res) Private x As T(,) = New T(1, 1) {{New Res(), New Res()}, {New Res(), New Res()}} ' invalid Public Sub Foo() Dim x As T(,) = New T(1, 2) {} End Sub End Class Public Class Res End Class </file> </compilation>).VerifyDiagnostics( Diagnostic(ERRID.ERR_NarrowingConversionDisallowed2, "New Res()").WithArguments("Res", "T"), Diagnostic(ERRID.ERR_NarrowingConversionDisallowed2, "New Res()").WithArguments("Res", "T"), Diagnostic(ERRID.ERR_NarrowingConversionDisallowed2, "New Res()").WithArguments("Res", "T"), Diagnostic(ERRID.ERR_NarrowingConversionDisallowed2, "New Res()").WithArguments("Res", "T")) End Sub <Fact()> Public Sub BC30512ERR_SelectCaseNarrowingConversionErrors() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports System Module M1 Sub Main() Dim success As Boolean = True For count = 0 To 13 Test(count, success) Next If success Then Console.Write("Success") Else Console.Write("Fail") End If End Sub Sub Test(count As Integer, ByRef success As Boolean) Dim Bo As Boolean Dim Ob As Object Dim SB As SByte Dim By As Byte Dim Sh As Short Dim US As UShort Dim [In] As Integer Dim UI As UInteger Dim Lo As Long Dim UL As ULong Dim De As Decimal Dim Si As Single Dim [Do] As Double Dim St As String Bo = False Ob = 1 SB = 2 By = 3 Sh = 4 US = 5 [In] = 6 UI = 7 Lo = 8 UL = 9 Si = 10 [Do] = 11 De = 12D St = "13" Select Case count Case Bo success = success AndAlso If(count = 0, True, False) Case Is < Ob success = success AndAlso If(count = 1, True, False) Case SB success = success AndAlso If(count = 2, True, False) Case By success = success AndAlso If(count = 3, True, False) Case Sh success = success AndAlso If(count = 4, True, False) Case US success = success AndAlso If(count = 5, True, False) Case [In] success = success AndAlso If(count = 6, True, False) Case UI To Lo success = success AndAlso If(count = 7, True, False) Case Lo success = success AndAlso If(count = 8, True, False) Case UL success = success AndAlso If(count = 9, True, False) Case Si success = success AndAlso If(count = 10, True, False) Case [Do] success = success AndAlso If(count = 11, True, False) Case De success = success AndAlso If(count = 12, True, False) Case St success = success AndAlso If(count = 13, True, False) Case Else success = False End Select End Sub End Module ]]></file> </compilation>) Dim expectedErrors = <errors><![CDATA[ BC30512: Option Strict On disallows implicit conversions from 'Boolean' to 'Integer'. Case Bo ~~ BC30038: Option Strict On prohibits operands of type Object for operator '<'. Case Is < Ob ~~ BC30512: Option Strict On disallows implicit conversions from 'UInteger' to 'Integer'. Case UI To Lo ~~ BC30512: Option Strict On disallows implicit conversions from 'Long' to 'Integer'. Case UI To Lo ~~ BC30512: Option Strict On disallows implicit conversions from 'Long' to 'Integer'. Case Lo ~~ BC30512: Option Strict On disallows implicit conversions from 'ULong' to 'Integer'. Case UL ~~ BC30512: Option Strict On disallows implicit conversions from 'Single' to 'Integer'. Case Si ~~ BC30512: Option Strict On disallows implicit conversions from 'Double' to 'Integer'. Case [Do] ~~~~ BC30512: Option Strict On disallows implicit conversions from 'Decimal' to 'Integer'. Case De ~~ BC30512: Option Strict On disallows implicit conversions from 'String' to 'Integer'. Case St ~~ ]]></errors> CompilationUtils.AssertTheseDiagnostics(compilation, expectedErrors) End Sub <Fact()> Public Sub BC30516ERR_NoArgumentCountOverloadCandidates1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="NoArgumentCountOverloadCandidates1"> <file name="a.vb"> Module Module1 Class C0 Public whichOne As String Sub Foo(ByVal t1 As String) whichOne = "T" End Sub End Class Class C1 Inherits C0 Overloads Sub Foo(ByVal y1 As String) whichOne = "Y" End Sub End Class Sub test() Dim [ident1] As C0 = New C0() Dim clsNarg2get As C1 = New C1() Dim str1 As String = "Visual Basic" 'COMPILEERROR: BC30516, "y" clsNarg2get.Foo(1, y1:=2) 'COMPILEERROR: BC30516, "x" clsNarg2get.Foo(y1:=1, y1:=1) End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30516: Overload resolution failed because no accessible 'Foo' accepts this number of arguments. clsNarg2get.Foo(1, y1:=2) ~~~ BC30516: Overload resolution failed because no accessible 'Foo' accepts this number of arguments. clsNarg2get.Foo(y1:=1, y1:=1) ~~~ </expected>) End Sub <Fact()> Public Sub BC30517ERR_NoViableOverloadCandidates1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="NoViableOverloadCandidates1"> <file name="a.vb"> Imports System &lt;AttributeUsage(AttributeTargets.All)&gt; Class attr2 Inherits Attribute Private Sub New(ByVal i As Integer) End Sub Protected Sub New(ByVal i As Char) End Sub End Class &lt;attr2(1)&gt; Class target2 End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30517: Overload resolution failed because no 'New' is accessible. &lt;attr2(1)&gt; Class target2 ~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30518ERR_NoCallableOverloadCandidates2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="NoCallableOverloadCandidates2"> <file name="a.vb"> class M1 Sub sub1(Of U, V) (ByVal p1 As U, ByVal p2 As V) End Sub Sub sub1(Of U, V) (ByVal p1() As V, ByVal p2() As U) End Sub Sub GenMethod6210() sub1(Of String, Integer) (17@, #3/3/2003#) sub1(Of Integer, String) (New Integer() {1, 2, 3}, New String() {"a", "b"}) End Sub End class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30518: Overload resolution failed because no accessible 'sub1' can be called with these arguments: 'Public Sub sub1(Of String, Integer)(p1 As String, p2 As Integer)': Value of type 'Date' cannot be converted to 'Integer'. 'Public Sub sub1(Of String, Integer)(p1 As Integer(), p2 As String())': Value of type 'Decimal' cannot be converted to 'Integer()'. 'Public Sub sub1(Of String, Integer)(p1 As Integer(), p2 As String())': Value of type 'Date' cannot be converted to 'String()'. sub1(Of String, Integer) (17@, #3/3/2003#) ~~~~~~~~~~~~~~~~~~~~~~~~ BC30518: Overload resolution failed because no accessible 'sub1' can be called with these arguments: 'Public Sub sub1(Of Integer, String)(p1 As Integer, p2 As String)': Value of type 'Integer()' cannot be converted to 'Integer'. 'Public Sub sub1(Of Integer, String)(p1 As Integer, p2 As String)': Value of type 'String()' cannot be converted to 'String'. 'Public Sub sub1(Of Integer, String)(p1 As String(), p2 As Integer())': Value of type 'Integer()' cannot be converted to 'String()' because 'Integer' is not derived from 'String'. 'Public Sub sub1(Of Integer, String)(p1 As String(), p2 As Integer())': Value of type 'String()' cannot be converted to 'Integer()' because 'String' is not derived from 'Integer'. sub1(Of Integer, String) (New Integer() {1, 2, 3}, New String() {"a", "b"}) ~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <WorkItem(546763, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546763")> <Fact()> Public Sub BC30518ERR_NoCallableOverloadCandidates_LateBindingDisabled() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="a.vb"> Option Strict On Option Infer On Imports System Imports System.Threading.Tasks Public Module Program Sub Main() Dim a As Object = Nothing Parallel.ForEach(a, Sub(x As Object) Console.WriteLine(x)) End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30518: Overload resolution failed because no accessible 'ForEach' can be called with these arguments: 'Public Shared Overloads Function ForEach(Of TSource)(source As IEnumerable(Of TSource), body As Action(Of TSource)) As ParallelLoopResult': Data type(s) of the type parameter(s) cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error. 'Public Shared Overloads Function ForEach(Of TSource)(source As IEnumerable(Of TSource), body As Action(Of TSource, ParallelLoopState)) As ParallelLoopResult': Data type(s) of the type parameter(s) cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error. 'Public Shared Overloads Function ForEach(Of TSource)(source As IEnumerable(Of TSource), body As Action(Of TSource, ParallelLoopState, Long)) As ParallelLoopResult': Data type(s) of the type parameter(s) cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error. 'Public Shared Overloads Function ForEach(Of TSource)(source As Partitioner(Of TSource), body As Action(Of TSource)) As ParallelLoopResult': Data type(s) of the type parameter(s) cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error. 'Public Shared Overloads Function ForEach(Of TSource)(source As Partitioner(Of TSource), body As Action(Of TSource, ParallelLoopState)) As ParallelLoopResult': Data type(s) of the type parameter(s) cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error. 'Public Shared Overloads Function ForEach(Of TSource)(source As OrderablePartitioner(Of TSource), body As Action(Of TSource, ParallelLoopState, Long)) As ParallelLoopResult': Data type(s) of the type parameter(s) cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error. Parallel.ForEach(a, Sub(x As Object) Console.WriteLine(x)) ~~~~~~~ </expected>) End Sub <Fact(), WorkItem(542956, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542956")> Public Sub BC30518ERR_NoCallableOverloadCandidates2_trycatch() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndReferences( <compilation name="ExitTryNotWithinTry"> <file name="a.vb"> Imports System Imports System.Linq Class BaseClass Function Method() As String Dim x = New Integer() {} x.Where(Function(y) Try Exit Try Catch ex1 As Exception When True Exit Try Finally Exit Function End Try Return y = "" End Function) Return "x" End Function End Class Class DerivedClass Inherits BaseClass Shared Sub Main() End Sub End Class </file> </compilation>, {Net40.SystemCore}) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30101: Branching out of a 'Finally' is not valid. Exit Function ~~~~~~~~~~~~~ BC42353: Function '&lt;anonymous method>' doesn't return a value on all code paths. Are you missing a 'Return' statement? End Function) ~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30519ERR_NoNonNarrowingOverloadCandidates2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="NoNonNarrowingOverloadCandidates2"> <file name="a.vb"> Module Module1 Class C0(Of T) Public whichOne As String Sub Foo(ByVal t1 As T) whichOne = "T" End Sub Default Property Prop1(ByVal t1 As T) As Integer Get Return 100 End Get Set(ByVal Value As Integer) whichOne = "T" End Set End Property End Class Class C1(Of T, Y) Inherits C0(Of T) Overloads Sub Foo(ByVal y1 As Y) whichOne = "Y" End Sub Default Overloads Property Prop1(ByVal y1 As Y) As Integer Get Return 200 End Get Set(ByVal Value As Integer) whichOne = "Y" End Set End Property End Class Structure S1 Dim i As Integer End Structure Class Scenario11 Public Shared Narrowing Operator CType(ByVal Arg As Scenario11) As C1(Of Integer, Integer) Return New C1(Of Integer, Integer) End Operator Public Shared Narrowing Operator CType(ByVal Arg As Scenario11) As S1 Return New S1 End Operator End Class Sub GenUnif0060() Dim iTmp As Integer = 2000 Dim dTmp As Decimal = CDec(2000000) Dim tc2 As New C1(Of S1, C1(Of Integer, Integer)) Dim tc3 As New C1(Of Short, Long) Dim sc11 As New Scenario11 ' COMPILEERROR: BC30519,"Call tc2.Foo (New Scenario11)" Call tc2.Foo(New Scenario11) ' COMPILEERROR: BC30519,"Call tc2.Foo (sc11)" Call tc2.Foo(sc11) ' COMPILEERROR: BC30519,"Call tc3.Foo (dTmp)" Call tc3.Foo(dTmp) ' COMPILEERROR: BC30519,"tc2 (New Scenario11) = 1000" tc2(New Scenario11) = 1000 ' COMPILEERROR: BC30519,"tc2 (New Scenario11)" iTmp = tc2(New Scenario11) ' COMPILEERROR: BC30519,"tc3 (dTmp) = 2000" tc3(dTmp) = 2000 ' COMPILEERROR: BC30519,"tc3 (dTmp)" iTmp = tc3(dTmp) End Sub End Module </file> </compilation>) compilation.VerifyDiagnostics( Diagnostic(ERRID.ERR_NoNonNarrowingOverloadCandidates2, "Foo").WithArguments("Foo", <![CDATA[ 'Public Overloads Sub Foo(y1 As Module1.C1(Of Integer, Integer))': Argument matching parameter 'y1' narrows from 'Module1.Scenario11' to 'Module1.C1(Of Integer, Integer)'. 'Public Sub Foo(t1 As Module1.S1)': Argument matching parameter 't1' narrows from 'Module1.Scenario11' to 'Module1.S1'.]]>.Value.Replace(vbLf, Environment.NewLine)), Diagnostic(ERRID.ERR_NoNonNarrowingOverloadCandidates2, "Foo").WithArguments("Foo", <![CDATA[ 'Public Overloads Sub Foo(y1 As Module1.C1(Of Integer, Integer))': Argument matching parameter 'y1' narrows from 'Module1.Scenario11' to 'Module1.C1(Of Integer, Integer)'. 'Public Sub Foo(t1 As Module1.S1)': Argument matching parameter 't1' narrows from 'Module1.Scenario11' to 'Module1.S1'.]]>.Value.Replace(vbLf, Environment.NewLine)), Diagnostic(ERRID.ERR_NoNonNarrowingOverloadCandidates2, "Foo").WithArguments("Foo", <![CDATA[ 'Public Overloads Sub Foo(y1 As Long)': Argument matching parameter 'y1' narrows from 'Decimal' to 'Long'. 'Public Sub Foo(t1 As Short)': Argument matching parameter 't1' narrows from 'Decimal' to 'Short'.]]>.Value.Replace(vbLf, Environment.NewLine)), Diagnostic(ERRID.ERR_NoNonNarrowingOverloadCandidates2, "tc2").WithArguments("Prop1", <![CDATA[ 'Public Overloads Default Property Prop1(y1 As Module1.C1(Of Integer, Integer)) As Integer': Argument matching parameter 'y1' narrows from 'Module1.Scenario11' to 'Module1.C1(Of Integer, Integer)'. 'Public Default Property Prop1(t1 As Module1.S1) As Integer': Argument matching parameter 't1' narrows from 'Module1.Scenario11' to 'Module1.S1'.]]>.Value.Replace(vbLf, Environment.NewLine)), Diagnostic(ERRID.ERR_NoNonNarrowingOverloadCandidates2, "tc2").WithArguments("Prop1", <![CDATA[ 'Public Overloads Default Property Prop1(y1 As Module1.C1(Of Integer, Integer)) As Integer': Argument matching parameter 'y1' narrows from 'Module1.Scenario11' to 'Module1.C1(Of Integer, Integer)'. 'Public Default Property Prop1(t1 As Module1.S1) As Integer': Argument matching parameter 't1' narrows from 'Module1.Scenario11' to 'Module1.S1'.]]>.Value.Replace(vbLf, Environment.NewLine)), Diagnostic(ERRID.ERR_NoNonNarrowingOverloadCandidates2, "tc3").WithArguments("Prop1", <![CDATA[ 'Public Overloads Default Property Prop1(y1 As Long) As Integer': Argument matching parameter 'y1' narrows from 'Decimal' to 'Long'. 'Public Default Property Prop1(t1 As Short) As Integer': Argument matching parameter 't1' narrows from 'Decimal' to 'Short'.]]>.Value.Replace(vbLf, Environment.NewLine)), Diagnostic(ERRID.ERR_NoNonNarrowingOverloadCandidates2, "tc3").WithArguments("Prop1", <![CDATA[ 'Public Overloads Default Property Prop1(y1 As Long) As Integer': Argument matching parameter 'y1' narrows from 'Decimal' to 'Long'. 'Public Default Property Prop1(t1 As Short) As Integer': Argument matching parameter 't1' narrows from 'Decimal' to 'Short'.]]>.Value.Replace(vbLf, Environment.NewLine)) ) End Sub <Fact()> Public Sub BC30520ERR_ArgumentNarrowing3_RoslynBC30519() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ArgumentNarrowing3"> <file name="a.vb"> Option Strict Off Module Module1 Class sample7C1(Of X) Enum E e1 e2 e3 End Enum End Class Class sample7C2(Of T, Y) Public whichOne As String Sub Foo(ByVal p1 As sample7C1(Of T).E) whichOne = "1" End Sub Sub Foo(ByVal p1 As sample7C1(Of Y).E) whichOne = "2" End Sub Sub Scenario8(ByVal p1 As sample7C1(Of T).E) Call Me.Foo(p1) End Sub End Class Sub test() Dim tc7 As New sample7C2(Of Integer, Integer) Dim sc7 As New sample7C1(Of Byte) 'COMPILEERROR: BC30520, "sample7C1(Of Long).E.e1" Call tc7.Foo (sample7C1(Of Long).E.e1) 'COMPILEERROR: BC30520, "sample7C1(Of Short).E.e2" Call tc7.Foo (sample7C1(Of Short).E.e2) 'COMPILEERROR: BC30520, "sc7.E.e3" Call tc7.Foo (sc7.E.e3) End Sub End Module </file> </compilation>) ' BC0000 - Test bug ' Roslyn BC30519 - Dev11 BC30520 compilation.VerifyDiagnostics( Diagnostic(ERRID.ERR_NoNonNarrowingOverloadCandidates2, "Foo").WithArguments("Foo", <![CDATA[ 'Public Sub Foo(p1 As Module1.sample7C1(Of Integer).E)': Argument matching parameter 'p1' narrows from 'Module1.sample7C1(Of Long).E' to 'Module1.sample7C1(Of Integer).E'. 'Public Sub Foo(p1 As Module1.sample7C1(Of Integer).E)': Argument matching parameter 'p1' narrows from 'Module1.sample7C1(Of Long).E' to 'Module1.sample7C1(Of Integer).E'.]]>.Value.Replace(vbLf, Environment.NewLine)), Diagnostic(ERRID.ERR_NoNonNarrowingOverloadCandidates2, "Foo").WithArguments("Foo", <![CDATA[ 'Public Sub Foo(p1 As Module1.sample7C1(Of Integer).E)': Argument matching parameter 'p1' narrows from 'Module1.sample7C1(Of Short).E' to 'Module1.sample7C1(Of Integer).E'. 'Public Sub Foo(p1 As Module1.sample7C1(Of Integer).E)': Argument matching parameter 'p1' narrows from 'Module1.sample7C1(Of Short).E' to 'Module1.sample7C1(Of Integer).E'.]]>.Value.Replace(vbLf, Environment.NewLine)), Diagnostic(ERRID.WRN_SharedMemberThroughInstance, "sc7.E"), Diagnostic(ERRID.ERR_NoNonNarrowingOverloadCandidates2, "Foo").WithArguments("Foo", <![CDATA[ 'Public Sub Foo(p1 As Module1.sample7C1(Of Integer).E)': Argument matching parameter 'p1' narrows from 'Module1.sample7C1(Of Byte).E' to 'Module1.sample7C1(Of Integer).E'. 'Public Sub Foo(p1 As Module1.sample7C1(Of Integer).E)': Argument matching parameter 'p1' narrows from 'Module1.sample7C1(Of Byte).E' to 'Module1.sample7C1(Of Integer).E'.]]>.Value.Replace(vbLf, Environment.NewLine)) ) 'CompilationUtils.AssertTheseErrors(compilation, ' <expected> 'BC30520: Argument matching parameter 'p1' narrows from 'ConsoleApplication10.Module1.sample7C1(Of Long).E' to 'ConsoleApplication10.Module1.sample7C1(Of Integer).E'. ' Call tc7.Foo (sample7C1(Of Long).E.e1) ' ~~~~ 'BC30520: Argument matching parameter 'p1' narrows from 'ConsoleApplication10.Module1.sample7C1(Of Short).E' to 'ConsoleApplication10.Module1.sample7C1(Of Integer).E'. ' Call tc7.Foo (sample7C1(Of Short).E.e2) ' ~~~~ 'BC30520: Argument matching parameter 'p1' narrows from 'ConsoleApplication10.Module1.sample7C1(Of Byte).E' to 'ConsoleApplication10.Module1.sample7C1(Of Integer).E'. ' Call tc7.Foo (sc7.E.e3) ' ~~~~ '</expected>) End Sub <Fact()> Public Sub BC30521ERR_NoMostSpecificOverload2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="NoMostSpecificOverload2"> <file name="a.vb"> Module Module1 Class C0(Of T) Sub Foo(ByVal t1 As T) End Sub End Class Class C1(Of T, Y) Inherits C0(Of T) Overloads Sub Foo(ByVal y1 As Y) End Sub End Class Structure S1 Dim i As Integer End Structure Class C2 Public Shared Widening Operator CType(ByVal Arg As C2) As C1(Of Integer, Integer) Return New C1(Of Integer, Integer) End Operator Public Shared Widening Operator CType(ByVal Arg As C2) As S1 Return New S1 End Operator End Class Sub test() Dim C As New C1(Of S1, C1(Of Integer, Integer)) Call C.Foo(New C2) End Sub End Module </file> </compilation>) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_NoMostSpecificOverload2, "Foo").WithArguments("Foo", <![CDATA[ 'Public Overloads Sub Module1.C1(Of Module1.S1, Module1.C1(Of Integer, Integer)).Foo(y1 As Module1.C1(Of Integer, Integer))': Not most specific. 'Public Sub Module1.C0(Of Module1.S1).Foo(t1 As Module1.S1)': Not most specific.]]>.Value.Replace(vbLf, Environment.NewLine)) ) End Sub <Fact()> Public Sub BC30524ERR_NoGetProperty1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C WriteOnly Property P Set End Set End Property Shared WriteOnly Property Q Set End Set End Property Sub M() Dim o o = P o = Me.P o = Q o = C.Q End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30524: Property 'P' is 'WriteOnly'. o = P ~ BC30524: Property 'P' is 'WriteOnly'. o = Me.P ~~~~ BC30524: Property 'Q' is 'WriteOnly'. o = Q ~ BC30524: Property 'Q' is 'WriteOnly'. o = C.Q ~~~ </expected>) End Sub <Fact()> Public Sub BC30524ERR_NoGetProperty1_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Interface I Default WriteOnly Property P(s As String) End Interface Structure S Default WriteOnly Property Q(s As String) Set(value) End Set End Property End Structure Class C Default WriteOnly Property R(s As String) Set(value) End Set End Property Shared Sub M(x As I, y As S, z As C) x!Q = x!R y!Q = y!R z!Q = z!R End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30524: Property 'P' is 'WriteOnly'. x!Q = x!R ~~~ BC30524: Property 'Q' is 'WriteOnly'. y!Q = y!R ~~~ BC30524: Property 'R' is 'WriteOnly'. z!Q = z!R ~~~ </expected>) End Sub <Fact()> Public Sub BC30524ERR_NoGetProperty1_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module M1 Sub Main() foo(p) End Sub WriteOnly Property p() As Single Set(ByVal Value As Single) End Set End Property Public Sub foo(ByRef x As Single) End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30524: Property 'p' is 'WriteOnly'. foo(p) ~ </expected>) End Sub <Fact(), WorkItem(6810, "DevDiv_Projects/Roslyn")> Public Sub BC30524ERR_NoGetProperty1_3() CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C WriteOnly Property P As Object() Set(value As Object()) End Set End Property WriteOnly Property Q As System.Action(Of Object) Set(value As System.Action(Of Object)) End Set End Property WriteOnly Property R As C Set(value As C) End Set End Property Default ReadOnly Property S(i As Integer) Get Return Nothing End Get End Property Sub M() Dim o o = P()(1) o = Q()(2) o = R()(3) o = P(1) o = Q(2) o = R(3) End Sub End Class </file> </compilation>).VerifyDiagnostics( Diagnostic(ERRID.ERR_NoGetProperty1, "P()").WithArguments("P"), Diagnostic(ERRID.ERR_NoGetProperty1, "Q()").WithArguments("Q"), Diagnostic(ERRID.ERR_NoGetProperty1, "R()").WithArguments("R"), Diagnostic(ERRID.ERR_NoGetProperty1, "P").WithArguments("P"), Diagnostic(ERRID.ERR_NoGetProperty1, "Q").WithArguments("Q"), Diagnostic(ERRID.ERR_NoGetProperty1, "R").WithArguments("R")) End Sub ''' <summary> ''' Report BC30524 even in cases when the ''' expression will be ignored. ''' </summary> ''' <remarks></remarks> <Fact()> Public Sub BC30524ERR_NoGetProperty1_4() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Class A Class B Friend Const F As Object = Nothing End Class Shared WriteOnly Property P As A Set(value As A) End Set End Property Shared ReadOnly Property Q As A Get Return Nothing End Get End Property Shared Sub M() Dim o As Object o = P.B.F o = Q.B.F End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30524: Property 'P' is 'WriteOnly'. o = P.B.F ~ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. o = Q.B.F ~~~ </expected>) End Sub <Fact()> Public Sub BC30526ERR_NoSetProperty1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C ReadOnly Property P Get Return Nothing End Get End Property Shared ReadOnly Property Q Get Return Nothing End Get End Property Sub M() P = Nothing Me.P = Nothing Q = Nothing C.Q = Nothing End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30526: Property 'P' is 'ReadOnly'. P = Nothing ~~~~~~~~~~~ BC30526: Property 'P' is 'ReadOnly'. Me.P = Nothing ~~~~~~~~~~~~~~ BC30526: Property 'Q' is 'ReadOnly'. Q = Nothing ~~~~~~~~~~~ BC30526: Property 'Q' is 'ReadOnly'. C.Q = Nothing ~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30526ERR_NoSetProperty1_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Interface I Default ReadOnly Property P(s As String) End Interface Structure S Default ReadOnly Property Q(s As String) Get Return Nothing End Get End Property End Structure Class C Default ReadOnly Property R(s As String) Get Return Nothing End Get End Property Shared Sub M(x As I, y As S, z As C) x!Q = x!R y!Q = y!R z!Q = z!R End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30526: Property 'P' is 'ReadOnly'. x!Q = x!R ~~~~~~~~~ BC30526: Property 'Q' is 'ReadOnly'. y!Q = y!R ~~~~~~~~~ BC30526: Property 'R' is 'ReadOnly'. z!Q = z!R ~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30532ERR_DateToDoubleConversion() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="DateToDoubleConversion"> <file name="a.vb"> Structure s1 function foo() as double return #1/1/2000# End function End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30532: Conversion from 'Date' to 'Double' requires calling the 'Date.ToOADate' method. return #1/1/2000# ~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30532ERR_DateToDoubleConversion_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="DateToDoubleConversion"> <file name="a.vb"> Imports System Class C Shared Sub Main() For Each x As Double In New Date() {#12:00:00 AM#} Next End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30532: Conversion from 'Date' to 'Double' requires calling the 'Date.ToOADate' method. For Each x As Double In New Date() {#12:00:00 AM#} ~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30533ERR_DoubleToDateConversion() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="DoubleToDateConversion"> <file name="a.vb"> Structure s1 Function foo() As Date Dim a As Double = 12 Return a End Function End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30533: Conversion from 'Double' to 'Date' requires calling the 'Date.FromOADate' method. Return a ~ </expected>) End Sub <Fact()> Public Sub BC30542ERR_ZeroDivide() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="DateToDoubleConversion"> <file name="a.vb"> Module M1 'Const z = 0 Sub foo() Dim s = 1 \ Nothing Dim m = 1 \ 0 'Dim n = 1 \ z If (1 \ 0 = 1) Then End If End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30542: Division by zero occurred while evaluating this expression. Dim s = 1 \ Nothing ~~~~~~~~~~~ BC30542: Division by zero occurred while evaluating this expression. Dim m = 1 \ 0 ~~~~~ BC30542: Division by zero occurred while evaluating this expression. If (1 \ 0 = 1) Then ~~~~~ </expected>) End Sub <Fact()> Public Sub BC30545ERR_PropertyAccessIgnored() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="PropertyAccessIgnored"> <file name="a.vb"> Class C Shared Property P ReadOnly Property Q Get Return Nothing End Get End Property Property R(o) Get Return Nothing End Get Set(value) End Set End Property Sub M(o) P M(P) C.P C.P = Nothing Q M(Q) Me.Q M(Me.Q) R(Nothing) R(Nothing) = Nothing Me.R(Nothing) M(Me.R(Nothing)) End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30545: Property access must assign to the property or use its value. P ~ BC30545: Property access must assign to the property or use its value. C.P ~~~ BC30545: Property access must assign to the property or use its value. Q ~ BC30545: Property access must assign to the property or use its value. Me.Q ~~~~ BC30545: Property access must assign to the property or use its value. R(Nothing) ~~~~~~~~~~ BC30545: Property access must assign to the property or use its value. Me.R(Nothing) ~~~~~~~~~~~~~ </expected>) End Sub <WorkItem(531311, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531311")> <Fact()> Public Sub BC30545ERR_PropertyAccessIgnored_Latebound() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="PropertyAccessIgnored"> <file name="a.vb"> Structure s1 Dim z As Integer Property foo(ByVal i As Integer) Get Return Nothing End Get Set(ByVal Value) End Set End Property Property foo(ByVal i As Double) Get Return Nothing End Get Set(ByVal Value) End Set End Property Sub goo() Dim o As Object = 1 'COMPILEERROR: BC30545, "foo(o)" foo(o) End Sub End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30545: Property access must assign to the property or use its value. foo(o) ~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30547ERR_InterfaceNoDefault1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Namespace N Interface I End Interface Class C Shared Sub M(x As I) N(x(0)) N(x!P) End Sub Shared Sub N(o As Object) End Sub End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30547: 'I' cannot be indexed because it has no default property. N(x(0)) ~ BC30547: 'I' cannot be indexed because it has no default property. N(x!P) ~ </expected>) End Sub <Fact()> Public Sub BC30554ERR_AmbiguousInUnnamedNamespace1() Dim Lib1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="App1"> <file name="a.vb"> Public Class C1 End Class </file> </compilation>) Dim Lib2 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="App2"> <file name="a.vb"> Public Class C1 End Class </file> </compilation>) Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="APP"> <file name="a.vb"> Imports System Module Module1 Sub Main() Dim obj = New C1() End Sub End Module </file> </compilation>) Dim ref1 = New VisualBasicCompilationReference(Lib1) Dim ref2 = New VisualBasicCompilationReference(Lib2) compilation1 = compilation1.AddReferences(ref1) compilation1 = compilation1.AddReferences(ref2) Dim expectedErrors1 = <errors> BC30554: 'C1' is ambiguous. Dim obj = New C1() ~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC30555ERR_DefaultMemberNotProperty1() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Class C Shared Sub M(a As Array, f As Func(Of Dictionary(Of Object, Object))) Dim o As Object o = Function() Return New Dictionary(Of String, String) End Function!a o = a!b o = f!c o = f()!d End Sub End Class </file> </compilation>) ' For now, lambdas result in BC30491 which differs from Dev10. ' This should change once lambda support is complete. Dim expectedErrors1 = <errors> BC30555: Default member of 'Function &lt;generated method&gt;() As Dictionary(Of String, String)' is not a property. o = Function() ~~~~~~~~~~~ BC30555: Default member of 'Array' is not a property. o = a!b ~ BC30555: Default member of 'Func(Of Dictionary(Of Object, Object))' is not a property. o = f!c ~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC30565ERR_ArrayInitializerTooFewDimensions() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ArrayInitializerTooFewDimensions"> <file name="a.vb"> Module Module1 Sub test() Dim FixedRankArray_1(,) As Double 'COMPILEERROR: BC30565, "(0", BC30198, "," FixedRankArray_1 = New Double(,) {(0.1), {2.4, 4.6}} Exit Sub End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30565: Array initializer has too few dimensions. FixedRankArray_1 = New Double(,) {(0.1), {2.4, 4.6}} ~~~~~ </expected>) End Sub <Fact()> Public Sub BC30566ERR_ArrayInitializerTooManyDimensions() CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ArrayInitializerTooManyDimensions"> <file name="a.vb"> Module Module1 Structure S1 Public x As Long Public s As String End Structure Sub foo() Dim obj = New S1() {{1, "one"}} Exit Sub End Sub End Module </file> </compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_ArrayInitializerTooManyDimensions, "{1, ""one""}")) End Sub ' Roslyn too many extra errors (last 4) <Fact()> Public Sub BC30566ERR_ArrayInitializerTooManyDimensions_1() CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ArrayInitializerTooManyDimensions"> <file name="a.vb"> Module Module1 Sub foo() Dim myArray As Integer(,) = New Integer(2, 1) {{{1, 2}, {3, 4}, {5, 6}}} End Sub End Module </file> </compilation>).VerifyDiagnostics( Diagnostic(ERRID.ERR_ArrayInitializerTooManyDimensions, "{1, 2}"), Diagnostic(ERRID.ERR_ArrayInitializerTooManyDimensions, "{3, 4}"), Diagnostic(ERRID.ERR_ArrayInitializerTooManyDimensions, "{5, 6}"), Diagnostic(ERRID.ERR_InitializerTooManyElements1, "{{1, 2}, {3, 4}, {5, 6}}").WithArguments("1"), Diagnostic(ERRID.ERR_InitializerTooFewElements1, "{{{1, 2}, {3, 4}, {5, 6}}}").WithArguments("2")) End Sub <Fact()> Public Sub BC30567ERR_InitializerTooFewElements1() CreateCompilationWithMscorlib40( <compilation name="InitializerTooFewElements1"> <file name="a.vb"> Class A Sub foo() Dim x = {{1, 2, 3}, {4, 5}} End Sub End Class </file> </compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_InitializerTooFewElements1, "{4, 5}").WithArguments("1")) End Sub <Fact()> Public Sub BC30567ERR_InitializerTooFewElements1_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="InitializerTooFewElements1"> <file name="a.vb"> Class A Sub foo() Dim x127 As Object(,) = New System.Exception(,) {{New System.AccessViolationException, New System.ArgumentException}, {New System.Exception}} End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30567: Array initializer is missing 1 elements. Dim x127 As Object(,) = New System.Exception(,) {{New System.AccessViolationException, New System.ArgumentException}, {New System.Exception}} ~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30567ERR_InitializerTooFewElements1_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C Private A() As Object = New Object(0) {} Private B As Object() = New Object(2) {} Private C As Object(,) = New Object(1, 0) {} Private D As Object(,) = New Object(1, 0) {{}, {2}} Private E As Object(,) = New Object(0, 2) {} Private F()() As Object = New Object(0)() {} Private G()() As Object = New Object(0)() {New Object(0) {}} End Class </file> </compilation>) compilation.AssertTheseDiagnostics( <expected> BC30567: Array initializer is missing 1 elements. Private D As Object(,) = New Object(1, 0) {{}, {2}} ~~ </expected>) End Sub <Fact()> Public Sub BC30568ERR_InitializerTooManyElements1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="InitializerTooManyElements1"> <file name="a.vb"> Class A Sub foo() Dim x127 As Object(,) = New System.Exception(,) {{New System.AccessViolationException}, {New System.Exception, New System.ArgumentException}} End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30568: Array initializer has 1 too many elements. Dim x127 As Object(,) = New System.Exception(,) {{New System.AccessViolationException}, {New System.Exception, New System.ArgumentException}} ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30569ERR_NewOnAbstractClass() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="NewOnAbstractClass"> <file name="a.vb"> Class C1 MustInherit Class C2 Public foo As New C2() End Class Public foo As New C2() End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30569: 'New' cannot be used on a class that is declared 'MustInherit'. Public foo As New C2() ~~~~~~~~ BC30569: 'New' cannot be used on a class that is declared 'MustInherit'. Public foo As New C2() ~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30574ERR_StrictDisallowsLateBinding() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="StrictDisallowsLateBinding"> <file name="a.vb"> Module Module1 Dim bol As Boolean Class C1 Property Prop As Long End Class Sub foo() Dim Obj As Object = New C1() bol = Obj(1) bol = Obj!P End Sub End Module </file> </compilation>, TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.On)) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30574: Option Strict On disallows late binding. bol = Obj(1) ~~~ BC30574: Option Strict On disallows late binding. bol = Obj!P ~~~~~ </expected>) compilation = compilation.WithOptions(compilation.Options.WithOptionStrict(OptionStrict.Custom)) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42017: Late bound resolution; runtime errors could occur. bol = Obj(1) ~~~ BC42016: Implicit conversion from 'Object' to 'Boolean'. bol = Obj(1) ~~~~~~ BC42016: Implicit conversion from 'Object' to 'Boolean'. bol = Obj!P ~~~~~ BC42017: Late bound resolution; runtime errors could occur. bol = Obj!P ~~~~~ </expected>) End Sub <WorkItem(546763, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546763")> <Fact()> Public Sub BC30574ERR_StrictDisallowsLateBinding_16745() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict On Option Infer On Public Module Program Sub Main() Dim a As Object = Nothing a.DoSomething() End Sub End Module </file> </compilation>, TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.On)) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30574: Option Strict On disallows late binding. a.DoSomething() ~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30574ERR_StrictDisallowsLateBinding1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="StrictDisallowsLateBinding"> <file name="a.vb"> Imports System Module Program Delegate Sub d1(ByRef x As Integer, y As Integer) Sub Main() Dim obj As Object = New cls1 Dim o As d1 = AddressOf obj.foo Dim l As Integer = 0 o(l, 2) Console.WriteLine(l) End Sub Class cls1 Shared Sub foo(ByRef x As Integer, y As Integer) x = 42 Console.WriteLine(x + y) End Sub End Class End Module </file> </compilation>, TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.On)) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30574: Option Strict On disallows late binding. Dim o As d1 = AddressOf obj.foo ~~~~~~~ </expected>) compilation = compilation.WithOptions(compilation.Options.WithOptionStrict(OptionStrict.Custom)) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42017: Late bound resolution; runtime errors could occur. Dim o As d1 = AddressOf obj.foo ~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30577ERR_AddressOfOperandNotMethod() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="AddressOfOperandNotMethod"> <file name="a.vb"> Delegate Function MyDelegate() Module M1 Enum MyEnum One End Enum Sub Main() Dim x As MyDelegate Dim oEnum As MyEnum x = AddressOf oEnum x.Invoke() End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30577: 'AddressOf' operand must be the name of a method (without parentheses). x = AddressOf oEnum ~~~~~ </expected>) End Sub <Fact()> Public Sub BC30581ERR_AddressOfNotDelegate1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="AddressOfNotDelegate1"> <file name="a.vb"> Module M Sub Main() Dim x = New Object() Dim f = AddressOf x.GetType End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30581: 'AddressOf' expression cannot be converted to 'Object' because 'Object' is not a delegate type. Dim f = AddressOf x.GetType ~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30582ERR_SyncLockRequiresReferenceType1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="SyncLockRequiresReferenceType1"> <file name="a.vb"> Imports System Module M1 Class C Private Shared count = 0 Sub IncrementCount() Dim i As Integer SyncLock i = 0 count = count + 1 End SyncLock End Sub End Class End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30582: 'SyncLock' operand cannot be of type 'Boolean' because 'Boolean' is not a reference type. SyncLock i = 0 ~~~~~ </expected>) End Sub <Fact()> Public Sub BC30582ERR_SyncLockRequiresReferenceType1_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="SyncLockRequiresReferenceType1"> <file name="a.vb"> Imports System Module Program Sub Main(args As String()) Dim S1_a As New Object() Dim S1_b As Integer? = 4 Dim S1_c As Integer? = 41 SyncLock If(False, S1_a, S1_a) End SyncLock SyncLock If(True, S1_b, S1_b) End SyncLock SyncLock If(False, S1_b, 1) End SyncLock End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30582: 'SyncLock' operand cannot be of type 'Integer?' because 'Integer?' is not a reference type. SyncLock If(True, S1_b, S1_b) ~~~~~~~~~~~~~~~~~~~~ BC30582: 'SyncLock' operand cannot be of type 'Integer?' because 'Integer?' is not a reference type. SyncLock If(False, S1_b, 1) ~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30582ERR_SyncLockRequiresReferenceType1_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="SyncLockRequiresReferenceType1"> <file name="a.vb"> Interface I End Interface Class A End Class Class C Shared Sub M(Of T1, T2 As Class, T3 As Structure, T4 As New, T5 As I, T6 As A, T7 As U, U)(_1 As T1, _2 As T2, _3 As T3, _4 As T4, _5 As T5, _6 As T6, _7 As T7) SyncLock _1 End SyncLock SyncLock _2 End SyncLock SyncLock _3 End SyncLock SyncLock _4 End SyncLock SyncLock _5 End SyncLock SyncLock _6 End SyncLock SyncLock _7 End SyncLock End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30582: 'SyncLock' operand cannot be of type 'T1' because 'T1' is not a reference type. SyncLock _1 ~~ BC30582: 'SyncLock' operand cannot be of type 'T3' because 'T3' is not a reference type. SyncLock _3 ~~ BC30582: 'SyncLock' operand cannot be of type 'T4' because 'T4' is not a reference type. SyncLock _4 ~~ BC30582: 'SyncLock' operand cannot be of type 'T5' because 'T5' is not a reference type. SyncLock _5 ~~ BC30582: 'SyncLock' operand cannot be of type 'T7' because 'T7' is not a reference type. SyncLock _7 ~~ </expected>) End Sub <Fact> Public Sub BC30587ERR_NamedParamArrayArgument() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="NamedParamArrayArgument"> <file name="a.vb"> Class C1 Shared Sub Main() Dim a As New C1 a.abc(s:=10) End Sub Sub abc(ByVal ParamArray s() As Integer) End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30587: Named argument cannot match a ParamArray parameter. a.abc(s:=10) ~ </expected>) End Sub <Fact()> Public Sub BC30588ERR_OmittedParamArrayArgument() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="OmittedParamArrayArgument"> <file name="a.vb"> Imports System Imports C1(Of String, Integer) Class C1(Of T As {Class}, U As Structure) Public Shared Property Overloaded(ByVal ParamArray y() As Exception) As C2 Get Return New C2 End Get Set(ByVal value As C2) End Set End Property End Class Class C2 End Class Module M1 Sub FOO() Overloaded(, , ) = Nothing End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30588: Omitted argument cannot match a ParamArray parameter. Overloaded(, , ) = Nothing ~ BC30588: Omitted argument cannot match a ParamArray parameter. Overloaded(, , ) = Nothing ~ BC30588: Omitted argument cannot match a ParamArray parameter. Overloaded(, , ) = Nothing ~ </expected>) End Sub <Fact()> Public Sub BC30611ERR_NegativeArraySize() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="NegativeArraySize"> <file name="a.vb"> Class C1 Sub foo() Dim x8(-2) As String End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30611: Array dimensions cannot have a negative size. Dim x8(-2) As String ~~ </expected>) End Sub <Fact()> Public Sub BC30611ERR_NegativeArraySize_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="NegativeArraySize"> <file name="a.vb"> Class C1 Sub foo() Dim arr11 As Integer(,) = New Integer(-2, -2) {} ' Invalid End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30611: Array dimensions cannot have a negative size. Dim arr11 As Integer(,) = New Integer(-2, -2) {} ' Invalid ~~ BC30611: Array dimensions cannot have a negative size. Dim arr11 As Integer(,) = New Integer(-2, -2) {} ' Invalid ~~ </expected>) End Sub <Fact()> Public Sub BC30611ERR_NegativeArraySize_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="NegativeArraySize"> <file name="a.vb"> Class C1 Sub foo() Dim arr(0 To 0, 0 To -2) As Integer 'Invalid End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30611: Array dimensions cannot have a negative size. Dim arr(0 To 0, 0 To -2) As Integer 'Invalid ~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30614ERR_MyClassAbstractCall1_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BC30614ERR_MyClassAbstractCall1_1"> <file name="a.vb"> MustInherit Class C1 Public Sub UseMyClass() MyClass.foo() End Sub MustOverride Sub foo() End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30614: 'MustOverride' method 'Public MustOverride Sub foo()' cannot be called with 'MyClass'. MyClass.foo() ~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30614ERR_MyClassAbstractCall1_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BC30614ERR_MyClassAbstractCall1_2"> <file name="a.vb"> Public MustInherit Class Base1 Public MustOverride Property P1() Public Sub M2() MyClass.P1 = MyClass.P1 End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30614: 'MustOverride' method 'Public MustOverride Property P1 As Object' cannot be called with 'MyClass'. MyClass.P1 = MyClass.P1 ~~~~~~~~~~ BC30614: 'MustOverride' method 'Public MustOverride Property P1 As Object' cannot be called with 'MyClass'. MyClass.P1 = MyClass.P1 ~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30614ERR_MyClassAbstractCall1_3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BC30614ERR_MyClassAbstractCall1_3"> <file name="a.vb"> Imports System Public MustInherit Class Base1 Public MustOverride Function F1() As Integer Public Sub M2() Dim _func As Func(Of Integer) = AddressOf MyClass.F1 End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30614: 'MustOverride' method 'Public MustOverride Function F1() As Integer' cannot be called with 'MyClass'. Dim _func As Func(Of Integer) = AddressOf MyClass.F1 ~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30614ERR_MyClassAbstractCall1_4() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BC30614ERR_MyClassAbstractCall1_4"> <file name="a.vb"> Imports System Public MustInherit Class Base1 Public MustOverride Function F1() As Integer Public Function F2() As Integer Return 1 End Function Public Sub M2() Dim _func As Func(Of Func(Of Integer)) = Function() New Func(Of Integer)(AddressOf MyClass.F1) Dim _func2 As Func(Of Func(Of Integer)) = Function() New Func(Of Integer)(AddressOf MyClass.F2) End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30614: 'MustOverride' method 'Public MustOverride Function F1() As Integer' cannot be called with 'MyClass'. Dim _func As Func(Of Func(Of Integer)) = Function() New Func(Of Integer)(AddressOf MyClass.F1) ~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30614ERR_MyClassAbstractCall1_5() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BC30614ERR_MyClassAbstractCall1_5"> <file name="a.vb"> Imports System Public MustInherit Class Base1 Public MustOverride Function F1() As Integer Public Function F2() As Integer Return 1 End Function Public FLD As Func(Of Func(Of Integer)) = Function() New Func(Of Integer)(AddressOf MyClass.F1) Public Property PROP As Func(Of Func(Of Integer)) = Function() New Func(Of Integer)(AddressOf MyClass.F1) Public FLD2 As Func(Of Func(Of Integer)) = Function() New Func(Of Integer)(AddressOf MyClass.F2) Public Property PROP2 As Func(Of Func(Of Integer)) = Function() New Func(Of Integer)(AddressOf MyClass.F2) End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30614: 'MustOverride' method 'Public MustOverride Function F1() As Integer' cannot be called with 'MyClass'. Function() New Func(Of Integer)(AddressOf MyClass.F1) ~~~~~~~~~~ BC30614: 'MustOverride' method 'Public MustOverride Function F1() As Integer' cannot be called with 'MyClass'. Function() New Func(Of Integer)(AddressOf MyClass.F1) ~~~~~~~~~~ </expected>) End Sub ' Different error <Fact()> Public Sub BC30615ERR_EndDisallowedInDllProjects() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="EndDisallowedInDllProjects"> <file name="a.vb"> Class C1 Function foo() End End Class </file> </compilation>, options:=TestOptions.ReleaseDll) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30027: 'End Function' expected. Function foo() ~~~~~~~~~~~~~~ BC30615: 'End' statement cannot be used in class library projects. End ~~~ </expected>) End Sub <Fact()> Public Sub BC30616ERR_BlockLocalShadowing1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="BlockLocalShadowing1"> <file name="a.vb"> Class C1 Sub foo() dim s = 10 if s>5 dim s = 5 if s > 7 dim s = 7 End If End If End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30616: Variable 's' hides a variable in an enclosing block. dim s = 5 ~ BC30616: Variable 's' hides a variable in an enclosing block. dim s = 7 ~ </expected>) End Sub ' spec changes in Roslyn <WorkItem(528680, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528680")> <Fact()> Public Sub BC30616ERR_BlockLocalShadowing1_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="BlockLocalShadowing1"> <file name="a.vb"> Class C Private field As Integer = 0 Private Property [property]() As Integer Get Return m_property End Get Set(value As Integer) m_property = value End Set End Property Property prop() As Integer Get Return 1 End Get Set(ByVal Value As Integer) ' Was Dev10: COMPILEERROR: BC30616, "value" ' now Dev10: BC30734: 'value' is already declared as a parameter of this method. For Each value As Byte In New Byte() {1, 2, 3} Next End Set End Property Private m_property As Integer Shared Sub Main() Dim ints As Integer() = New Integer() {1, 2, 3} Dim strings As String() = New String() {"1", "2", "3"} Dim conflict As Integer = 1 For Each field As Integer In ints Next For Each [property] As String In strings Next For Each conflict As String In strings Next Dim [qq] As Integer = 23 'COMPILEERROR: BC30616, "qq" For Each qq As Integer In New Integer() {1, 2, 3} Next Dim ww As Integer = 23 'COMPILEERROR: BC30616, "[ww]" For Each [ww] As Integer In New Integer() {1, 2, 3} Next For Each z As Integer In New Integer() {1, 2, 3} 'COMPILEERROR: BC30616, "z" For Each z As Decimal In New Decimal() {1, 2, 3} Next Next For Each t As Long In New Long() {1, 2, 3} For Each u As Boolean In New Boolean() {False, True} 'COMPILEERROR: BC30616, "t" Dim t As Integer Next Next End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30734: 'value' is already declared as a parameter of this method. For Each value As Byte In New Byte() {1, 2, 3} ~~~~~ BC30616: Variable 'conflict' hides a variable in an enclosing block. For Each conflict As String In strings ~~~~~~~~ BC30616: Variable 'qq' hides a variable in an enclosing block. For Each qq As Integer In New Integer() {1, 2, 3} ~~ BC30616: Variable 'ww' hides a variable in an enclosing block. For Each [ww] As Integer In New Integer() {1, 2, 3} ~~~~ BC30616: Variable 'z' hides a variable in an enclosing block. For Each z As Decimal In New Decimal() {1, 2, 3} ~ BC30616: Variable 't' hides a variable in an enclosing block. Dim t As Integer ~ BC42024: Unused local variable: 't'. Dim t As Integer ~ </expected>) End Sub <Fact()> Public Sub BC30616ERR_BlockLocalShadowing1_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="BlockLocalShadowing1"> <file name="a.vb"> Option Strict Off Option Infer On Public Class MyClass1 Public Shared Sub Main() Dim var1 As Integer For var1 As Integer = 1 To 10 Next End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42024: Unused local variable: 'var1'. Dim var1 As Integer ~~~~ BC30616: Variable 'var1' hides a variable in an enclosing block. For var1 As Integer = 1 To 10 ~~~~ </expected>) End Sub <Fact()> Public Sub BC30616ERR_BlockLocalShadowing1_4() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="BlockLocalShadowing1"> <file name="a.vb"> Public Class MyClass1 Public Shared Sub Main() Static var2 As Long For var2 As Short = 0 To 10 Next var2 = 0 End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30616: Variable 'var2' hides a variable in an enclosing block. For var2 As Short = 0 To 10 ~~~~ </expected>) End Sub <Fact()> Public Sub BC30616ERR_BlockLocalShadowing1_5() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="BlockLocalShadowing1"> <file name="a.vb"> Public Class MyClass1 Public Shared Sub Main() For varo As Integer = 0 To 10 For varo As Integer = 0 To 10 Next Next End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30616: Variable 'varo' hides a variable in an enclosing block. For varo As Integer = 0 To 10 ~~~~ </expected>) End Sub <Fact()> Public Sub BC30616ERR_BlockLocalShadowing1_6() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="BlockLocalShadowing1"> <file name="a.vb"> Public Class MyClass1 Public Shared Sub Main() For varo As Integer = 0 To 10 Dim [qqq] As Integer For qqq As Integer = 0 To 10 Next Dim www As Integer For [www] As Integer = 0 To 10 Next Next End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42024: Unused local variable: 'qqq'. Dim [qqq] As Integer ~~~~~ BC30616: Variable 'qqq' hides a variable in an enclosing block. For qqq As Integer = 0 To 10 ~~~ BC42024: Unused local variable: 'www'. Dim www As Integer ~~~ BC30616: Variable 'www' hides a variable in an enclosing block. For [www] As Integer = 0 To 10 ~~~~~ </expected>) End Sub <Fact()> Public Sub BC30616ERR_BlockLocalShadowing1_7() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="BlockLocalShadowing1"> <file name="a.vb"> Public Class MyClass1 Public Shared Sub Main() For x As Integer = 0 To 10 Dim x As Integer Next End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30616: Variable 'x' hides a variable in an enclosing block. Dim x As Integer ~ BC42024: Unused local variable: 'x'. Dim x As Integer ~ </expected>) End Sub <Fact()> Public Sub BC30616ERR_BlockLocalShadowing1_8() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="BlockLocalShadowing1"> <file name="a.vb"> Public Class MyClass1 Public Shared Sub Main() For var1 As Integer = 0 To 10 For var2 As Integer = 0 To 10 Dim var1 As Integer Next Next End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30616: Variable 'var1' hides a variable in an enclosing block. Dim var1 As Integer ~~~~ BC42024: Unused local variable: 'var1'. Dim var1 As Integer ~~~~ </expected>) End Sub <Fact()> Public Sub BC30616ERR_BlockLocalShadowing1_9() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="DuplicateLocals1"> <file name="a.vb"> Class C Shared Sub Main() For Each r As Integer In New Integer() {1, 2, 3} 'Was COMPILEERROR: BC30288, "r" in Dev10 'Now BC30616 Dim r As Integer Next End Sub End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC30616: Variable 'r' hides a variable in an enclosing block. Dim r As Integer ~ BC42024: Unused local variable: 'r'. Dim r As Integer ~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC30647ERR_ReturnFromNonFunction() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="ReturnFromNonFunction"> <file name="a.vb"> Structure S1 shared sub foo() return 1 end sub End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30647: 'Return' statement in a Sub or a Set cannot return a value. return 1 ~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30654ERR_ReturnWithoutValue() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="ReturnWithoutValue"> <file name="a.vb"> Structure S1 shared Function foo return end Function End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30654: 'Return' statement in a Function, Get, or Operator must return a value. return ~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30657ERR_UnsupportedMethod1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="UnsupportedMethod1"> <file name="a.vb"> Class C1 Dim x As System.Threading.IOCompletionCallback Sub Sub1() End Sub Sub New() x = New System.Threading.IOCompletionCallback(AddressOf Sub1) End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30657: 'IOCompletionCallback' has a return type that is not supported or parameter types that are not supported. x = New System.Threading.IOCompletionCallback(AddressOf Sub1) ~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30658ERR_NoNonIndexProperty1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="NoNonIndexProperty1"> <file name="a.vb"> Option Explicit On Imports System Module M1 Class MyAttr Inherits Attribute Public Property Prop(ByVal i As Integer) As Integer Get Return Nothing End Get Set(ByVal Value As Integer) End Set End Property End Class &lt;MyAttr(Prop:=1)&gt;'BIND:"Prop" Class C1 End Class End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30658: Property 'Prop' with no parameters cannot be found. &lt;MyAttr(Prop:=1)&gt;'BIND:"Prop" ~~~~ </expected>) VerifyOperationTreeForTest(Of IdentifierNameSyntax)(compilation, "a.vb", <![CDATA[ IPropertyReferenceOperation: Property M1.MyAttr.Prop(i As System.Int32) As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsInvalid) (Syntax: 'Prop') Instance Receiver: null]]>.Value) End Sub <Fact()> Public Sub BC30659ERR_BadAttributePropertyType1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BadAttributePropertyType1"> <file name="a.vb"><![CDATA[ Imports System <AttributeUsage(AttributeTargets.Class, AllowMultiple:=True, Inherited:=True)> Class MultiUseAttribute Inherits System.Attribute Public Sub New(ByVal Value As Integer) End Sub End Class <AttributeUsage(AttributeTargets.Class, Inherited:=True)> Class SingleUseAttribute Inherits Attribute Property A() As Date Get Return Nothing End Get Set(value As Date) End Set End Property Public Sub New(ByVal Value As Integer) End Sub End Class <SingleUse(1, A:=1.1), MultiUse(1)> Class Base End Class <SingleUse(0, A:=1.1), MultiUse(0)> Class Derived Inherits Base End Class ]]></file> </compilation>).VerifyDiagnostics( Diagnostic(ERRID.ERR_BadAttributePropertyType1, "A").WithArguments("A"), Diagnostic(ERRID.ERR_DoubleToDateConversion, "1.1"), Diagnostic(ERRID.ERR_BadAttributePropertyType1, "A").WithArguments("A"), Diagnostic(ERRID.ERR_DoubleToDateConversion, "1.1")) ' BC30533: Dev10 NOT report End Sub <Fact()> Public Sub BC30661ERR_PropertyOrFieldNotDefined1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="PropertyOrFieldNotDefined1"> <file name="a.vb"><![CDATA[ Imports System <AttributeUsage(AttributeTargets.All)> Public Class GeneralAttribute Inherits Attribute End Class <General(NotExist:=10)> Class C1 End Class ]]></file> </compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_PropertyOrFieldNotDefined1, "NotExist").WithArguments("NotExist")) End Sub <Fact()> Public Sub BC30665ERR_CantThrowNonException() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module M1 Sub Foo() Throw (Nothing) End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30665: 'Throw' operand must derive from 'System.Exception'. Throw (Nothing) ~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30665ERR_CantThrowNonException_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Class A End Class Class C Shared Sub M1(Of T As System.Exception)(e As T) Throw e End Sub Shared Sub M2(Of T As {System.Exception, New})() Throw New T() End Sub Shared Sub M3(Of T As A)(a As T) Throw a End Sub Shared Sub M4(Of U As New)() Throw New U() End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30665: 'Throw' operand must derive from 'System.Exception'. Throw a ~~~~~~~ BC30665: 'Throw' operand must derive from 'System.Exception'. Throw New U() ~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30666ERR_MustBeInCatchToRethrow() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="MustBeInCatchToRethrow"> <file name="a.vb"> Imports System Class C1 Sub foo() Try Throw Catch ex As Exception End Try End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30666: 'Throw' statement cannot omit operand outside a 'Catch' statement or inside a 'Finally' statement. Throw ~~~~~ </expected>) End Sub <Fact()> Public Sub BC30671ERR_InitWithMultipleDeclarators() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="InitWithMultipleDeclarators"> <file name="a.vb"> Imports System Public Structure Class1 implements IDisposable Public Sub Dispose() implements Idisposable.Dispose End Sub End Structure Public Class Class2 Sub foo() Dim a, b As Class1 = New Class1 a = nothing b = nothing Using c, d as Class1 = nothing End Using End Sub End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC30671: Explicit initialization is not permitted with multiple variables declared with a single type specifier. Dim a, b As Class1 = New Class1 ~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36011: 'Using' resource variable must have an explicit initialization. Using c, d as Class1 = nothing ~ BC30671: Explicit initialization is not permitted with multiple variables declared with a single type specifier. Using c, d as Class1 = nothing ~~~~~~~~~~~~~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC30671ERR_InitWithMultipleDeclarators02() Dim source = <compilation> <file name="a.vb"> Option strict on imports system Class C1 ' not so ok public i, j as integer = 23 ' ok enough :) public k as integer,l as integer = 23 Public shared Sub Main(args() as string) End sub End Class </file> </compilation> Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) CompilationUtils.AssertTheseDiagnostics(c1, <expected> BC30671: Explicit initialization is not permitted with multiple variables declared with a single type specifier. public i, j as integer = 23 ~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30672ERR_InitWithExplicitArraySizes() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="InitWithExplicitArraySizes"> <file name="a.vb"> Structure myStruct1 sub foo() Dim a6(,) As Integer Dim b6(5, 5) As Integer = a6 end Sub End structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30672: Explicit initialization is not permitted for arrays declared with explicit bounds. Dim b6(5, 5) As Integer = a6 ~~~~~~~~ BC42104: Variable 'a6' is used before it has been assigned a value. A null reference exception could result at runtime. Dim b6(5, 5) As Integer = a6 ~~ </expected>) End Sub <WorkItem(542258, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542258")> <Fact()> Public Sub BC30672ERR_InitWithExplicitArraySizes_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="InitWithExplicitArraySizes"> <file name="a.vb"> Class Cls1 Public Arr(3) As Cls1 = New Cls1() {New Cls1} Sub foo Dim Arr(3) As Cls1 = New Cls1() {New Cls1} End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30672: Explicit initialization is not permitted for arrays declared with explicit bounds. Public Arr(3) As Cls1 = New Cls1() {New Cls1} ~~~~~~ BC30672: Explicit initialization is not permitted for arrays declared with explicit bounds. Dim Arr(3) As Cls1 = New Cls1() {New Cls1} ~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30672ERR_InitWithExplicitArraySizes_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="InitWithExplicitArraySizes"> <file name="a.vb"> Option Infer On Imports System Module Module1 Sub Main() Dim arr14(1, 2) = New Double(1, 2) {} ' Invalid End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30672: Explicit initialization is not permitted for arrays declared with explicit bounds. Dim arr14(1, 2) = New Double(1, 2) {} ' Invalid ~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30676ERR_NameNotEvent2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="NameNotEvent2"> <file name="a.vb"> Option Strict Off Module M Sub Foo() Dim x As C1 = New C1 AddHandler x.E, Sub() Console.WriteLine() End Sub End Module Class C1 Public Dim E As String End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30676: 'E' is not an event of 'C1'. AddHandler x.E, Sub() Console.WriteLine() ~ </expected>) End Sub <Fact()> Public Sub BC30677ERR_AddOrRemoveHandlerEvent() CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="AddOrRemoveHandlerEvent"> <file name="a.vb"> Module M Sub Main() AddHandler Nothing, Nothing End Sub End Module </file> </compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_AddOrRemoveHandlerEvent, "Nothing")) End Sub <Fact(), WorkItem(918579, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/918579"), WorkItem(34, "CodePlex")> Public Sub BC30685ERR_AmbiguousAcrossInterfaces3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="AmbiguousAcrossInterfaces3"> <file name="a.vb"> Interface A Sub fun(ByVal i As Integer) End Interface Interface AB Inherits A Shadows Sub fun(ByVal i As Integer) End Interface Interface AC Inherits A Shadows Sub fun(ByVal i As Integer) End Interface Interface ABS Inherits AB, AC End Interface Class Test Sub D(ByVal d As ABS) d.fun(2) End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30521: Overload resolution failed because no accessible 'fun' is most specific for these arguments: 'Sub AB.fun(i As Integer)': Not most specific. 'Sub AC.fun(i As Integer)': Not most specific. d.fun(2) ~~~ </expected>) End Sub <Fact()> Public Sub BC30686ERR_DefaultPropertyAmbiguousAcrossInterfaces4() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="DefaultPropertyAmbiguousAcrossInterfaces4"> <file name="a.vb"> Option Strict On Interface IA(Of T) Default ReadOnly Property P(o As T) As Object End Interface Interface IB1(Of T) Inherits IA(Of T) End Interface Interface IB2(Of T) Inherits IA(Of T) Default Overloads ReadOnly Property P(x As T, y As T) As Object End Interface Interface IB3(Of T) Inherits IA(Of T) Default Overloads ReadOnly Property Q(x As Integer, y As Integer, z As Integer) As Object End Interface Interface IC1 Inherits IA(Of String), IB1(Of String) End Interface Interface IC2 Inherits IA(Of String), IB1(Of Object) End Interface Interface IC3 Inherits IA(Of String), IB2(Of String) End Interface Interface IC4 Inherits IA(Of String), IB3(Of String) End Interface Module M Sub M(c1 As IC1, c2 As IC2, c3 As IC3, c4 As IC4) Dim value As Object value = c1("") value = c2("") value = c3("") value = c4("") End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC40007: Default property 'Q' conflicts with the default property 'P' in the base interface 'IA'. 'Q' will be the default property. 'Q' should be declared 'Shadows'. Default Overloads ReadOnly Property Q(x As Integer, y As Integer, z As Integer) As Object ~ BC30686: Default property access is ambiguous between the inherited interface members 'ReadOnly Default Property P(o As String) As Object' of interface 'IA(Of String)' and 'ReadOnly Default Property P(o As Object) As Object' of interface 'IA(Of Object)'. value = c2("") ~~ BC30686: Default property access is ambiguous between the inherited interface members 'ReadOnly Default Property P(o As String) As Object' of interface 'IA(Of String)' and 'ReadOnly Default Property P(x As String, y As String) As Object' of interface 'IB2(Of String)'. value = c3("") ~~ BC30686: Default property access is ambiguous between the inherited interface members 'ReadOnly Default Property P(o As String) As Object' of interface 'IA(Of String)' and 'ReadOnly Default Property Q(x As Integer, y As Integer, z As Integer) As Object' of interface 'IB3(Of String)'. value = c4("") ~~ </expected>) End Sub <Fact()> Public Sub BC30690ERR_StructureNoDefault1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Namespace N Structure S End Structure End Namespace Namespace M Class C Shared Sub M(x As N.S) N(x(0)) N(x!P) End Sub Shared Sub N(o As Object) End Sub End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30690: Structure 'S' cannot be indexed because it has no default property. N(x(0)) ~ BC30690: Structure 'S' cannot be indexed because it has no default property. N(x!P) ~ </expected>) End Sub <Fact()> Public Sub BC30734ERR_LocalNamedSameAsParam1() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="LocalNamedSameAsParam1"> <file name="a.vb"> Class cls0(Of G) Sub foo(Of T) (ByVal x As T) Dim x As T End Sub End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC30734: 'x' is already declared as a parameter of this method. Dim x As T ~ BC42024: Unused local variable: 'x'. Dim x As T ~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC30734ERR_LocalNamedSameAsParam1_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="BC30734ERR_LocalNamedSameAsParam1_2"> <file name="a.vb"> Class C Private field As Integer = 0 Private Property [property]() As Integer Get Return m_property End Get Set(value As Integer) m_property = value End Set End Property Property prop() As Integer Get Return 1 End Get Set(ByVal Value As Integer) ' Was Dev10: COMPILEERROR: BC30616, "value" ' Now: BC30734 For Each value As Byte In New Byte() {1, 2, 3} Next End Set End Property Private m_property As Integer Shared Sub Main() End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30734: 'value' is already declared as a parameter of this method. For Each value As Byte In New Byte() {1, 2, 3} ~~~~~ </expected>) End Sub <WorkItem(528680, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528680")> <Fact()> Public Sub BC30734ERR_LocalNamedSameAsParam1_3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="BlockLocalShadowing1"> <file name="a.vb"> Public Class MyClass1 Public Shared Sub Main() End Sub Sub foo(ByVal p1 As Integer) For p1 As Integer = 1 To 10 Next End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30734: 'p1' is already declared as a parameter of this method. For p1 As Integer = 1 To 10 ~~ </expected>) End Sub <Fact()> Public Sub BC30742ERR_CannotConvertValue2() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports microsoft.visualbasic.strings Module M1 Sub foo() Dim i As Integer Dim c As Char I% = Asc("") i% = Asc("" + "" + "" + "" + "" + "" + "" + "" + "") c = ChrW(65536) c = ChrW(-68888) End Sub End module </file> </compilation>) Dim expectedErrors1 = <errors> BC30742: Value '' cannot be converted to 'Integer'. I% = Asc("") ~~~~~~~ BC30742: Value '' cannot be converted to 'Integer'. i% = Asc("" + "" + "" + "" + "" + "" + "" + "" + "") ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30742: Value '65536' cannot be converted to 'Char'. c = ChrW(65536) ~~~~~~~~~~~ BC30742: Value '-68888' cannot be converted to 'Char'. c = ChrW(-68888) ~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC30742ERR_CannotConvertValue2_2() Dim source = <compilation> <file name="a.vb"> Option strict on imports system imports microsoft.visualbasic.strings Imports System.Text Class C1 private const f1 as integer = Asc("") ' empty string private const f2 as integer = AscW("") ' empty string private const f3 as integer = Asc(CStr(nothing)) ' nothing string private const f4 as integer = AscW(CStr(nothing)) ' nothing string private const f5 as Char = ChrW(65536) Public shared Sub Main(args() as string) End sub End Class </file> </compilation> Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) AssertTheseDiagnostics(c1, <expected> BC30742: Value '' cannot be converted to 'Integer'. private const f1 as integer = Asc("") ' empty string ~~~~~~~ BC30742: Value '' cannot be converted to 'Integer'. private const f2 as integer = AscW("") ' empty string ~~~~~~~~ BC30742: Value '' cannot be converted to 'Integer'. private const f3 as integer = Asc(CStr(nothing)) ' nothing string ~~~~~~~~~~~~~~~~~~ BC30742: Value '' cannot be converted to 'Integer'. private const f4 as integer = AscW(CStr(nothing)) ' nothing string ~~~~~~~~~~~~~~~~~~~ BC30742: Value '65536' cannot be converted to 'Char'. private const f5 as Char = ChrW(65536) ~~~~~~~~~~~ </expected>) End Sub <WorkItem(574290, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/574290")> <Fact()> Public Sub BC30742ERR_PassVBNullToAsc() Dim source = <compilation name="ExpressionContext"> <file name="a.vb"> Imports Microsoft.VisualBasic Module Module1 Sub Main Asc(vbnullstring) End Sub End MOdule </file> </compilation> CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_CannotConvertValue2, "Asc(vbnullstring)").WithArguments("", "Integer")) End Sub <Fact()> Public Sub BC30752ERR_OnErrorInSyncLock() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="OnErrorInSyncLock"> <file name="a.vb"> Imports System Class C Sub IncrementCount() SyncLock GetType(C) On Error GoTo 0 End SyncLock End Sub End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC30752: 'On Error' statements are not valid within 'SyncLock' statements. On Error GoTo 0 ~~~~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC30753ERR_NarrowingConversionCollection2() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="NarrowingConversionCollection2"> <file name="a.vb"> option strict on Imports System class C1 Function Main() As Microsoft.VisualBasic.Collection 'Dim collection As Microsoft.VisualBasic. = Nothing Dim _collection As _Collection = Nothing return _collection End function End Class Interface _Collection End Interface </file> </compilation>) Dim expectedErrors1 = <errors> BC30753: Option Strict On disallows implicit conversions from '_Collection' to 'Collection'; the Visual Basic 6.0 collection type is not compatible with the .NET Framework collection type. return _collection ~~~~~~~~~~~ BC42322: Runtime errors might occur when converting '_Collection' to 'Collection'. return _collection ~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC30754ERR_GotoIntoTryHandler() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GotoIntoTryHandler"> <file name="a.vb"> Imports System Class C1 Sub Main() Do While (True) GoTo LB1 Loop Try Catch ex As Exception Finally LB1: End Try End Sub End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC30754: 'GoTo LB1' is not valid because 'LB1' is inside a 'Try', 'Catch' or 'Finally' statement that does not contain this statement. GoTo LB1 ~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <WorkItem(543055, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543055")> <Fact()> Public Sub BC30754ERR_GotoIntoTryHandler_2() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GotoIntoTryHandler"> <file name="a.vb"> Imports System Module Program Sub Main(args As String()) Try GoTo label GoTo label5 Catch ex As Exception label: Finally label5: End Try End Sub End Module </file> </compilation>) Dim expectedErrors1 = <errors> BC30754: 'GoTo label' is not valid because 'label' is inside a 'Try', 'Catch' or 'Finally' statement that does not contain this statement. GoTo label ~~~~~ BC30754: 'GoTo label5' is not valid because 'label5' is inside a 'Try', 'Catch' or 'Finally' statement that does not contain this statement. GoTo label5 ~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC30755ERR_GotoIntoSyncLock() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GotoIntoSyncLock"> <file name="a.vb"> Imports System Class C Sub IncrementCount() SyncLock GetType(C) label: End SyncLock GoTo label End Sub End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC30755: 'GoTo label' is not valid because 'label' is inside a 'SyncLock' statement that does not contain this statement. GoTo label ~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC30756ERR_GotoIntoWith() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GotoIntoWith"> <file name="a.vb"> Class C1 Sub Main() Dim s = New Type1() With s .x = 1 GoTo lab1 End With With s lab1: .x = 1 End With End Sub End Class Class Type1 Public x As Short End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC30756: 'GoTo lab1' is not valid because 'lab1' is inside a 'With' statement that does not contain this statement. GoTo lab1 ~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC30756ERR_GotoIntoWith_1() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GotoIntoWith"> <file name="a.vb"> Class C1 Function Main() Dim s = New Type1() With s lab1: .x = 1 End With GoTo lab1 End Function End Class Class Type1 Public x As Short End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC30756: 'GoTo lab1' is not valid because 'lab1' is inside a 'With' statement that does not contain this statement. GoTo lab1 ~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC30757ERR_GotoIntoFor() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GotoIntoFor"> <file name="a.vb"> Class C1 Sub Main() Dim s = New Type1() With s .x = 1 GoTo label1 End With For i = 0 To 5 GoTo label1 label1: Continue For Next End Sub End Class Class Type1 Public x As Short End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC30757: 'GoTo label1' is not valid because 'label1' is inside a 'For' or 'For Each' statement that does not contain this statement. GoTo label1 ~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC30757ERR_GotoIntoFor_1() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GotoIntoFor"> <file name="a.vb"> Class C1 Function Main() if (true) GoTo label1 End If For i as Integer = 0 To 5 GoTo label1 label1: Continue For Next return 1 End Function End Class Class Type1 Public x As Short End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC30757: 'GoTo label1' is not valid because 'label1' is inside a 'For' or 'For Each' statement that does not contain this statement. GoTo label1 ~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC30757ERR_GotoIntoFor_2() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GotoIntoFor"> <file name="a.vb"> Option Infer On Option Strict Off Class C1 Function Main() Dim s As Type1 = New Type1() If (True) GoTo label1 End If For Each i In s GoTo label1 label1: Continue For Next Return 1 End Function End Class Class Type1 Public x As Short End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC30757: 'GoTo label1' is not valid because 'label1' is inside a 'For' or 'For Each' statement that does not contain this statement. GoTo label1 ~~~~~~ BC32023: Expression is of type 'Type1', which is not a collection type. For Each i In s ~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <WorkItem(540627, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540627")> <Fact()> Public Sub BC30758ERR_BadAttributeNonPublicConstructor() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BadAttributeNonPublicConstructor"> <file name="at30758.vb"><![CDATA[ Imports System <AttributeUsage(AttributeTargets.All)> Public MustInherit Class MyAttribute Inherits Attribute Friend Sub New() End Sub End Class <My()> Class Foo End Class ]]></file> </compilation>).VerifyDiagnostics( Diagnostic(ERRID.ERR_AttributeCannotBeAbstract, "My").WithArguments("MyAttribute"), Diagnostic(ERRID.ERR_BadAttributeNonPublicConstructor, "My")) End Sub <Fact()> Public Sub BC30782ERR_ContinueDoNotWithinDo() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ContinueDoNotWithinDo"> <file name="a.vb"> Class C1 Sub Main() While True Continue Do End While End Sub End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC30782: 'Continue Do' can only appear inside a 'Do' statement. Continue Do ~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC30783ERR_ContinueForNotWithinFor() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ContinueForNotWithinFor"> <file name="a.vb"> Class C1 Sub Main() Continue for End Sub End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC30783: 'Continue For' can only appear inside a 'For' statement. Continue for ~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC30784ERR_ContinueWhileNotWithinWhile() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ContinueWhileNotWithinWhile"> <file name="a.vb"> Class C1 Sub Main() Continue while End Sub End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC30784: 'Continue While' can only appear inside a 'While' statement. Continue while ~~~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC30793ERR_TryCastOfUnconstrainedTypeParam1() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="TryCastOfUnconstrainedTypeParam1"> <file name="a.vb"> Module M1 Sub Foo(Of T) (ByVal x As T) Dim o As Object = TryCast(x, T) End Sub End Module </file> </compilation>) Dim expectedErrors1 = <errors> BC30793: 'TryCast' operands must be class-constrained type parameter, but 'T' has no class constraint. Dim o As Object = TryCast(x, T) ~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC30794ERR_AmbiguousDelegateBinding2() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="AmbiguousDelegateBinding2"> <file name="a.vb"> Module Module1 Public Delegate Sub Bar(ByVal x As Integer, ByVal y As Integer) Public Sub Foo(Of T, R)(ByVal x As T, ByVal y As R) End Sub Public Sub Foo(Of T)(ByVal x As T, ByVal y As T) End Sub End Module Class C1 Sub FOO() Dim x1 As Module1.Bar = AddressOf Module1.Foo End Sub End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC30794: No accessible 'Foo' is most specific: Public Sub Foo(Of Integer, Integer)(x As Integer, y As Integer) Public Sub Foo(Of Integer)(x As Integer, y As Integer) Dim x1 As Module1.Bar = AddressOf Module1.Foo ~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact> Public Sub BC30917ERR_NoNonObsoleteConstructorOnBase3() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="NoNonObsoleteConstructorOnBase3"> <file name="a.vb"> Imports System Class C1 &lt;Obsolete(Nothing, True)&gt; Sub New() End Sub End Class Class C2 Inherits C1 End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC30917: Class 'C2' must declare a 'Sub New' because the 'Public Sub New()' in its base class 'C1' is marked obsolete. Class C2 ~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact> Public Sub BC30918ERR_NoNonObsoleteConstructorOnBase4() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="NoNonObsoleteConstructorOnBase4"> <file name="a.vb"> Imports System Class C1 &lt;Obsolete("hello", True)&gt; Sub New() End Sub End Class Class C2 Inherits C1 End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC30918: Class 'C2' must declare a 'Sub New' because the 'Public Sub New()' in its base class 'C1' is marked obsolete: 'hello'. Class C2 ~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact> Public Sub BC30919ERR_RequiredNonObsoleteNewCall3() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="RequiredNonObsoleteNewCall3"> <file name="a.vb"> Imports System Class C1 &lt;Obsolete(Nothing, True)&gt; Sub New() End Sub End Class Class C2 Inherits C1 Sub New() End Sub End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC30919: First statement of this 'Sub New' must be an explicit call to 'MyBase.New' or 'MyClass.New' because the 'Public Sub New()' in the base class 'C1' of 'C2' is marked obsolete. Sub New() ~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact> Public Sub BC30920ERR_RequiredNonObsoleteNewCall4() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="RequiredNonObsoleteNewCall4"> <file name="a.vb"> Imports System Class C1 &lt;Obsolete("hello", True)&gt; Sub New() End Sub End Class Class C2 Inherits C1 Sub New() End Sub End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC30920: First statement of this 'Sub New' must be an explicit call to 'MyBase.New' or 'MyClass.New' because the 'Public Sub New()' in the base class 'C1' of 'C2' is marked obsolete: 'hello'. Sub New() ~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <WorkItem(531309, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531309")> <Fact()> Public Sub BC30933ERR_LateBoundOverloadInterfaceCall1() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="LateBoundOverloadInterfaceCall1"> <file name="a.vb"> Module m1 Interface i1 Sub s1(ByVal p1 As Integer) Sub s1(ByVal p1 As Double) End Interface Class c1 Implements i1 Public Overloads Sub s1(ByVal p1 As Integer) Implements i1.s1 End Sub Public Overloads Sub s2(ByVal p1 As Double) Implements i1.s1 End Sub End Class Sub Main() Dim refer As i1 = New c1 Dim o1 As Object = 3.1415 refer.s1(o1) End Sub End Module Module m2 Interface i1 Property s1(ByVal p1 As Integer) Property s1(ByVal p1 As Double) End Interface Class c1 Implements i1 Public Property s1(p1 As Double) As Object Implements i1.s1 Get Return Nothing End Get Set(value As Object) End Set End Property Public Property s1(p1 As Integer) As Object Implements i1.s1 Get Return Nothing End Get Set(value As Object) End Set End Property End Class Sub Main() Dim refer As i1 = New c1 Dim o1 As Object = 3.1415 refer.s1(o1) = 1 End Sub End Module </file> </compilation>) Dim expectedErrors1 = <errors> BC30933: Late bound overload resolution cannot be applied to 's1' because the accessing instance is an interface type. refer.s1(o1) ~~ BC30933: Late bound overload resolution cannot be applied to 's1' because the accessing instance is an interface type. refer.s1(o1) = 1 ~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC30934ERR_RequiredAttributeConstConversion2() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="a.vb"><![CDATA[ Imports System <A(<a/>)> Class A Inherits Attribute Public Sub New(o As Object) End Sub End Class ]]></file> </compilation>, references:=XmlReferences) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_RequiredAttributeConstConversion2, "<a/>").WithArguments("System.Xml.Linq.XElement", "Object")) End Sub <Fact()> Public Sub BC30939ERR_AddressOfNotCreatableDelegate1() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="AddressOfNotCreatableDelegate1"> <file name="a.vb"> Imports System Module M1 Sub foo() Dim x As [Delegate] = AddressOf main End Sub Sub main() End Sub End Module </file> </compilation>) Dim expectedErrors1 = <errors> BC30939: 'AddressOf' expression cannot be converted to '[Delegate]' because type '[Delegate]' is declared 'MustInherit' and cannot be created. Dim x As [Delegate] = AddressOf main ~~~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact(), WorkItem(529157, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529157")> Public Sub BC30940ERR_ReturnFromEventMethod() 'diag behavior change by design- not worth investing in. Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="ReturnFromEventMethod"> <file name="a.vb"> Class C1 Delegate Sub EH() Custom Event e1 As EH AddHandler(ByVal value As EH) Return value End AddHandler RemoveHandler(ByVal value As EH) Return value End RemoveHandler RaiseEvent() Return value End RaiseEvent End Event End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC30647: 'Return' statement in a Sub or a Set cannot return a value. Return value ~~~~~~~~~~~~ BC30647: 'Return' statement in a Sub or a Set cannot return a value. Return value ~~~~~~~~~~~~ BC30647: 'Return' statement in a Sub or a Set cannot return a value. Return value ~~~~~~~~~~~~ BC30451: 'value' is not declared. It may be inaccessible due to its protection level. Return value ~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <WorkItem(542270, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542270")> <Fact()> Public Sub BC30949ERR_ArrayInitializerForNonConstDim() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ArrayInitializerForNonConstDim"> <file name="a.vb"> Option Strict On Module M Sub Main() Dim x as integer = 1 Dim y as Object = New Integer(x) {1, 2} End Sub End Module </file> </compilation>) Dim expectedErrors1 = <errors> BC30949: Array initializer cannot be specified for a non constant dimension; use the empty initializer '{}'. Dim y as Object = New Integer(x) {1, 2} ~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <WorkItem(542270, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542270")> <Fact()> Public Sub BC30949ERR_ArrayInitializerForNonConstDim_1() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="ArrayInitializerForNonConstDim"> <file name="a.vb"> Option Strict On Imports System Class M1 Public Shared Sub Main() Dim myLength As Integer = 2 Dim arr As Integer(,) = New Integer(myLength - 1, 1) {{1, 2}, {3, 4}, {5, 6}} End Sub Private Class A Private x As Integer = 1 Private arr As Integer(,) = New Integer(x, 1) {{1, 2}, {3, 4}, {5, 6}} End Class End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC30949: Array initializer cannot be specified for a non constant dimension; use the empty initializer '{}'. Dim arr As Integer(,) = New Integer(myLength - 1, 1) {{1, 2}, {3, 4}, {5, 6}} ~~~~~~~~~~~~~~~~~~~~~~~~ BC30949: Array initializer cannot be specified for a non constant dimension; use the empty initializer '{}'. Private arr As Integer(,) = New Integer(x, 1) {{1, 2}, {3, 4}, {5, 6}} ~~~~~~~~~~~~~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC30950ERR_DelegateBindingFailure3() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="DelegateBindingFailure3"> <file name="a.vb"> Option Strict On Imports System Module M Dim f As Action(Of Object) = CType(AddressOf 1.ToString, Action(Of Object)) End Module </file> </compilation>) Dim expectedErrors1 = <errors> </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC30978ERR_IterationVariableShadowLocal1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="IterationVariableShadowLocal1"> <file name="a.vb"> Option Infer On Option Strict Off Imports System.Linq Module M Sub Bar() Dim x = From bar In "" End Sub Function Foo() Dim x = From foo In "" Return Nothing End Function End Module </file> </compilation>, {Net40.SystemCore}) Dim expectedErrors1 = <errors> BC30978: Range variable 'foo' hides a variable in an enclosing block or a range variable previously defined in the query expression. Dim x = From foo In "" ~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation, expectedErrors1) End Sub <Fact()> Public Sub BC30978ERR_IterationVariableShadowLocal1_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="IterationVariableShadowLocal1"> <file name="a.vb"> Option Infer Off Imports System Imports System.Linq Module Program Sub Main(args As String()) Dim arr As String() = New String() {"aaa", "bbb", "ccc"} Dim arr_int As Integer() = New Integer() {111, 222, 333} Dim x = 1 Dim s = If(True, (From x In arr Select x).ToList(), From y As Integer In arr_int Select y) End Sub End Module </file> </compilation>, {Net40.SystemCore}, options:=TestOptions.ReleaseExe) Dim expectedErrors1 = <errors> BC30978: Range variable 'x' hides a variable in an enclosing block or a range variable previously defined in the query expression. Dim s = If(True, (From x In arr Select x).ToList(), From y As Integer In arr_int Select y) ~ BC30978: Range variable 'x' hides a variable in an enclosing block or a range variable previously defined in the query expression. Dim s = If(True, (From x In arr Select x).ToList(), From y As Integer In arr_int Select y) ~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation, expectedErrors1) End Sub <Fact()> Public Sub BC30980ERR_CircularInference1() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="CircularInference2"> <file name="a.vb"> Module M Const x = 1 Sub Main() Dim x = Function() x End Sub End Module </file> </compilation>) ' Extra Warning in Roslyn compilation1.VerifyDiagnostics( Diagnostic(ERRID.ERR_CircularInference1, "x").WithArguments("x") ) End Sub <Fact()> Public Sub BC30980ERR_CircularInference1_2() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="CircularInference2"> <file name="a.vb"> Option Infer On Imports System Class C Shared Sub Main() Dim f As Func(Of Integer) = Function() For Each x In x + 1 Return x Next return 0 End Function End Sub End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC30980: Type of 'x' cannot be inferred from an expression containing 'x'. For Each x In x + 1 ~ BC42104: Variable 'x' is used before it has been assigned a value. A null reference exception could result at runtime. For Each x In x + 1 ~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC30980ERR_CircularInference2_2() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="CircularInference2_2"> <file name="a.vb"> Class C Shared Sub Main() For Each y In New Object() {New With {Key .y = y}} Next End Sub End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC30980: Type of 'y' cannot be inferred from an expression containing 'y'. For Each y In New Object() {New With {Key .y = y}} ~ BC42104: Variable 'y' is used before it has been assigned a value. A null reference exception could result at runtime. For Each y In New Object() {New With {Key .y = y}} ~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC30980ERR_CircularInference2_2a() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="CircularInference2_2a"> <file name="a.vb"> Class C Shared Sub Main() 'For Each y As Object In New Object() {y} For Each y As Object In New Object() {New With {Key .y = y}} Next End Sub End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC42104: Variable 'y' is used before it has been assigned a value. A null reference exception could result at runtime. For Each y As Object In New Object() {New With {Key .y = y}} ~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <WorkItem(542268, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542268")> <Fact()> Public Sub BC30980ERR_CircularInference2_3() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="CircularInference2_3"> <file name="a.vb"> Option Infer On Class C Shared Sub Main() Dim a = a.b End Sub End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC30980: Type of 'a' cannot be inferred from an expression containing 'a'. Dim a = a.b ~ BC42104: Variable 'a' is used before it has been assigned a value. A null reference exception could result at runtime. Dim a = a.b ~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <WorkItem(542268, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542268")> <Fact()> Public Sub BC30980ERR_CircularInference2_3a() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="CircularInference2_3a"> <file name="a.vb"> Option Infer Off Class C Shared Sub Main() Dim a = a.ToString() End Sub End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC42104: Variable 'a' is used before it has been assigned a value. A null reference exception could result at runtime. Dim a = a.ToString() ~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact(), WorkItem(542191, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542191")> Public Sub BC30982ERR_NoSuitableWidestType1() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="NoSuitableWidestType1"> <file name="a.vb"> Option Infer On Module M Sub Main() Dim stepVar = "1"c For i = 1 To 10 Step stepVar Next End Sub End Module </file> </compilation>) Dim expectedErrors1 = <errors> BC30982: Type of 'i' cannot be inferred because the loop bounds and the step clause do not convert to the same type. For i = 1 To 10 Step stepVar ~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact(), WorkItem(12261, "DevDiv_Projects/Roslyn")> Public Sub BC30983ERR_AmbiguousWidestType3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="AmbiguousWidestType3"> <file name="a.vb"> Module modErr30983 Sub Test() 'COMPILEERROR : BC30983, "i" For i = New first(1) To New second(2) Step New third(3) Next End Sub End Module Class base End Class Class first Inherits base Dim m_count As ULong Sub New(ByVal d As ULong) m_count = d End Sub Overloads Shared Widening Operator CType(ByVal d As first) As second Return New second(d.m_count) End Operator End Class Class second Inherits base Dim m_count As ULong Sub New(ByVal d As ULong) m_count = d End Sub Overloads Shared Widening Operator CType(ByVal d As second) As first Return New first(d.m_count) End Operator End Class Class third Inherits first Sub New(ByVal d As ULong) MyBase.New(d) End Sub Overloads Shared Widening Operator CType(ByVal d As third) As Integer Return 1 End Operator End Class </file> </compilation>) 'BC30983: Type of 'i' is ambiguous because the loop bounds and the step clause do not convert to the same type. 'For i = New first(1) To New second(2) Step New third(3) ' ~ compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_AmbiguousWidestType3, "i").WithArguments("i")) End Sub <Fact()> Public Sub BC30989ERR_DuplicateAggrMemberInit1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="DuplicateAggrMemberInit1"> <file name="a.vb"> Module M Sub Main() Dim cust = New Customer() With {.Name = "Bob", .Name = "Robert"} End Sub End Module Class Customer Property Name As String End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30989: Multiple initializations of 'Name'. Fields and properties can be initialized only once in an object initializer expression. Dim cust = New Customer() With {.Name = "Bob", .Name = "Robert"} ~~~~ </expected>) End Sub <Fact()> Public Sub BC30990ERR_NonFieldPropertyAggrMemberInit1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="NonFieldPropertyAggrMemberInit1"> <file name="a.vb"> Module M1 Class WithSubX Public Sub x() End Sub End Class Sub foo() Dim z As WithSubX = New WithSubX With {.x = 5} End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30990: Member 'x' cannot be initialized in an object initializer expression because it is not a field or property. Dim z As WithSubX = New WithSubX With {.x = 5} ~ </expected>) End Sub <Fact()> Public Sub BC30991ERR_SharedMemberAggrMemberInit1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="SharedMemberAggrMemberInit1"> <file name="a.vb"> Module M Sub Main() Dim cust As New Customer With {.totalCustomers = 21} End Sub End Module Public Class Customer Public Shared totalCustomers As Integer End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30991: Member 'totalCustomers' cannot be initialized in an object initializer expression because it is shared. Dim cust As New Customer With {.totalCustomers = 21} ~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30992ERR_ParameterizedPropertyInAggrInit1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ParameterizedPropertyInAggrInit1"> <file name="a.vb"> Module M Sub Main() Dim strs As New C1() With {.defaultProp = "One"} End Sub End Module Public Class C1 Private myStrings() As String Default Property defaultProp(ByVal index As Integer) As String Get Return myStrings(index) End Get Set(ByVal Value As String) myStrings(index) = Value End Set End Property End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30992: Property 'defaultProp' cannot be initialized in an object initializer expression because it requires arguments. Dim strs As New C1() With {.defaultProp = "One"} ~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30993ERR_NoZeroCountArgumentInitCandidates1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="NoZeroCountArgumentInitCandidates1"> <file name="a.vb"> Module M Sub Main() Dim aCoinObject = nothing Dim coinCollection As New C1 With {.Item = aCoinObject} End Sub End Module Class C1 WriteOnly Property Item(ByVal Key As String) As Object Set(ByVal value As Object) End Set End Property WriteOnly Property Item(ByVal Index As Integer) As Object Set(ByVal value As Object) End Set End Property private WriteOnly Property Item(ByVal Index As Long) As Object Set(ByVal value As Object) End Set End Property End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30993: Property 'Item' cannot be initialized in an object initializer expression because all accessible overloads require arguments. Dim coinCollection As New C1 With {.Item = aCoinObject} ~~~~ </expected>) End Sub <Fact()> Public Sub BC30994ERR_AggrInitInvalidForObject() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="AggrInitInvalidForObject"> <file name="a.vb"> Module M Sub Main() Dim obj = New Object With {.ToString = "hello"} End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30994: Object initializer syntax cannot be used to initialize an instance of 'System.Object'. Dim obj = New Object With {.ToString = "hello"} ~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC31080ERR_ReferenceComparison3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="ReferenceComparison3"> <file name="a.vb"> Interface I1 Interface I2 End Interface End Interface Class C1 Sub FOO() Dim scenario1 As I1.I2 If scenario1 = Nothing Then End If End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42104: Variable 'scenario1' is used before it has been assigned a value. A null reference exception could result at runtime. If scenario1 = Nothing Then ~~~~~~~~~ BC31080: Operator '=' is not defined for types 'I1.I2' and 'I1.I2'. Use 'Is' operator to compare two reference types. If scenario1 = Nothing Then ~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC31082ERR_CatchVariableNotLocal1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="CatchVariableNotLocal1"> <file name="a.vb"> Imports System Module M Dim ex As Exception Sub Main() Try Catch ex End Try End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC31082: 'ex' is not a local variable or parameter, and so cannot be used as a 'Catch' variable. Catch ex ~~ </expected>) End Sub <WorkItem(538613, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538613")> <Fact()> Public Sub BC30251_ModuleConstructorCall() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module M Sub [New]() M.New() End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30251: Type 'M' has no constructors. M.New() ~~~~~ </expected>) End Sub <WorkItem(538613, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538613")> <Fact()> Public Sub BC30251_ModuleGenericConstructorCall() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module M Sub [New](Of T)() M.New(Of Integer) End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30251: Type 'M' has no constructors. M.New(Of Integer) ~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact(), WorkItem(570936, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/570936")> Public Sub BC31092ERR_ParamArrayWrongType() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ParamArrayWrongType"> <file name="a.vb"> Module M1 Sub Foo() Dim x As New C1 Dim sResult As String = x.Foo(1, 2, 3, 4) End Sub End Module Class C1 Function Foo(&lt;System.[ParamArray]()&gt; ByVal x As Integer) As String Return "He" End Function End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC31092: ParamArray parameters must have an array type. Dim sResult As String = x.Foo(1, 2, 3, 4) ~~~ </expected>) End Sub <Fact(), WorkItem(570936, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/570936")> Public Sub BC31092ERR_ParamArrayWrongType_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ParamArrayWrongType"> <file name="a.vb"> Module M1 Sub Foo() Dim x As New C1 Dim sResult As String = x.Foo(1) End Sub End Module Class C1 Function Foo(&lt;System.[ParamArray]()&gt; ByVal x As Integer) As String Return "He" End Function End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC31092: ParamArray parameters must have an array type. Dim sResult As String = x.Foo(1) ~~~ </expected>) End Sub <Fact()> Public Sub BC31095ERR_InvalidMyClassReference() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BC31095ERR_InvalidMyClassReference"> <file name="a.vb"> Class cls0 Public s2 As String End Class Class Cls1 Inherits cls0 Sub New(ByVal x As Short) End Sub Sub New() 'COMPILEERROR: BC31095, "MyClass" MyClass.New(MyClass.s2) End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC31095: Reference to object under construction is not valid when calling another constructor. MyClass.New(MyClass.s2) ~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC31095ERR_InvalidMyBaseReference() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BC31095ERR_InvalidMyBaseReference"> <file name="a.vb"> Class cls0 Public s2 As String End Class Class Cls1 Inherits cls0 Sub New(ByVal x As Short) End Sub Sub New() 'COMPILEERROR: BC31095, "MyBase" MyClass.New(MyBase.s2) End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC31095: Reference to object under construction is not valid when calling another constructor. MyClass.New(MyBase.s2) ~~~~~~ </expected>) End Sub <WorkItem(541798, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541798")> <Fact()> Public Sub BC31095ERR_InvalidMeReference() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="InvalidMeReference"> <file name="a.vb"> Class cls0 Public s2 As String End Class Class Cls1 Inherits cls0 Sub New(ByVal x As String) End Sub Sub New(ByVal x As Short) Me.New(Me.s2) 'COMPILEERROR: BC31095, "Me" End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC31095: Reference to object under construction is not valid when calling another constructor. Me.New(Me.s2) 'COMPILEERROR: BC31095, "Me" ~~ </expected>) End Sub <WorkItem(541799, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541799")> <Fact()> Public Sub BC31096ERR_InvalidImplicitMeReference() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="InvalidImplicitMeReference"> <file name="a.vb"> Imports System Module M1 Class clsTest1 Private strTest As String = "Hello" Sub New() 'COMPILEERROR: BC31096, "strTest" Me.New(strTest) End Sub Sub New(ByVal ArgX As String) End Sub End Class End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC31096: Implicit reference to object under construction is not valid when calling another constructor. Me.New(strTest) ~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC31096ERR_InvalidImplicitMeReference_MyClass() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="BC31096ERR_InvalidImplicitMeReference_MyClass"> <file name="a.vb"> Imports System Module M1 Class clsTest1 Private strTest As String = "Hello" Sub New() 'COMPILEERROR: BC31096, "strTest" MyClass.New(strTest) End Sub Sub New(ByVal ArgX As String) End Sub End Class End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC31096: Implicit reference to object under construction is not valid when calling another constructor. MyClass.New(strTest) ~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC31096ERR_InvalidImplicitMeReference_MyBase() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="BC31096ERR_InvalidImplicitMeReference_MyBase"> <file name="a.vb"> Imports System Module M1 Class clsTest0 Public Sub New(ByVal strTest As String) End Sub End Class Class clsTest1 Inherits clsTest0 Private strTest As String = "Hello" Sub New() 'COMPILEERROR: BC31096, "strTest" MyBase.New(strTest) End Sub End Class End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC31096: Implicit reference to object under construction is not valid when calling another constructor. MyBase.New(strTest) ~~~~~~~ </expected>) End Sub ' Different error <Fact()> Public Sub BC31109ERR_InAccessibleCoClass3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="C"> <file name="a.vb"> Imports System.Runtime.InteropServices &lt;Assembly: ImportedFromTypeLib("NoPIANew1-PIA2.dll")&gt; &lt;Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")&gt; Public Class Class1 &lt;Guid("bd60d4b3-f50b-478b-8ef2-e777df99d810")&gt; _ &lt;ComImport()&gt; _ &lt;InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)&gt; _ &lt;CoClass(GetType(FooImpl))&gt; _ Public Interface IFoo End Interface &lt;Guid("c9dcf748-b634-4504-a7ce-348cf7c61891")&gt; _ Friend Class FooImpl End Class End Class </file> </compilation>) Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="InAccessibleCoClass3"> <file name="a.vb"> Public Module Module1 Public Sub Main() Dim i1 As New Class1.IFoo(1) Dim i2 = New Class1.IFoo(Nothing) End Sub End Module </file> </compilation>) Dim compRef = New VisualBasicCompilationReference(compilation) compilation1 = compilation1.AddReferences(compRef) compilation1.VerifyDiagnostics(Diagnostic(ERRID.ERR_InAccessibleCoClass3, "New Class1.IFoo(1)").WithArguments("Class1.FooImpl", "Class1.IFoo", "Friend"), Diagnostic(ERRID.ERR_InAccessibleCoClass3, "New Class1.IFoo(Nothing)").WithArguments("Class1.FooImpl", "Class1.IFoo", "Friend")) End Sub <WorkItem(6977, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub BC31110ERR_MissingValuesForArraysInApplAttrs() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="MissingValuesForArraysInApplAttrs"> <file name="a.vb"><![CDATA[ Imports System <AttributeUsage(AttributeTargets.All)> Public Class MyAttribute Inherits Attribute Public Sub New(ByVal o As Object) End Sub End Class Namespace AttributeRegress003 Friend Module AttributeRegress003mod 'COMPILEERROR: BC31110, "{}" <My(New Integer(3) {})> Class Test End Class End Module End Namespace ]]></file> </compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_MissingValuesForArraysInApplAttrs, "{}")) End Sub <Fact()> Public Sub BC31102ERR_NoAccessibleSet() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="NoAccessibleSet"> <file name="a.vb"> Class A Shared Property P Get Return Nothing End Get Private Set End Set End Property Property Q Get Return Nothing End Get Private Set End Set End Property End Class Class B Sub M(ByVal x As A) A.P = Nothing x.Q = Nothing End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC31102: 'Set' accessor of property 'P' is not accessible. A.P = Nothing ~~~~~~~~~~~~~ BC31102: 'Set' accessor of property 'Q' is not accessible. x.Q = Nothing ~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC31103ERR_NoAccessibleGet() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="NoAccessibleGet"> <file name="a.vb"> Class A Shared Property P Private Get Return Nothing End Get Set End Set End Property Property Q Private Get Return Nothing End Get Set End Set End Property End Class Class B Sub M(ByVal x As A) N(A.P) N(x.Q) End Sub Sub N(ByVal o As Object) End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC31103: 'Get' accessor of property 'P' is not accessible. N(A.P) ~~~ BC31103: 'Get' accessor of property 'Q' is not accessible. N(x.Q) ~~~ </expected>) End Sub <Fact()> Public Sub BC31143ERR_DelegateBindingIncompatible2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="DelegateBindingIncompatible2"> <file name="a.vb"> Public Class C1 Delegate Function FunDel(ByVal i As Integer, ByVal d As Double) As Integer Function ExampleMethod1(ByVal m As Integer, ByVal aDate As Date) As Integer Return 1 End Function Sub Main() Dim d1 As FunDel = AddressOf ExampleMethod1 End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC31143: Method 'Public Function ExampleMethod1(m As Integer, aDate As Date) As Integer' does not have a signature compatible with delegate 'Delegate Function C1.FunDel(i As Integer, d As Double) As Integer'. Dim d1 As FunDel = AddressOf ExampleMethod1 ~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC31148ERR_UndefinedXmlPrefix() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Imports <xmlns:p0="http://roslyn/"> Module M Private F1 = GetXmlNamespace(p1) Private F2 = <%= GetXmlNamespace(p0) %> Private F3 = <%= GetXmlNamespace(p3) %> Private F4 = <p4:x xmlns:p4="http://roslyn/"><%= GetXmlNamespace(p4) %></p4:x> End Module ]]></file> </compilation>, references:=XmlReferences) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC31148: XML namespace prefix 'p1' is not defined. Private F1 = GetXmlNamespace(p1) ~~ BC31172: An embedded expression cannot be used here. Private F2 = <%= GetXmlNamespace(p0) %> ~~~~~~~~~~~~~~~~~~~~~~~~~~ BC31172: An embedded expression cannot be used here. Private F3 = <%= GetXmlNamespace(p3) %> ~~~~~~~~~~~~~~~~~~~~~~~~~~ BC31148: XML namespace prefix 'p3' is not defined. Private F3 = <%= GetXmlNamespace(p3) %> ~~ BC31148: XML namespace prefix 'p4' is not defined. Private F4 = <p4:x xmlns:p4="http://roslyn/"><%= GetXmlNamespace(p4) %></p4:x> ~~ ]]></errors>) End Sub <Fact()> Public Sub BC31148ERR_UndefinedXmlPrefix_1() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Imports System.Xml.Linq Class C Private F1 As XElement = <p1:a q1:b="c" xmlns:p1="..." xmlns:q1="..."/> Private F2 As XElement = <p2:a q2:b="c"><b xmlns:p2="..." xmlns:q2="..."/></p2:a> Private F3 As String = <p3:a q3:b="c" xmlns:p3="..." xmlns:q3="..."/>.<p3:a>.@q3:b End Class ]]></file> </compilation>, references:=XmlReferences) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC31148: XML namespace prefix 'p2' is not defined. Private F2 As XElement = <p2:a q2:b="c"><b xmlns:p2="..." xmlns:q2="..."/></p2:a> ~~ BC31148: XML namespace prefix 'q2' is not defined. Private F2 As XElement = <p2:a q2:b="c"><b xmlns:p2="..." xmlns:q2="..."/></p2:a> ~~ BC31148: XML namespace prefix 'p3' is not defined. Private F3 As String = <p3:a q3:b="c" xmlns:p3="..." xmlns:q3="..."/>.<p3:a>.@q3:b ~~ BC31148: XML namespace prefix 'q3' is not defined. Private F3 As String = <p3:a q3:b="c" xmlns:p3="..." xmlns:q3="..."/>.<p3:a>.@q3:b ~~ ]]></errors>) End Sub <Fact()> Public Sub BC31148ERR_UndefinedXmlPrefix_2() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Imports <xmlns:p0="..."> Module M Private F = <x1 xmlns:p1="..."> <x2 xmlns:p2="..." p0:a0="..." p1:a1="..." p2:a2="..." p6:a6="..." p7:a7="..." p8:a8="..."> <%= <x3> <x4 p0:a0="..." p1:a1="..." p2:a2="..." p6:a6="..." p7:a7="..." p8:a8="..."> <%= <x5> <x6 xmlns:p6="..." p0:a0="..." p1:a1="..." p2:a2="..." p6:a6="..." p7:a7="..." p8:a8="..."> <%= <x7 xmlns:p7="..."> <x8 xmlns:p8="..."> <x9 p0:a0="..." p1:a1="..." p2:a2="..." p6:a6="..." p7:a7="..." p8:a8="..."/> </x8> </x7> %> </x6> </x5> %> </x4> </x3> %> </x2> </x1> End Module ]]></file> </compilation>, references:=XmlReferences) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC31148: XML namespace prefix 'p6' is not defined. <x2 xmlns:p2="..." p0:a0="..." p1:a1="..." p2:a2="..." p6:a6="..." p7:a7="..." p8:a8="..."> ~~ BC31148: XML namespace prefix 'p7' is not defined. <x2 xmlns:p2="..." p0:a0="..." p1:a1="..." p2:a2="..." p6:a6="..." p7:a7="..." p8:a8="..."> ~~ BC31148: XML namespace prefix 'p8' is not defined. <x2 xmlns:p2="..." p0:a0="..." p1:a1="..." p2:a2="..." p6:a6="..." p7:a7="..." p8:a8="..."> ~~ BC31148: XML namespace prefix 'p1' is not defined. <x4 p0:a0="..." p1:a1="..." p2:a2="..." p6:a6="..." p7:a7="..." p8:a8="..."> ~~ BC31148: XML namespace prefix 'p2' is not defined. <x4 p0:a0="..." p1:a1="..." p2:a2="..." p6:a6="..." p7:a7="..." p8:a8="..."> ~~ BC31148: XML namespace prefix 'p6' is not defined. <x4 p0:a0="..." p1:a1="..." p2:a2="..." p6:a6="..." p7:a7="..." p8:a8="..."> ~~ BC31148: XML namespace prefix 'p7' is not defined. <x4 p0:a0="..." p1:a1="..." p2:a2="..." p6:a6="..." p7:a7="..." p8:a8="..."> ~~ BC31148: XML namespace prefix 'p8' is not defined. <x4 p0:a0="..." p1:a1="..." p2:a2="..." p6:a6="..." p7:a7="..." p8:a8="..."> ~~ BC31148: XML namespace prefix 'p1' is not defined. <x6 xmlns:p6="..." p0:a0="..." p1:a1="..." p2:a2="..." p6:a6="..." p7:a7="..." p8:a8="..."> ~~ BC31148: XML namespace prefix 'p2' is not defined. <x6 xmlns:p6="..." p0:a0="..." p1:a1="..." p2:a2="..." p6:a6="..." p7:a7="..." p8:a8="..."> ~~ BC31148: XML namespace prefix 'p7' is not defined. <x6 xmlns:p6="..." p0:a0="..." p1:a1="..." p2:a2="..." p6:a6="..." p7:a7="..." p8:a8="..."> ~~ BC31148: XML namespace prefix 'p8' is not defined. <x6 xmlns:p6="..." p0:a0="..." p1:a1="..." p2:a2="..." p6:a6="..." p7:a7="..." p8:a8="..."> ~~ BC31148: XML namespace prefix 'p1' is not defined. <x9 p0:a0="..." p1:a1="..." p2:a2="..." p6:a6="..." p7:a7="..." p8:a8="..."/> ~~ BC31148: XML namespace prefix 'p2' is not defined. <x9 p0:a0="..." p1:a1="..." p2:a2="..." p6:a6="..." p7:a7="..." p8:a8="..."/> ~~ BC31148: XML namespace prefix 'p6' is not defined. <x9 p0:a0="..." p1:a1="..." p2:a2="..." p6:a6="..." p7:a7="..." p8:a8="..."/> ~~ ]]></errors>) End Sub <WorkItem(531633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531633")> <Fact()> Public Sub BC31148ERR_UndefinedXmlPrefix_3() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Module M Sub Main() Dim x As Object x = <x/>.@Return:a End Sub End Module ]]></file> </compilation>, references:=XmlReferences) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC31148: XML namespace prefix 'Return' is not defined. x = <x/>.@Return:a ~~~~~~ ]]></errors>) End Sub <Fact()> Public Sub BC31149ERR_DuplicateXmlAttribute() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Module M Private F1 = <x a="b" a="c" A="d" A="e"/> Private F2 = <x a="b" a="c" a="d" xmlns="http://roslyn"/> Private F3 = <x p:a="b" p:a="c" xmlns:p="http://roslyn"/> Private F4 = <x xmlns:a="b" xmlns:a="c"/> Private F5 = <x p:a="b" q:a="c" xmlns:p="http://roslyn" xmlns:q="http://roslyn"/> Private F6 = <x p:a="b" P:a="c" xmlns:p="http://roslyn/p" xmlns:P="http://roslyn/P"/> Private F7 = <x a="b" <%= "a" %>="c" <%= "a" %>="d"/> End Module ]]></file> </compilation>, references:=XmlReferences) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC31149: Duplicate XML attribute 'a'. Private F1 = <x a="b" a="c" A="d" A="e"/> ~ BC31149: Duplicate XML attribute 'A'. Private F1 = <x a="b" a="c" A="d" A="e"/> ~ BC31149: Duplicate XML attribute 'a'. Private F2 = <x a="b" a="c" a="d" xmlns="http://roslyn"/> ~ BC31149: Duplicate XML attribute 'a'. Private F2 = <x a="b" a="c" a="d" xmlns="http://roslyn"/> ~ BC31149: Duplicate XML attribute 'p:a'. Private F3 = <x p:a="b" p:a="c" xmlns:p="http://roslyn"/> ~~~ BC31149: Duplicate XML attribute 'xmlns:a'. Private F4 = <x xmlns:a="b" xmlns:a="c"/> ~~~~~~~ BC31149: Duplicate XML attribute 'q:a'. Private F5 = <x p:a="b" q:a="c" xmlns:p="http://roslyn" xmlns:q="http://roslyn"/> ~~~ ]]></errors>) End Sub <Fact()> Public Sub BC31149ERR_DuplicateXmlAttribute_1() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports <xmlns="http://roslyn/"> Imports <xmlns:p="http://roslyn/"> Imports <xmlns:q=""> Class C Private Shared F1 As Object = <x a="b" a="c"/> Private Shared F2 As Object = <x p:a="b" a="c"/> Private Shared F3 As Object = <x q:a="b" a="c"/> End Class ]]></file> </compilation>, references:=XmlReferences) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC31149: Duplicate XML attribute 'a'. Private Shared F1 As Object = <x a="b" a="c"/> ~ BC31149: Duplicate XML attribute 'a'. Private Shared F3 As Object = <x q:a="b" a="c"/> ~ ]]></errors>) End Sub ' Should report duplicate xmlns attributes, even for xmlns ' attributes that match Imports since those have special handling. <Fact()> Public Sub BC31149ERR_DuplicateXmlAttribute_2() Dim options = TestOptions.ReleaseDll.WithGlobalImports(GlobalImport.Parse({"<xmlns:p=""http://roslyn/p"">"})) Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports <xmlns:q="http://roslyn/q"> Module M Private F1 As Object = <x xmlns:p="http://roslyn/p" xmlns:p="http://roslyn/other"/> Private F2 As Object = <x xmlns:q="http://roslyn/other" xmlns:q="http://roslyn/q"/> End Module ]]></file> </compilation>, references:=XmlReferences, options:=options) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC31149: Duplicate XML attribute 'xmlns:p'. Private F1 As Object = <x xmlns:p="http://roslyn/p" xmlns:p="http://roslyn/other"/> ~~~~~~~ BC31149: Duplicate XML attribute 'xmlns:q'. Private F2 As Object = <x xmlns:q="http://roslyn/other" xmlns:q="http://roslyn/q"/> ~~~~~~~ ]]></errors>) End Sub <Fact()> Public Sub BC31152ERR_ReservedXmlPrefix() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Imports <xmlns="http://roslyn/"> Imports <xmlns:xml="http://roslyn/xml"> Imports <xmlns:xmlns="http://roslyn/xmlns"> Imports <xmlns:Xml="http://roslyn/xml"> Imports <xmlns:Xmlns="http://roslyn/xmlns"> Module M Private F1 As Object = <x xmlns="http://roslyn/" xmlns:xml="http://roslyn/xml" xmlns:xmlns="http://roslyn/xmlns"/> Private F2 As Object = <x xmlns:XML="http://roslyn/xml" xmlns:XMLNS="http://roslyn/xmlns"/> Private F3 As Object = <x xmlns="" xmlns:xml="" xmlns:xmlns=""/> End Module ]]></file> </compilation>, references:=XmlReferences) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC31152: XML namespace prefix 'xml' is reserved for use by XML and the namespace URI cannot be changed. Imports <xmlns:xml="http://roslyn/xml"> ~~~ BC31152: XML namespace prefix 'xmlns' is reserved for use by XML and the namespace URI cannot be changed. Imports <xmlns:xmlns="http://roslyn/xmlns"> ~~~~~ BC31152: XML namespace prefix 'xml' is reserved for use by XML and the namespace URI cannot be changed. xmlns:xml="http://roslyn/xml" ~~~ BC31152: XML namespace prefix 'xmlns' is reserved for use by XML and the namespace URI cannot be changed. xmlns:xmlns="http://roslyn/xmlns"/> ~~~~~ BC31152: XML namespace prefix 'xml' is reserved for use by XML and the namespace URI cannot be changed. xmlns:xml="" ~~~ BC31152: XML namespace prefix 'xmlns' is reserved for use by XML and the namespace URI cannot be changed. xmlns:xmlns=""/> ~~~~~ ]]></errors>) End Sub <Fact()> Public Sub BC31152ERR_ReservedXmlPrefix_1() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Imports <xmlns:xml="http://www.w3.org/XML/1998/namespace"> Imports <xmlns:xmlns="http://www.w3.org/XML/1998/namespace"> Module M Private F1 As Object = <x xmlns:xml="http://www.w3.org/2000/xmlns/" xmlns:xmlns="http://www.w3.org/2000/xmlns/"/> Private F2 As Object = <x xmlns:xml="http://www.w3.org/XML/1998/NAMESPACE"/> End Module ]]></file> </compilation>, references:=XmlReferences) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC31152: XML namespace prefix 'xmlns' is reserved for use by XML and the namespace URI cannot be changed. Imports <xmlns:xmlns="http://www.w3.org/XML/1998/namespace"> ~~~~~ BC31152: XML namespace prefix 'xml' is reserved for use by XML and the namespace URI cannot be changed. xmlns:xml="http://www.w3.org/2000/xmlns/" ~~~ BC31152: XML namespace prefix 'xmlns' is reserved for use by XML and the namespace URI cannot be changed. xmlns:xmlns="http://www.w3.org/2000/xmlns/"/> ~~~~~ BC31152: XML namespace prefix 'xml' is reserved for use by XML and the namespace URI cannot be changed. xmlns:xml="http://www.w3.org/XML/1998/NAMESPACE"/> ~~~ ]]></errors>) End Sub <Fact()> Public Sub BC31168ERR_NoXmlAxesLateBinding() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="a.vb"><![CDATA[ Module M1 Sub M() Dim a = Nothing Dim b As Object = Nothing Dim c As Object c = a.<x> c = b.@a End Sub End Module ]]></file> <file name="b.vb"><![CDATA[ Option Strict On Module M2 Sub M() Dim a As Object = Nothing Dim b = Nothing Dim c As Object c = a...<x> c = b.@<a> End Sub End Module ]]></file> </compilation>, references:=XmlReferences) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC31168: XML axis properties do not support late binding. c = a.<x> ~~~~~ BC31168: XML axis properties do not support late binding. c = b.@a ~~~~ BC31168: XML axis properties do not support late binding. c = a...<x> ~~~~~~~ BC31168: XML axis properties do not support late binding. c = b.@<a> ~~~~~~ ]]></errors>) End Sub <Fact()> Public Sub BC31172ERR_EmbeddedExpression() Dim options = TestOptions.ReleaseDll.WithGlobalImports(GlobalImport.Parse({"<xmlns:p=<%= M1.F %>>"})) Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Imports <xmlns:q=<%= M1.F %>> Module M1 Private F = "..." End Module Module M2 Public F = <x xmlns=<%= M1.F %>/> End Module ]]></file> </compilation>, references:=XmlReferences, options:=options) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC31172: Error in project-level import '<xmlns:p=<%= M1.F %>>' at '<%= M1.F %>' : An embedded expression cannot be used here. BC31172: An embedded expression cannot be used here. Imports <xmlns:q=<%= M1.F %>> ~~~~~~~~~~~ BC31172: An embedded expression cannot be used here. Public F = <x xmlns=<%= M1.F %>/> ~~~~~~~~~~~ BC30389: 'M1.F' is not accessible in this context because it is 'Private'. Public F = <x xmlns=<%= M1.F %>/> ~~~~ ]]></errors>) End Sub <Fact()> Public Sub BC31183ERR_ReservedXmlNamespace() Dim options = TestOptions.ReleaseDll.WithGlobalImports(GlobalImport.Parse({"<xmlns=""http://www.w3.org/XML/1998/namespace"">", "<xmlns:p1=""http://www.w3.org/2000/xmlns/"">"})) Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Imports <xmlns="http://www.w3.org/XML/1998/namespace"> Imports <xmlns:p2="http://www.w3.org/2000/xmlns/"> Module M Private F1 As Object = <x xmlns="http://www.w3.org/2000/xmlns/" xmlns:p3="http://www.w3.org/XML/1998/namespace"/> Private F2 As Object = <x xmlns="http://www.w3.org/2000/XMLNS/" xmlns:p4="http://www.w3.org/XML/1998/NAMESPACE"/> End Module ]]></file> </compilation>, references:=XmlReferences, options:=options) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC31183: Error in project-level import '<xmlns:p1="http://www.w3.org/2000/xmlns/">' at '"http://www.w3.org/2000/xmlns/"' : Prefix 'p1' cannot be bound to namespace name reserved for 'xmlns'. BC31183: Error in project-level import '<xmlns="http://www.w3.org/XML/1998/namespace">' at '"http://www.w3.org/XML/1998/namespace"' : Prefix '' cannot be bound to namespace name reserved for 'xml'. BC31183: Prefix '' cannot be bound to namespace name reserved for 'xml'. Imports <xmlns="http://www.w3.org/XML/1998/namespace"> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC31183: Prefix 'p2' cannot be bound to namespace name reserved for 'xmlns'. Imports <xmlns:p2="http://www.w3.org/2000/xmlns/"> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC31183: Prefix '' cannot be bound to namespace name reserved for 'xmlns'. xmlns="http://www.w3.org/2000/xmlns/" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC31183: Prefix 'p3' cannot be bound to namespace name reserved for 'xml'. xmlns:p3="http://www.w3.org/XML/1998/namespace"/> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></errors>) End Sub <Fact()> Public Sub BC31184ERR_IllegalDefaultNamespace() Dim options = TestOptions.ReleaseDll.WithGlobalImports(GlobalImport.Parse({"<xmlns="""">", "<xmlns:p="""">"})) Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Imports <xmlns=""> Imports <xmlns:q=""> Module M Private F As Object = <x xmlns="" xmlns:r=""/> End Module ]]></file> </compilation>, references:=XmlReferences, options:=options) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC31184: Namespace declaration with prefix cannot have an empty value inside an XML literal. Private F As Object = <x xmlns="" xmlns:r=""/> ~ ]]></errors>) End Sub <Fact()> Public Sub BC31189ERR_IllegalXmlnsPrefix() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Imports <xmlns:p=""> Imports <xmlns:XMLNS=""> Module M Private F1 As Object = <xmlns/> Private F2 As Object = <xmlns:x/> Private F3 As Object = <p:xmlns/> Private F4 As Object = <XMLNS:x/> Private F5 As Object = <x/>.<xmlns> Private F6 As Object = <x/>.<xmlns:y> Private F7 As Object = <x/>.<p:xmlns> Private F8 As Object = <x/>.<XMLNS:y> Private F9 As Object = <x/>.@xmlns Private F10 As Object = <x/>.@xmlns:z End Module ]]></file> </compilation>, references:=XmlReferences) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC31189: Element names cannot use the 'xmlns' prefix. Private F2 As Object = <xmlns:x/> ~~~~~ BC31189: Element names cannot use the 'xmlns' prefix. Private F6 As Object = <x/>.<xmlns:y> ~~~~~ ]]></errors>) End Sub ' No ref to system.xml.dll <Fact()> Public Sub BC31190ERR_XmlFeaturesNotAvailable() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Module M1 Sub Foo() Dim x = Function() <aoeu> <%= 5 %> <%= (Function() "five")() %> </aoeu> Dim y = Function() <aoeu val=<%= (Function() <htns></htns>)().ToString() %>/> End Sub End Module ]]></file> </compilation>) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC31190: XML literals and XML axis properties are not available. Add references to System.Xml, System.Xml.Linq, and System.Core or other assemblies declaring System.Linq.Enumerable, System.Xml.Linq.XElement, System.Xml.Linq.XName, System.Xml.Linq.XAttribute and System.Xml.Linq.XNamespace types. Dim x = Function() <aoeu> ~~~~~~~ BC31190: XML literals and XML axis properties are not available. Add references to System.Xml, System.Xml.Linq, and System.Core or other assemblies declaring System.Linq.Enumerable, System.Xml.Linq.XElement, System.Xml.Linq.XName, System.Xml.Linq.XAttribute and System.Xml.Linq.XNamespace types. Dim y = Function() <aoeu val=<%= (Function() <htns></htns>)().ToString() %>/> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></errors>) End Sub <Fact()> Public Sub BC31190ERR_XmlFeaturesNotAvailable_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports <xmlns:p="..."> Module M Private A = <a><b><%= <c/> %></b></a> Private B = <a b=<%= <c/> %>/> Private C = <a/>.<b>.<c> Private D = <%= A %> Private E = <%= <x><%= A %></x> %> Private F = <a/>.<a>.<b> Private G = <a b="c"/>.<a>.@b Private H = <a/>...<b> Private J = <!-- comment --> Private K = <?xml version="1.0"?><x/> End Module ]]></file> </compilation>) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC31190: XML literals and XML axis properties are not available. Add references to System.Xml, System.Xml.Linq, and System.Core or other assemblies declaring System.Linq.Enumerable, System.Xml.Linq.XElement, System.Xml.Linq.XName, System.Xml.Linq.XAttribute and System.Xml.Linq.XNamespace types. Private A = <a><b><%= <c/> %></b></a> ~~~~~~~~~~~~~~~~~~~~~~~~~ BC31190: XML literals and XML axis properties are not available. Add references to System.Xml, System.Xml.Linq, and System.Core or other assemblies declaring System.Linq.Enumerable, System.Xml.Linq.XElement, System.Xml.Linq.XName, System.Xml.Linq.XAttribute and System.Xml.Linq.XNamespace types. Private B = <a b=<%= <c/> %>/> ~~~~~~~~~~~~~~~~~~ BC31190: XML literals and XML axis properties are not available. Add references to System.Xml, System.Xml.Linq, and System.Core or other assemblies declaring System.Linq.Enumerable, System.Xml.Linq.XElement, System.Xml.Linq.XName, System.Xml.Linq.XAttribute and System.Xml.Linq.XNamespace types. Private C = <a/>.<b>.<c> ~~~~~~~~~~~~ BC31172: An embedded expression cannot be used here. Private D = <%= A %> ~~~~~~~~ BC31172: An embedded expression cannot be used here. Private E = <%= <x><%= A %></x> %> ~~~~~~~~~~~~~~~~~~~~~~ BC31190: XML literals and XML axis properties are not available. Add references to System.Xml, System.Xml.Linq, and System.Core or other assemblies declaring System.Linq.Enumerable, System.Xml.Linq.XElement, System.Xml.Linq.XName, System.Xml.Linq.XAttribute and System.Xml.Linq.XNamespace types. Private E = <%= <x><%= A %></x> %> ~~~~~~~~~~~~~~~ BC31190: XML literals and XML axis properties are not available. Add references to System.Xml, System.Xml.Linq, and System.Core or other assemblies declaring System.Linq.Enumerable, System.Xml.Linq.XElement, System.Xml.Linq.XName, System.Xml.Linq.XAttribute and System.Xml.Linq.XNamespace types. Private F = <a/>.<a>.<b> ~~~~~~~~~~~~ BC31190: XML literals and XML axis properties are not available. Add references to System.Xml, System.Xml.Linq, and System.Core or other assemblies declaring System.Linq.Enumerable, System.Xml.Linq.XElement, System.Xml.Linq.XName, System.Xml.Linq.XAttribute and System.Xml.Linq.XNamespace types. Private G = <a b="c"/>.<a>.@b ~~~~~~~~~~~~~~~~~ BC31190: XML literals and XML axis properties are not available. Add references to System.Xml, System.Xml.Linq, and System.Core or other assemblies declaring System.Linq.Enumerable, System.Xml.Linq.XElement, System.Xml.Linq.XName, System.Xml.Linq.XAttribute and System.Xml.Linq.XNamespace types. Private H = <a/>...<b> ~~~~~~~~~~ BC31190: XML literals and XML axis properties are not available. Add references to System.Xml, System.Xml.Linq, and System.Core or other assemblies declaring System.Linq.Enumerable, System.Xml.Linq.XElement, System.Xml.Linq.XName, System.Xml.Linq.XAttribute and System.Xml.Linq.XNamespace types. Private J = <!-- comment --> ~~~~~~~~~~~~~~~~ BC31190: XML literals and XML axis properties are not available. Add references to System.Xml, System.Xml.Linq, and System.Core or other assemblies declaring System.Linq.Enumerable, System.Xml.Linq.XElement, System.Xml.Linq.XName, System.Xml.Linq.XAttribute and System.Xml.Linq.XNamespace types. Private K = <?xml version="1.0"?><x/> ~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></errors>) End Sub <Fact()> Public Sub BC31190ERR_XmlFeaturesNotAvailable_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module M Private F1 = &lt;x&gt;&lt;![CDATA[str]]&gt;&lt;/&gt; Private F2 = &lt;![CDATA[str]]&gt; End Module </file> </compilation>) compilation.AssertTheseDiagnostics(<errors> BC31190: XML literals and XML axis properties are not available. Add references to System.Xml, System.Xml.Linq, and System.Core or other assemblies declaring System.Linq.Enumerable, System.Xml.Linq.XElement, System.Xml.Linq.XName, System.Xml.Linq.XAttribute and System.Xml.Linq.XNamespace types. Private F1 = &lt;x&gt;&lt;![CDATA[str]]&gt;&lt;/&gt; ~~~~~~~~~~~~~~~~~~~~~ BC31190: XML literals and XML axis properties are not available. Add references to System.Xml, System.Xml.Linq, and System.Core or other assemblies declaring System.Linq.Enumerable, System.Xml.Linq.XElement, System.Xml.Linq.XName, System.Xml.Linq.XAttribute and System.Xml.Linq.XNamespace types. Private F2 = &lt;![CDATA[str]]&gt; ~~~~~~~~~~~~~~~ </errors>) End Sub <Fact()> Public Sub BC31190ERR_XmlFeaturesNotAvailable_3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Module M Private F = GetXmlNamespace() End Module ]]></file> </compilation>) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC31190: XML literals and XML axis properties are not available. Add references to System.Xml, System.Xml.Linq, and System.Core or other assemblies declaring System.Linq.Enumerable, System.Xml.Linq.XElement, System.Xml.Linq.XName, System.Xml.Linq.XAttribute and System.Xml.Linq.XNamespace types. Private F = GetXmlNamespace() ~~~~~~~~~~~~~~~~~ ]]></errors>) End Sub <Fact()> Public Sub BC42361WRN_UseValueForXmlExpression3() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="a.vb"><![CDATA[ Option Strict Off Imports System.Collections.Generic Imports System.Xml.Linq Class A End Class NotInheritable Class B End Class Module M Sub M(Of T As Class)() Dim _o As Object Dim _s As String Dim _a As A Dim _b As B Dim _t As T _o = <x/>.<y> _o = CType(<x/>.<y>, Object) _o = DirectCast(<x/>.<y>, Object) _o = TryCast(<x/>.<y>, Object) _s = <x/>.<y> _s = CType(<x/>.<y>, String) _s = DirectCast(<x/>.<y>, String) _s = TryCast(<x/>.<y>, String) _a = <x/>.<y> _a = CType(<x/>.<y>, A) _a = DirectCast(<x/>.<y>, A) _a = TryCast(<x/>.<y>, A) _b = <x/>.<y> _b = CType(<x/>.<y>, B) _b = DirectCast(<x/>.<y>, B) _b = TryCast(<x/>.<y>, B) _t = <x/>.<y> _t = CType(<x/>.<y>, T) _t = DirectCast(<x/>.<y>, T) _t = TryCast(<x/>.<y>, T) End Sub End Module ]]></file> </compilation>, references:=XmlReferences) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC42361: Cannot convert 'IEnumerable(Of XElement)' to 'String'. You can use the 'Value' property to get the string value of the first element of 'IEnumerable(Of XElement)'. _s = <x/>.<y> ~~~~~~~~ BC42361: Cannot convert 'IEnumerable(Of XElement)' to 'String'. You can use the 'Value' property to get the string value of the first element of 'IEnumerable(Of XElement)'. _s = CType(<x/>.<y>, String) ~~~~~~~~ BC42361: Cannot convert 'IEnumerable(Of XElement)' to 'String'. You can use the 'Value' property to get the string value of the first element of 'IEnumerable(Of XElement)'. _s = DirectCast(<x/>.<y>, String) ~~~~~~~~ BC42361: Cannot convert 'IEnumerable(Of XElement)' to 'String'. You can use the 'Value' property to get the string value of the first element of 'IEnumerable(Of XElement)'. _s = TryCast(<x/>.<y>, String) ~~~~~~~~ BC42322: Runtime errors might occur when converting 'IEnumerable(Of XElement)' to 'B'. _b = <x/>.<y> ~~~~~~~~ BC42322: Runtime errors might occur when converting 'IEnumerable(Of XElement)' to 'B'. _b = CType(<x/>.<y>, B) ~~~~~~~~ BC42322: Runtime errors might occur when converting 'IEnumerable(Of XElement)' to 'B'. _b = DirectCast(<x/>.<y>, B) ~~~~~~~~ BC42322: Runtime errors might occur when converting 'IEnumerable(Of XElement)' to 'B'. _b = TryCast(<x/>.<y>, B) ~~~~~~~~ ]]></errors>) End Sub ' Same as above but with "Option Strict On". <Fact()> Public Sub BC42361WRN_UseValueForXmlExpression3_1() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports System.Collections.Generic Imports System.Xml.Linq Class A End Class NotInheritable Class B End Class Module M Sub M(Of T As Class)() Dim _o As Object Dim _s As String Dim _a As A Dim _b As B Dim _t As T _o = <x/>.<y> _o = CType(<x/>.<y>, Object) _o = DirectCast(<x/>.<y>, Object) _o = TryCast(<x/>.<y>, Object) _s = <x/>.<y> _s = CType(<x/>.<y>, String) _s = DirectCast(<x/>.<y>, String) _s = TryCast(<x/>.<y>, String) _a = <x/>.<y> _a = CType(<x/>.<y>, A) _a = DirectCast(<x/>.<y>, A) _a = TryCast(<x/>.<y>, A) _b = <x/>.<y> _b = CType(<x/>.<y>, B) _b = DirectCast(<x/>.<y>, B) _b = TryCast(<x/>.<y>, B) _t = <x/>.<y> _t = CType(<x/>.<y>, T) _t = DirectCast(<x/>.<y>, T) _t = TryCast(<x/>.<y>, T) End Sub End Module ]]></file> </compilation>, references:=XmlReferences) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC30512: Option Strict On disallows implicit conversions from 'IEnumerable(Of XElement)' to 'String'. _s = <x/>.<y> ~~~~~~~~ BC42361: Cannot convert 'IEnumerable(Of XElement)' to 'String'. You can use the 'Value' property to get the string value of the first element of 'IEnumerable(Of XElement)'. _s = <x/>.<y> ~~~~~~~~ BC42361: Cannot convert 'IEnumerable(Of XElement)' to 'String'. You can use the 'Value' property to get the string value of the first element of 'IEnumerable(Of XElement)'. _s = CType(<x/>.<y>, String) ~~~~~~~~ BC42361: Cannot convert 'IEnumerable(Of XElement)' to 'String'. You can use the 'Value' property to get the string value of the first element of 'IEnumerable(Of XElement)'. _s = DirectCast(<x/>.<y>, String) ~~~~~~~~ BC42361: Cannot convert 'IEnumerable(Of XElement)' to 'String'. You can use the 'Value' property to get the string value of the first element of 'IEnumerable(Of XElement)'. _s = TryCast(<x/>.<y>, String) ~~~~~~~~ BC30512: Option Strict On disallows implicit conversions from 'IEnumerable(Of XElement)' to 'A'. _a = <x/>.<y> ~~~~~~~~ BC30512: Option Strict On disallows implicit conversions from 'IEnumerable(Of XElement)' to 'B'. _b = <x/>.<y> ~~~~~~~~ BC42322: Runtime errors might occur when converting 'IEnumerable(Of XElement)' to 'B'. _b = <x/>.<y> ~~~~~~~~ BC42322: Runtime errors might occur when converting 'IEnumerable(Of XElement)' to 'B'. _b = CType(<x/>.<y>, B) ~~~~~~~~ BC42322: Runtime errors might occur when converting 'IEnumerable(Of XElement)' to 'B'. _b = DirectCast(<x/>.<y>, B) ~~~~~~~~ BC42322: Runtime errors might occur when converting 'IEnumerable(Of XElement)' to 'B'. _b = TryCast(<x/>.<y>, B) ~~~~~~~~ BC30512: Option Strict On disallows implicit conversions from 'IEnumerable(Of XElement)' to 'T'. _t = <x/>.<y> ~~~~~~~~ ]]></errors>) End Sub <Fact()> Public Sub BC42361WRN_UseValueForXmlExpression3_2() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="a.vb"><![CDATA[ Option Strict Off Imports System.Collections.Generic Imports System.Xml.Linq Class X Inherits XElement Public Sub New(name As XName) MyBase.New(name) End Sub End Class Interface IEnumerableOfXElement Inherits IEnumerable(Of XElement) End Interface Module M Sub M(Of T As XElement)(_1 As XElement, _2 As IEnumerable(Of XElement), _3 As XElement(), _4 As List(Of XElement), _5 As IEnumerable(Of XObject), _6 As IEnumerable(Of XElement)(), _7 As IEnumerableOfXElement, _8 As IEnumerable(Of X), _9 As IEnumerable(Of T)) Dim o As String o = _1 o = _2 o = _3 o = _4 o = _5 o = _6 o = _7 o = _8 o = _9 End Sub End Module ]]></file> </compilation>, references:=XmlReferences) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC42361: Cannot convert 'IEnumerable(Of XElement)' to 'String'. You can use the 'Value' property to get the string value of the first element of 'IEnumerable(Of XElement)'. o = _2 ~~ BC30311: Value of type 'XElement()' cannot be converted to 'String'. o = _3 ~~ BC30311: Value of type 'List(Of XElement)' cannot be converted to 'String'. o = _4 ~~ BC42322: Runtime errors might occur when converting 'IEnumerable(Of XObject)' to 'String'. o = _5 ~~ BC30311: Value of type 'IEnumerable(Of XElement)()' cannot be converted to 'String'. o = _6 ~~ BC42361: Cannot convert 'IEnumerableOfXElement' to 'String'. You can use the 'Value' property to get the string value of the first element of 'IEnumerableOfXElement'. o = _7 ~~ BC42361: Cannot convert 'IEnumerable(Of X)' to 'String'. You can use the 'Value' property to get the string value of the first element of 'IEnumerable(Of X)'. o = _8 ~~ BC42361: Cannot convert 'IEnumerable(Of T As XElement)' to 'String'. You can use the 'Value' property to get the string value of the first element of 'IEnumerable(Of T As XElement)'. o = _9 ~~ ]]></errors>) End Sub ' Conversions to IEnumerable(Of XElement). Dev11 reports BC31193 ' when converting NotInheritable Class to IEnumerable(Of XElement). <Fact()> Public Sub BC42361WRN_UseValueForXmlExpression3_3() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="a.vb"><![CDATA[ Option Strict Off Imports System.Collections.Generic Imports System.Xml.Linq Class A End Class NotInheritable Class B End Class Module M Sub M(Of T As Class)() Dim _i As IEnumerable(Of XElement) Dim _o As Object = Nothing Dim _s As String = Nothing Dim _a As A = Nothing Dim _b As B = Nothing Dim _t As T = Nothing _i = _o _i = _s _i = _a _i = _b _i = _t End Sub End Module ]]></file> </compilation>, references:=XmlReferences) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC42322: Runtime errors might occur when converting 'String' to 'IEnumerable(Of XElement)'. _i = _s ~~ BC42322: Runtime errors might occur when converting 'B' to 'IEnumerable(Of XElement)'. _i = _b ~~ ]]></errors>) End Sub <Fact()> Public Sub BC31194ERR_TypeMismatchForXml3() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Option Strict Off Structure S End Structure Module M Sub M() Dim _s As S _s = <x/>.<y> _s = CType(<x/>.<y>, S) _s = DirectCast(<x/>.<y>, S) End Sub End Module ]]></file> </compilation>, references:=XmlReferences) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC31194: Value of type 'IEnumerable(Of XElement)' cannot be converted to 'S'. You can use the 'Value' property to get the string value of the first element of 'IEnumerable(Of XElement)'. _s = <x/>.<y> ~~~~~~~~ BC31194: Value of type 'IEnumerable(Of XElement)' cannot be converted to 'S'. You can use the 'Value' property to get the string value of the first element of 'IEnumerable(Of XElement)'. _s = CType(<x/>.<y>, S) ~~~~~~~~ BC31194: Value of type 'IEnumerable(Of XElement)' cannot be converted to 'S'. You can use the 'Value' property to get the string value of the first element of 'IEnumerable(Of XElement)'. _s = DirectCast(<x/>.<y>, S) ~~~~~~~~ ]]></errors>) End Sub <Fact()> Public Sub BC31194ERR_TypeMismatchForXml3_1() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Option Strict Off Imports System.Collections.Generic Imports System.Xml.Linq Structure S End Structure Class X Inherits XElement Public Sub New(name As XName) MyBase.New(name) End Sub End Class Interface IEnumerableOfXElement Inherits IEnumerable(Of XElement) End Interface Module M Sub M(Of T As XElement)(_1 As XElement, _2 As IEnumerable(Of XElement), _3 As XElement(), _4 As List(Of XElement), _5 As IEnumerable(Of XObject), _6 As IEnumerable(Of XElement)(), _7 As IEnumerableOfXElement, _8 As IEnumerable(Of X), _9 As IEnumerable(Of T)) Dim o As S o = _1 o = _2 o = _3 o = _4 o = _5 o = _6 o = _7 o = _8 o = _9 End Sub End Module ]]></file> </compilation>, references:=XmlReferences) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC30311: Value of type 'XElement' cannot be converted to 'S'. o = _1 ~~ BC31194: Value of type 'IEnumerable(Of XElement)' cannot be converted to 'S'. You can use the 'Value' property to get the string value of the first element of 'IEnumerable(Of XElement)'. o = _2 ~~ BC30311: Value of type 'XElement()' cannot be converted to 'S'. o = _3 ~~ BC30311: Value of type 'List(Of XElement)' cannot be converted to 'S'. o = _4 ~~ BC30311: Value of type 'IEnumerable(Of XObject)' cannot be converted to 'S'. o = _5 ~~ BC30311: Value of type 'IEnumerable(Of XElement)()' cannot be converted to 'S'. o = _6 ~~ BC31194: Value of type 'IEnumerableOfXElement' cannot be converted to 'S'. You can use the 'Value' property to get the string value of the first element of 'IEnumerableOfXElement'. o = _7 ~~ BC31194: Value of type 'IEnumerable(Of X)' cannot be converted to 'S'. You can use the 'Value' property to get the string value of the first element of 'IEnumerable(Of X)'. o = _8 ~~ BC31194: Value of type 'IEnumerable(Of T As XElement)' cannot be converted to 'S'. You can use the 'Value' property to get the string value of the first element of 'IEnumerable(Of T As XElement)'. o = _9 ~~ ]]></errors>) End Sub <Fact()> Public Sub BC31195ERR_BinaryOperandsForXml4() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Option Strict Off Imports System.Collections.Generic Imports System.Xml.Linq Class C End Class Class X Inherits XElement Public Sub New(name As XName) MyBase.New(name) End Sub End Class Interface IEnumerableOfXElement Inherits IEnumerable(Of XElement) End Interface Module M Sub M(Of T As XElement)(o As C, _1 As XElement, _2 As IEnumerable(Of XElement), _3 As XElement(), _4 As List(Of XElement), _5 As IEnumerable(Of XObject), _6 As IEnumerable(Of XElement)(), _7 As IEnumerableOfXElement, _8 As IEnumerable(Of X), _9 As IEnumerable(Of T)) Dim b As Boolean b = (o = _1) b = (o = _2) b = (o = _3) b = (o = _4) b = (_5 = o) b = (_6 = o) b = (_7 = o) b = (_8 = o) b = (_9 = o) b = (_1 = _2) b = (_2 = _2) b = (_3 = _2) b = (_4 = _2) b = (_5 = _2) b = (_2 = _6) b = (_2 = _7) b = (_2 = _8) b = (_2 = _9) End Sub End Module ]]></file> </compilation>, references:=XmlReferences) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC30452: Operator '=' is not defined for types 'C' and 'XElement'. b = (o = _1) ~~~~~~ BC31195: Operator '=' is not defined for types 'C' and 'IEnumerable(Of XElement)'. You can use the 'Value' property to get the string value of the first element of 'IEnumerable(Of XElement)'. b = (o = _2) ~~~~~~ BC31195: Operator '=' is not defined for types 'C' and 'XElement()'. You can use the 'Value' property to get the string value of the first element of 'XElement()'. b = (o = _3) ~~~~~~ BC31195: Operator '=' is not defined for types 'C' and 'List(Of XElement)'. You can use the 'Value' property to get the string value of the first element of 'List(Of XElement)'. b = (o = _4) ~~~~~~ BC30452: Operator '=' is not defined for types 'IEnumerable(Of XObject)' and 'C'. b = (_5 = o) ~~~~~~ BC30452: Operator '=' is not defined for types 'IEnumerable(Of XElement)()' and 'C'. b = (_6 = o) ~~~~~~ BC31195: Operator '=' is not defined for types 'IEnumerableOfXElement' and 'C'. You can use the 'Value' property to get the string value of the first element of 'IEnumerableOfXElement'. b = (_7 = o) ~~~~~~ BC31195: Operator '=' is not defined for types 'IEnumerable(Of X)' and 'C'. You can use the 'Value' property to get the string value of the first element of 'IEnumerable(Of X)'. b = (_8 = o) ~~~~~~ BC31195: Operator '=' is not defined for types 'IEnumerable(Of T As XElement)' and 'C'. You can use the 'Value' property to get the string value of the first element of 'IEnumerable(Of T As XElement)'. b = (_9 = o) ~~~~~~ BC31195: Operator '=' is not defined for types 'XElement' and 'IEnumerable(Of XElement)'. You can use the 'Value' property to get the string value of the first element of 'IEnumerable(Of XElement)'. b = (_1 = _2) ~~~~~~~ BC31080: Operator '=' is not defined for types 'IEnumerable(Of XElement)' and 'IEnumerable(Of XElement)'. Use 'Is' operator to compare two reference types. b = (_2 = _2) ~~~~~~~ BC31080: Operator '=' is not defined for types 'XElement()' and 'IEnumerable(Of XElement)'. Use 'Is' operator to compare two reference types. b = (_3 = _2) ~~~~~~~ BC31195: Operator '=' is not defined for types 'List(Of XElement)' and 'IEnumerable(Of XElement)'. You can use the 'Value' property to get the string value of the first element of 'List(Of XElement)'. b = (_4 = _2) ~~~~~~~ BC31080: Operator '=' is not defined for types 'IEnumerable(Of XObject)' and 'IEnumerable(Of XElement)'. Use 'Is' operator to compare two reference types. b = (_5 = _2) ~~~~~~~ BC31080: Operator '=' is not defined for types 'IEnumerable(Of XElement)' and 'IEnumerable(Of XElement)()'. Use 'Is' operator to compare two reference types. b = (_2 = _6) ~~~~~~~ BC31080: Operator '=' is not defined for types 'IEnumerable(Of XElement)' and 'IEnumerableOfXElement'. Use 'Is' operator to compare two reference types. b = (_2 = _7) ~~~~~~~ BC31080: Operator '=' is not defined for types 'IEnumerable(Of XElement)' and 'IEnumerable(Of X)'. Use 'Is' operator to compare two reference types. b = (_2 = _8) ~~~~~~~ BC31080: Operator '=' is not defined for types 'IEnumerable(Of XElement)' and 'IEnumerable(Of T As XElement)'. Use 'Is' operator to compare two reference types. b = (_2 = _9) ~~~~~~~ ]]></errors>) End Sub <Fact()> Public Sub BC31394ERR_RestrictedConversion1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="RestrictedConversion1"> <file name="a.vb"> Class C1 Sub FOO() Dim obj As Object obj = New system.ArgIterator End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC31394: Expression of type 'ArgIterator' cannot be converted to 'Object' or 'ValueType'. obj = New system.ArgIterator ~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <WorkItem(527685, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527685")> <Fact()> Public Sub BC31394ERR_RestrictedConversion1_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="RestrictedConversion1_1"> <file name="a.vb"> Option Infer Off imports system Structure C1 Sub FOO() Dim obj = New ArgIterator Dim TypeRefInstance As TypedReference obj = TypeRefInstance End Sub End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC31394: Expression of type 'ArgIterator' cannot be converted to 'Object' or 'ValueType'. Dim obj = New ArgIterator ~~~~~~~~~~~~~~~ BC31394: Expression of type 'TypedReference' cannot be converted to 'Object' or 'ValueType'. obj = TypeRefInstance ~~~~~~~~~~~~~~~ BC42109: Variable 'TypeRefInstance' is used before it has been assigned a value. A null reference exception could result at runtime. Make sure the structure or all the reference members are initialized before use obj = TypeRefInstance ~~~~~~~~~~~~~~~ </expected>) End Sub <WorkItem(527685, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527685")> <Fact()> Public Sub BC31394ERR_RestrictedConversion1_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="RestrictedConversion1"> <file name="a.vb"> Option Infer Off imports system Structure C1 Sub FOO() Dim obj = New ArgIterator obj = New RuntimeArgumentHandle End Sub End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC31394: Expression of type 'ArgIterator' cannot be converted to 'Object' or 'ValueType'. Dim obj = New ArgIterator ~~~~~~~~~~~~~~~ BC31394: Expression of type 'RuntimeArgumentHandle' cannot be converted to 'Object' or 'ValueType'. obj = New RuntimeArgumentHandle ~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact(), WorkItem(529561, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529561")> Public Sub BC31396ERR_RestrictedType1_1() CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Module M Sub Main() Dim x As TypedReference() Dim y() As ArgIterator Dim z = {New RuntimeArgumentHandle()} End Sub End Module </file> </compilation>).AssertTheseDiagnostics( <expected> BC42024: Unused local variable: 'x'. Dim x As TypedReference() ~ BC31396: 'TypedReference' 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 As TypedReference() ~~~~~~~~~~~~~~~~ BC42024: Unused local variable: 'y'. Dim 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 ArgIterator ~~~~~~~~~~~ BC31396: 'RuntimeArgumentHandle' 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 = {New RuntimeArgumentHandle()} ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC31396: 'RuntimeArgumentHandle' 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 = {New RuntimeArgumentHandle()} ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC31396ERR_RestrictedType1_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System Class C(Of T) Shared Sub F(Of U)(o As U) End Sub Shared Sub M() Dim o As Object o = New C(Of ArgIterator) o = New C(Of RuntimeArgumentHandle) o = New C(Of TypedReference) F(Of ArgIterator)(Nothing) F(Of RuntimeArgumentHandle)(Nothing) Dim t As TypedReference = Nothing F(t) End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> 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. o = New C(Of ArgIterator) ~~~~~~~~~~~ BC31396: 'RuntimeArgumentHandle' 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. o = New C(Of RuntimeArgumentHandle) ~~~~~~~~~~~~~~~~~~~~~ BC31396: 'TypedReference' 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. o = New C(Of TypedReference) ~~~~~~~~~~~~~~ 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. F(Of ArgIterator)(Nothing) ~~~~~~~~~~~~~~~~~ BC31396: 'RuntimeArgumentHandle' 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. F(Of RuntimeArgumentHandle)(Nothing) ~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC31396: 'TypedReference' 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. F(t) ~ </expected>) End Sub <Fact()> Public Sub BC31396ERR_RestrictedType1_3() CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Class C Private F As TypedReference Private G As ArgIterator() Private H = {New RuntimeArgumentHandle()} Sub M(e As ArgIterator()) End Sub End Class Interface I ReadOnly Property P As TypedReference Function F() As ArgIterator()() Property Q As RuntimeArgumentHandle()() End Interface </file> </compilation>).AssertTheseDiagnostics( <expected> BC31396: 'TypedReference' 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. Private F As TypedReference ~~~~~~~~~~~~~~ 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. Private G As ArgIterator() ~~~~~~~~~~~~~ BC31396: 'RuntimeArgumentHandle' 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. Private H = {New RuntimeArgumentHandle()} ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 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(e As ArgIterator()) ~~~~~~~~~~~~~ BC31396: 'TypedReference' 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. ReadOnly Property P As TypedReference ~~~~~~~~~~~~~~ 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. Function F() As ArgIterator()() ~~~~~~~~~~~~~~~ BC31396: 'RuntimeArgumentHandle' 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. Property Q As RuntimeArgumentHandle()() ~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC31399ERR_NoAccessibleConstructorOnBase() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="NoAccessibleConstructorOnBase"> <file name="a.vb"> Class c1 Private Sub New() End Sub End Class Class c2 Inherits c1 End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC31399: Class 'c1' has no accessible 'Sub New' and cannot be inherited. Class c2 ~~ </expected>) End Sub <Fact()> Public Sub BC31419ERR_IsNotOpRequiresReferenceTypes1() CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class A1 Sub scen1() dim arr1 = New Integer() {1, 2, 3} dim arr2 = arr1 Dim b As Boolean b = arr1(0) IsNot arr2(0) End Sub End Class </file> </compilation>).VerifyDiagnostics( Diagnostic(ERRID.ERR_IsNotOpRequiresReferenceTypes1, "arr1(0)").WithArguments("Integer"), Diagnostic(ERRID.ERR_IsNotOpRequiresReferenceTypes1, "arr2(0)").WithArguments("Integer")) End Sub <Fact()> Public Sub BC31419ERR_IsNotOpRequiresReferenceTypes1_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class A1 Sub scen1() Dim a As E Dim b As S1 dim o = a IsNot b End Sub End Class structure S1 End structure ENUM E Dummy End ENUM </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC31419: 'IsNot' requires operands that have reference types, but this operand has the value type 'E'. dim o = a IsNot b ~ BC31419: 'IsNot' requires operands that have reference types, but this operand has the value type 'S1'. dim o = a IsNot b ~ </expected>) End Sub <Fact()> Public Sub BC31419ERR_IsNotOpRequiresReferenceTypes1_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Interface I End Interface Class A End Class Class B(Of T As Structure) End Class Class C Shared Sub M1(Of T1)(_1 As T1) If _1 IsNot Nothing Then End If If Nothing IsNot _1 Then End If End Sub Shared Sub M2(Of T2 As Class)(_2 As T2) If _2 IsNot Nothing Then End If If Nothing IsNot _2 Then End If End Sub Shared Sub M3(Of T3 As Structure)(_3 As T3) If _3 IsNot Nothing Then End If If Nothing IsNot _3 Then End If End Sub Shared Sub M4(Of T4 As New)(_4 As T4) If _4 IsNot Nothing Then End If If Nothing IsNot _4 Then End If End Sub Shared Sub M5(Of T5 As I)(_5 As T5) If _5 IsNot Nothing Then End If If Nothing IsNot _5 Then End If End Sub Shared Sub M6(Of T6 As A)(_6 As T6) If _6 IsNot Nothing Then End If If Nothing IsNot _6 Then End If End Sub Shared Sub M7(Of T7 As U, U)(_7 As T7) If _7 IsNot Nothing Then End If If Nothing IsNot _7 Then End If End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC31419: 'IsNot' requires operands that have reference types, but this operand has the value type 'T3'. If _3 IsNot Nothing Then ~~ BC31419: 'IsNot' requires operands that have reference types, but this operand has the value type 'T3'. If Nothing IsNot _3 Then ~~ </expected>) End Sub <WorkItem(542192, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542192")> <Fact()> Public Sub BC31428ERR_VoidArrayDisallowed() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="VoidArrayDisallowed"> <file name="a.vb"> Imports System Module M1 Dim y As Type = GetType(Void) Dim x As Type = GetType(Void()) End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC31428: Arrays of type 'System.Void' are not allowed in this expression. Dim x As Type = GetType(Void()) ~~~~~~ </expected>) End Sub <Fact()> Public Sub PartialMethodAndDeclareMethod() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Imports System.Runtime.InteropServices Partial Class Clazz Partial Private Declare Sub S0 Lib "abc.dll" (p As String) Partial Private Sub S1(&lt;Out> p As String) End Sub Partial Private Sub S2(&lt;Out> ByRef p As String) End Sub End Class Partial Class Clazz Private Declare Sub S1 Lib "abc.dll" (p As String) End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30244: 'Partial' is not valid on a Declare. Partial Private Declare Sub S0 Lib "abc.dll" (p As String) ~~~~~~~ BC30345: 'Private Sub S1(p As String)' and 'Private Declare Ansi Sub S1 Lib "abc.dll" (p As String)' cannot overload each other because they differ only by parameters declared 'ByRef' or 'ByVal'. Partial Private Sub S1(&lt;Out> p As String) ~~ </expected>) End Sub <Fact()> Public Sub BC31435ERR_PartialMethodMustBeEmpty() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="PartialMethodMustBeEmpty"> <file name="a.vb"> Class C1 Partial Private Sub Foo() System.Console.WriteLine() End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC31435: Partial methods must have empty method bodies. Partial Private Sub Foo() ~~~ </expected>) End Sub <Fact()> Public Sub BC31435ERR_PartialMethodMustBeEmpty2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="PartialMethodMustBeEmpty2"> <file name="a.vb"> Imports System Class C1 Partial Private Shared Sub PS(a As Integer) Console.WriteLine() End Sub Partial Private Shared Sub Ps(a As Integer) Console.WriteLine() End Sub Private Shared Sub PS(a As Integer) End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC31435: Partial methods must have empty method bodies. Partial Private Shared Sub PS(a As Integer) ~~ BC31433: Method 'Ps' cannot be declared 'Partial' because only one method 'Ps' can be marked 'Partial'. Partial Private Shared Sub Ps(a As Integer) ~~ </expected>) End Sub <Fact()> Public Sub BC31435ERR_PartialMethodMustBeEmpty3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="PartialMethodMustBeEmpty3"> <file name="a.vb"> Imports System Class C1 Partial Private Shared Sub PS(a As Integer) End Sub Partial Private Shared Sub Ps(a As Integer) Console.WriteLine() End Sub Private Shared Sub PS(a As Integer) End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC31433: Method 'Ps' cannot be declared 'Partial' because only one method 'Ps' can be marked 'Partial'. Partial Private Shared Sub Ps(a As Integer) ~~ </expected>) End Sub <Fact()> Public Sub BC31440ERR_NoPartialMethodInAddressOf1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="NoPartialMethodInAddressOf1"> <file name="a.vb"> Public Class C1 Event x() Partial Private Sub Foo() End Sub Sub MethodToAddHandlerInPrivatePartial() AddHandler Me.x, AddressOf Me.Foo End Sub Sub MethodToRemoveHandlerInPrivatePartial() RemoveHandler Me.x, AddressOf Me.Foo End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC31440: 'AddressOf' cannot be applied to 'Private Sub Foo()' because 'Private Sub Foo()' is a partial method without an implementation. AddHandler Me.x, AddressOf Me.Foo ~~~~~~ BC31440: 'AddressOf' cannot be applied to 'Private Sub Foo()' because 'Private Sub Foo()' is a partial method without an implementation. RemoveHandler Me.x, AddressOf Me.Foo ~~~~~~ </expected>) End Sub ' Roslyn extra - ERR_TypeMismatch2 * 2 <Fact()> Public Sub BC31440ERR_NoPartialMethodInAddressOf1a() CreateCompilationWithMscorlib40( <compilation name="NoPartialMethodInAddressOf1a"> <file name="a.vb"> Imports System Public Class C1 Event x() Partial Private Sub Foo() End Sub Sub MethodToAddHandlerInPrivatePartial() AddHandler Me.x, New Action(AddressOf Me.Foo) End Sub Sub MethodToRemoveHandlerInPrivatePartial() RemoveHandler Me.x, New Action(AddressOf Me.Foo) End Sub End Class </file> </compilation>).VerifyDiagnostics( Diagnostic(ERRID.ERR_NoPartialMethodInAddressOf1, "Me.Foo").WithArguments("Private Sub Foo()"), Diagnostic(ERRID.ERR_TypeMismatch2, "New Action(AddressOf Me.Foo)").WithArguments("System.Action", "C1.xEventHandler"), Diagnostic(ERRID.ERR_NoPartialMethodInAddressOf1, "Me.Foo").WithArguments("Private Sub Foo()"), Diagnostic(ERRID.ERR_TypeMismatch2, "New Action(AddressOf Me.Foo)").WithArguments("System.Action", "C1.xEventHandler")) End Sub <Fact()> Public Sub BC31440ERR_NoPartialMethodInAddressOf1b() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="NoPartialMethodInAddressOf1b"> <file name="a.vb"> Imports System Public Class C1 Sub Test() Dim a As Action = New Action(AddressOf Me.Foo) a() End Sub Partial Private Sub Foo() End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC31440: 'AddressOf' cannot be applied to 'Private Sub Foo()' because 'Private Sub Foo()' is a partial method without an implementation. Dim a As Action = New Action(AddressOf Me.Foo) ~~~~~~ </expected>) End Sub <Fact()> Public Sub BC31500ERR_BadAttributeSharedProperty1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BadAttributeSharedProperty1"> <file name="at31500.vb"><![CDATA[ Imports System <AttributeUsage(AttributeTargets.All)> Public Class MyAttribute Inherits Attribute Public Shared SharedField As String Public Const ConstField As String = "AAA" End Class <My(SharedField:="testing")> Class Foo <My(ConstField:="testing")> Public Sub S() End Sub End Class ]]></file> </compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_BadAttributeSharedProperty1, "SharedField").WithArguments("SharedField"), Diagnostic(ERRID.ERR_BadAttributeSharedProperty1, "ConstField").WithArguments("ConstField")) ' Dev10: 31510 End Sub ''' BC31510 in DEV10 but is BC31500 in Roslyn <Fact()> Public Sub BC31500ERR_BadAttributeSharedProperty1_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BadAttributeConstField1"> <file name="a.vb"> Imports System &lt;AttributeUsage(AttributeTargets.All)&gt; Class attr Inherits Attribute Public Const c As String = "A" End Class &lt;attr(c:="test")&gt; Class c8 End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC31500: 'Shared' attribute property 'c' cannot be the target of an assignment. &lt;attr(c:="test")&gt; Class c8 ~ </expected>) End Sub <Fact()> Public Sub BC31501ERR_BadAttributeReadOnlyProperty1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BadAttributeReadOnlyProperty1"> <file name="at31501.vb"><![CDATA[ Imports System <AttributeUsage(AttributeTargets.All)> Public Class MyAttribute Inherits Attribute Public ReadOnly Property RP As String Get Return "RP" End Get End Property Public WriteOnly Property WP As Integer Set(value As Integer) End Set End Property End Class <MyAttribute(WP:=123, RP:="123")> Class Test End Class ]]></file> </compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_BadAttributeReadOnlyProperty1, "RP").WithArguments("RP")) End Sub Private Shared ReadOnly s_badAttributeIl As String = <![CDATA[ .class public auto ansi beforefieldinit BaseAttribute extends [mscorlib]System.Attribute { .custom instance void [mscorlib]System.AttributeUsageAttribute::.ctor(valuetype [mscorlib]System.AttributeTargets) = ( 01 00 FF 7F 00 00 00 00 ) .method public hidebysig newslot specialname virtual instance int32 get_PROP() cil managed { // Code size 2 (0x2) .maxstack 8 IL_0000: ldc.i4.1 IL_0001: ret } // end of method BaseAttribute::get_PROP .method public hidebysig newslot specialname virtual instance void set_PROP(int32 'value') cil managed { // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method BaseAttribute::set_PROP .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Attribute::.ctor() IL_0006: ret } // end of method BaseAttribute::.ctor .property instance int32 PROP() { .get instance int32 BaseAttribute::get_PROP() .set instance void BaseAttribute::set_PROP(int32) } // end of property BaseAttribute::PROP } // end of class BaseAttribute .class public auto ansi beforefieldinit DerivedAttribute extends BaseAttribute { .method public hidebysig specialname virtual instance int32 get_PROP() cil managed { // Code size 2 (0x2) .maxstack 8 IL_0000: ldc.i4.1 IL_0001: ret } // end of method DerivedAttribute::get_PROP .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void BaseAttribute::.ctor() IL_0006: ret } // end of method DerivedAttribute::.ctor .property instance int32 PROP() { .get instance int32 DerivedAttribute::get_PROP() } // end of property DerivedAttribute::PROP } // end of class DerivedAttribute ]]>.Value.Replace(vbLf, vbNewLine) <WorkItem(528981, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528981")> <Fact()> Public Sub BC31501ERR_BadAttributeReadOnlyProperty2() Dim compilation = CompilationUtils.CreateCompilationWithCustomILSource( <compilation name="BadAttributeReadOnlyProperty2"> <file name="at31501.vb"><![CDATA[ <Derived(PROP:=1)> Class Test End Class ]]></file> </compilation>, s_badAttributeIl).VerifyDiagnostics(Diagnostic(ERRID.ERR_BadAttributeReadOnlyProperty1, "PROP").WithArguments("PROP")) End Sub <WorkItem(540627, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540627")> <Fact()> Public Sub BC31511ERR_BadAttributeNonPublicProperty1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BadAttributeNonPublicProperty1"> <file name="at31511.vb"><![CDATA[ Imports System <AttributeUsage(AttributeTargets.All)> Public Class MyAttribute Inherits Attribute Friend Field As String Friend Property Prop As Long End Class <My(Field:="testing")> Class Foo <My(Prop:=12345)> Public Sub S() End Sub End Class ]]></file> </compilation>).VerifyDiagnostics( Diagnostic(ERRID.ERR_BadAttributeNonPublicProperty1, "Field").WithArguments("Field"), Diagnostic(ERRID.ERR_BadAttributeNonPublicProperty1, "Prop").WithArguments("Prop") ) End Sub <WorkItem(539101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539101")> <Fact()> Public Sub BC32000ERR_UseOfLocalBeforeDeclaration1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="LocalVariableCannotBeReferredToBeforeItIsDeclared"> <file name="a.vb"> Imports System Module X Sub foo() Dim x as integer x = y dim y as integer = 1 End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC32000: Local variable 'y' cannot be referred to before it is declared. x = y ~ </expected>) End Sub <Fact()> Public Sub BC32001ERR_UseOfKeywordFromModule1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="UseOfKeywordFromModule1"> <file name="a.vb"> Imports System Module X Sub foo() Dim o = Me dim p = MyBase.GetType End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC32001: 'Me' is not valid within a Module. Dim o = Me ~~ BC32001: 'MyBase' is not valid within a Module. dim p = MyBase.GetType ~~~~~~ </expected>) End Sub <WorkItem(542958, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542958")> <Fact()> Public Sub BC32001ERR_UseOfKeywordFromModule1_MeAsAttributeInModule() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="UseOfKeywordFromModule1_MeAsAttributeInModule"> <file name="a.vb"> Option Strict On Imports System Imports System.Runtime.InteropServices Public Module S1 &lt;MyAttribute(Me.color1.blue)&gt; Property name As String Sub foo() End Sub Sub main() End Sub Enum color1 blue End Enum End Module Class MyAttribute Inherits Attribute Sub New(x As S1.color1) End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC32001: 'Me' is not valid within a Module. &lt;MyAttribute(Me.color1.blue)&gt; ~~ </expected>) End Sub <WorkItem(542960, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542960")> <Fact()> Public Sub BC32001ERR_UseOfKeywordFromModule1_MyBaseAsAttributeInModule() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="UseOfKeywordFromModule1_MyBaseAsAttributeInModule"> <file name="a.vb"> Option Strict On Imports System Imports System.Runtime.InteropServices Public Module S1 &lt;MyAttribute(MyBase.color1.blue)&gt; Property name As String Sub foo() End Sub Sub main() End Sub Enum color1 blue End Enum End Module Class MyAttribute Inherits Attribute Sub New(x As S1.color1) End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC32001: 'MyBase' is not valid within a Module. &lt;MyAttribute(MyBase.color1.blue)&gt; ~~~~~~ </expected>) End Sub <Fact()> Public Sub BC32006ERR_CharToIntegralTypeMismatch1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="CharToIntegralTypeMismatch1"> <file name="a.vb"> Class C1 SUB scen1() Dim char1() As Char Dim bt(2) As Byte bt(0) = CType (char1(0), Byte) Dim char2() As Char Dim sht1(2) As Short sht1(0) = char2(0) sht1(0) = CType (char2(0), Short) End SUB End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42104: Variable 'char1' is used before it has been assigned a value. A null reference exception could result at runtime. bt(0) = CType (char1(0), Byte) ~~~~~ BC32006: 'Char' values cannot be converted to 'Byte'. Use 'Microsoft.VisualBasic.AscW' to interpret a character as a Unicode value or 'Microsoft.VisualBasic.Val' to interpret it as a digit. bt(0) = CType (char1(0), Byte) ~~~~~~~~ BC42104: Variable 'char2' is used before it has been assigned a value. A null reference exception could result at runtime. sht1(0) = char2(0) ~~~~~ BC32006: 'Char' values cannot be converted to 'Short'. Use 'Microsoft.VisualBasic.AscW' to interpret a character as a Unicode value or 'Microsoft.VisualBasic.Val' to interpret it as a digit. sht1(0) = char2(0) ~~~~~~~~ BC32006: 'Char' values cannot be converted to 'Short'. Use 'Microsoft.VisualBasic.AscW' to interpret a character as a Unicode value or 'Microsoft.VisualBasic.Val' to interpret it as a digit. sht1(0) = CType (char2(0), Short) ~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC32006ERR_CharToIntegralTypeMismatch1_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndReferences( <compilation name="CharToIntegralTypeMismatch1"> <file name="a.vb"> Imports System.Linq Class C Shared Sub Main() For Each x As Integer In From c In "abc" Select c Next End Sub End Class Public Structure S End Structure </file> </compilation>, {Net40.SystemCore}) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC32006: 'Char' values cannot be converted to 'Integer'. Use 'Microsoft.VisualBasic.AscW' to interpret a character as a Unicode value or 'Microsoft.VisualBasic.Val' to interpret it as a digit. For Each x As Integer In From c In "abc" Select c ~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC32007ERR_IntegralToCharTypeMismatch1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="CharToIntegralTypeMismatch1"> <file name="a.vb"> Imports System Module X Sub Foo() Dim O As Object 'COMPILEERROR: BC32007, "CUShort(15)" O = CChar(CUShort(15)) Dim sb As UShort = CUShort(1) 'COMPILEERROR: BC32007, "sb" O = CChar(sb) End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC32007: 'UShort' values cannot be converted to 'Char'. Use 'Microsoft.VisualBasic.ChrW' to interpret a numeric value as a Unicode character or first convert it to 'String' to produce a digit. O = CChar(CUShort(15)) ~~~~~~~~~~~ BC32007: 'UShort' values cannot be converted to 'Char'. Use 'Microsoft.VisualBasic.ChrW' to interpret a numeric value as a Unicode character or first convert it to 'String' to produce a digit. O = CChar(sb) ~~ </expected>) End Sub <Fact()> Public Sub BC32008ERR_NoDirectDelegateConstruction1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="NoDirectDelegateConstruction1"> <file name="a.vb"> Class C1 Public Delegate Sub myDelegate() public shared sub mySub() end sub End Class Module M1 Sub Main() Dim d1 As C1.myDelegate d1 = New C1.myDelegate() d1 = New C1.myDelegate(C1.mySub) d1 = New C1.myDelegate(C1.mySub, 23) d1 = New C1.myDelegate(addressof C1.mySub, 23) d1 = New C1.myDelegate(,) d1 = New C1.myDelegate(,,23) End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC32008: Delegate 'C1.myDelegate' requires an 'AddressOf' expression or lambda expression as the only argument to its constructor. d1 = New C1.myDelegate() ~~ BC32008: Delegate 'C1.myDelegate' requires an 'AddressOf' expression or lambda expression as the only argument to its constructor. d1 = New C1.myDelegate(C1.mySub) ~~~~~~~~~~ BC32008: Delegate 'C1.myDelegate' requires an 'AddressOf' expression or lambda expression as the only argument to its constructor. d1 = New C1.myDelegate(C1.mySub, 23) ~~~~~~~~~~~~~~ BC32008: Delegate 'C1.myDelegate' requires an 'AddressOf' expression or lambda expression as the only argument to its constructor. d1 = New C1.myDelegate(addressof C1.mySub, 23) ~~~~~~~~~~~~~~~~~~~~~~~~ BC32008: Delegate 'C1.myDelegate' requires an 'AddressOf' expression or lambda expression as the only argument to its constructor. d1 = New C1.myDelegate(,) ~~~ BC32008: Delegate 'C1.myDelegate' requires an 'AddressOf' expression or lambda expression as the only argument to its constructor. d1 = New C1.myDelegate(,,23) ~~~~~~ </expected>) End Sub <Fact()> Public Sub BC32008ERR_NoDirectDelegateConstruction1_2() Dim source = <compilation name="NewDelegateWithAddressOf"> <file name="a.vb"> Imports System Delegate Sub D() Module Program Sub Main(args As String()) Dim x As D x = New D(AddressOf Method, 23) x = New D(AddressOf Method, foo:=23) x = New D(bar:=AddressOf Method, foo:=23) x = New D(bar:=AddressOf Method, bar:=23) x = New D() x = New D(23) x = New D(nothing) x = New D Dim y1 as New D(AddressOf Method, 23) Dim y2 as New D(AddressOf Method, foo:=23) Dim y3 as New D(bar:=AddressOf Method, foo:=23) Dim y4 as New D(bar:=AddressOf Method, bar:=23) Dim y5 as New D() Dim y6 as New D(23) Dim y7 as New D(nothing) Dim y8 as New D End Sub Public Sub Method() console.writeline("Hello.") End Sub End Module </file> </compilation> Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) CompilationUtils.AssertTheseDiagnostics(c1, <expected> BC32008: Delegate 'D' requires an 'AddressOf' expression or lambda expression as the only argument to its constructor. x = New D(AddressOf Method, 23) ~~~~~~~~~~~~~~~~~~~~~~ BC32008: Delegate 'D' requires an 'AddressOf' expression or lambda expression as the only argument to its constructor. x = New D(AddressOf Method, foo:=23) ~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC32008: Delegate 'D' requires an 'AddressOf' expression or lambda expression as the only argument to its constructor. x = New D(bar:=AddressOf Method, foo:=23) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC32008: Delegate 'D' requires an 'AddressOf' expression or lambda expression as the only argument to its constructor. x = New D(bar:=AddressOf Method, bar:=23) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC32008: Delegate 'D' requires an 'AddressOf' expression or lambda expression as the only argument to its constructor. x = New D() ~~ BC32008: Delegate 'D' requires an 'AddressOf' expression or lambda expression as the only argument to its constructor. x = New D(23) ~~~~ BC32008: Delegate 'D' requires an 'AddressOf' expression or lambda expression as the only argument to its constructor. x = New D(nothing) ~~~~~~~~~ BC32008: Delegate 'D' requires an 'AddressOf' expression or lambda expression as the only argument to its constructor. x = New D ~~~~~ BC32008: Delegate 'D' requires an 'AddressOf' expression or lambda expression as the only argument to its constructor. Dim y1 as New D(AddressOf Method, 23) ~~~~~~~~~~~~~~~~~~~~~~ BC32008: Delegate 'D' requires an 'AddressOf' expression or lambda expression as the only argument to its constructor. Dim y2 as New D(AddressOf Method, foo:=23) ~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC32008: Delegate 'D' requires an 'AddressOf' expression or lambda expression as the only argument to its constructor. Dim y3 as New D(bar:=AddressOf Method, foo:=23) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC32008: Delegate 'D' requires an 'AddressOf' expression or lambda expression as the only argument to its constructor. Dim y4 as New D(bar:=AddressOf Method, bar:=23) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC32008: Delegate 'D' requires an 'AddressOf' expression or lambda expression as the only argument to its constructor. Dim y5 as New D() ~~ BC32008: Delegate 'D' requires an 'AddressOf' expression or lambda expression as the only argument to its constructor. Dim y6 as New D(23) ~~~~ BC32008: Delegate 'D' requires an 'AddressOf' expression or lambda expression as the only argument to its constructor. Dim y7 as New D(nothing) ~~~~~~~~~ BC32008: Delegate 'D' requires an 'AddressOf' expression or lambda expression as the only argument to its constructor. Dim y8 as New D ~~~~~ </expected>) End Sub <Fact()> Public Sub BC32010ERR_AttrAssignmentNotFieldOrProp1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="AttrAssignmentNotFieldOrProp1"> <file name="at32010.vb"><![CDATA[ Imports System <AttributeUsage(AttributeTargets.All)> Public Class MyAttribute Inherits Attribute Public Enum E Zero One End Enum Public Sub S() End Sub Public Function F!() Return 0.0F End Function End Class <My(E:=E.One, S:=Nothing)> Class Foo <My(F!:=1.234F)> Public Sub S2() End Sub End Class ]]></file> </compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_NameNotDeclared1, "E").WithArguments("E"), Diagnostic(ERRID.ERR_AttrAssignmentNotFieldOrProp1, "E").WithArguments("E"), Diagnostic(ERRID.ERR_AttrAssignmentNotFieldOrProp1, "S").WithArguments("S"), Diagnostic(ERRID.ERR_AttrAssignmentNotFieldOrProp1, "F!").WithArguments("F")) End Sub <Fact()> Public Sub BC32013ERR_StrictDisallowsObjectComparison1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="StrictDisallowsObjectComparison1"> <file name="a.vb"> Option Strict On Class C1 Sub scen1() Dim Obj As Object = New Object Select Case obj Case "DFT" End Select End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC32013: Option Strict On disallows operands of type Object for operator '='. Use the 'Is' operator to test for object identity. Select Case obj ~~~ </expected>) End Sub <Fact()> Public Sub BC32013ERR_StrictDisallowsObjectComparison1_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="StrictDisallowsObjectComparison1"> <file name="a.vb"> Option Strict On Class C1 Sub scen1() Dim Obj As Object = New Object if (obj="string") End If End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC32013: Option Strict On disallows operands of type Object for operator '='. Use the 'Is' operator to test for object identity. if (obj="string") ~~~ </expected>) End Sub <Fact()> Public Sub BC32014ERR_NoConstituentArraySizes() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="NoConstituentArraySizes"> <file name="a.vb"> Option Strict On Imports System Module Module1 Sub Main() Dim arr10 As Integer(,) = New Integer(9)(5) {} ' Invalid End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30414: Value of type 'Integer()()' cannot be converted to 'Integer(*,*)' because the array types have different numbers of dimensions. Dim arr10 As Integer(,) = New Integer(9)(5) {} ' Invalid ~~~~~~~~~~~~~~~~~~~~ BC32014: Bounds can be specified only for the top-level array when initializing an array of arrays. Dim arr10 As Integer(,) = New Integer(9)(5) {} ' Invalid ~ </expected>) End Sub <WorkItem(545621, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545621")> <Fact()> Public Sub BC32014ERR_NoConstituentArraySizes1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="NoConstituentArraySizes"> <file name="a.vb"> Module M Sub Main() Dim x()(1)() End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42024: Unused local variable: 'x'. Dim x()(1)() ~ BC32014: Bounds can be specified only for the top-level array when initializing an array of arrays. Dim x()(1)() ~ </expected>) End Sub <WorkItem(528729, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528729")> <Fact()> Public Sub BC32016ERR_FunctionResultCannotBeIndexed1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="FunctionResultCannotBeIndexed1"> <file name="a.vb"> Imports Microsoft.VisualBasic.FileSystem Module M1 Sub foo() If FreeFile(1) &lt; 255 Then End If End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC32016: 'Public Function FreeFile() As Integer' has no parameters and its return type cannot be indexed. If FreeFile(1) &lt; 255 Then ~~~~~~~~ </expected>) End Sub <Fact, WorkItem(543658, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543658")> Public Sub BC32021ERR_NamedArgAlsoOmitted2() CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="NamedArgAlsoOmitted2"> <file name="a.vb"> Public Module M1 Public Sub foo(ByVal X As Byte, Optional ByVal Y As Byte = 0, _ Optional ByVal Z As Byte = 0) Call foo(6, , Y:=3) End Sub End Module </file> </compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_NamedArgAlsoOmitted2, "Y").WithArguments("Y", "Public Sub foo(X As Byte, [Y As Byte = 0], [Z As Byte = 0])")) End Sub <Fact()> Public Sub BC32022ERR_CannotCallEvent1() CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="CannotCallEvent1"> <file name="a.vb"> Public Module M1 Public Event BurnPercent(ByVal Percent As Integer) Sub foo() BurnPercent.Invoke() End Sub End Module </file> </compilation>).AssertTheseDiagnostics( <expected> BC32022: 'Public Event BurnPercent(Percent As Integer)' is an event, and cannot be called directly. Use a 'RaiseEvent' statement to raise an event. BurnPercent.Invoke() ~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC32022ERR_CannotCallEvent1_2() CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Class C Private Event E As System.EventHandler Sub M(o As Object) E() M(E()) End Sub End Class </file> </compilation>).AssertTheseDiagnostics( <expected> BC32022: 'Private Event E As EventHandler' is an event, and cannot be called directly. Use a 'RaiseEvent' statement to raise an event. E() ~ BC32022: 'Private Event E As EventHandler' is an event, and cannot be called directly. Use a 'RaiseEvent' statement to raise an event. M(E()) ~ </expected>) End Sub <Fact()> Public Sub BC32023ERR_ForEachCollectionDesignPattern1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ForEachCollectionDesignPattern1"> <file name="a.vb"> Option Infer On Public Module M1 Sub foo() Dim s As Integer For Each i In s Next End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC32023: Expression is of type 'Integer', which is not a collection type. For Each i In s ~ </expected>) End Sub <Fact()> Public Sub BC32023ERR_ForEachCollectionDesignPattern1_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="ForEachCollectionDesignPattern1"> <file name="a.vb"> Option Infer On Class C Shared Sub Main() For Each x As Integer In If(x, x, x) Next End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC32023: Expression is of type 'Integer', which is not a collection type. For Each x As Integer In If(x, x, x) ~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC32023ERR_ForEachCollectionDesignPattern1_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="ForEachCollectionDesignPattern1"> <file name="a.vb"> Option Infer On Class C Public Shared Sub Main() Dim e As New Enumerable() For Each x In e Next End Sub End Class Structure Enumerable Public i As Integer Public Sub GetEnumerator() i = i + 1 'Return New Enumerator() End Sub End Structure Structure Enumerator Private x As Integer Public ReadOnly Property Current() As Integer Get Return x End Get End Property Public Function MoveNext() As Boolean Return System.Threading.Interlocked.Increment(x) &lt; 4 End Function End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC32023: Expression is of type 'Enumerable', which is not a collection type. For Each x In e ~ </expected>) End Sub <Fact()> Public Sub BC32023ERR_ForEachCollectionDesignPattern1_3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="ForEachCollectionDesignPattern1"> <file name="a.vb"> Option Infer On Class C Public Shared Sub Main() Dim e As New Enumerable() For Each x In e Next End Sub End Class Structure Enumerable Public i As Integer private Function GetEnumerator() as Enumerator i = i + 1 Return New Enumerator() End Function End Structure Structure Enumerator Private x As Integer Public ReadOnly Property Current() As Integer Get Return x End Get End Property Public Function MoveNext() As Boolean Return System.Threading.Interlocked.Increment(x) &lt; 4 End Function End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC32023: Expression is of type 'Enumerable', which is not a collection type. For Each x In e ~ </expected>) End Sub <Fact()> Public Sub BC32023ERR_ForEachCollectionDesignPattern1_4() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="ForEachCollectionDesignPattern1"> <file name="a.vb"> Option Infer On Class C Public Shared Sub Main() Dim e As New Enumerable() For Each x In e Next End Sub End Class Structure Enumerable Public i As Integer End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC32023: Expression is of type 'Enumerable', which is not a collection type. For Each x In e ~ </expected>) End Sub <Fact()> Public Sub BC32029ERR_StrictArgumentCopyBackNarrowing3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="StrictArgumentCopyBackNarrowing3"> <file name="a.vb"> Option Strict On Class C1 Public intDataField As Integer Dim type1 As MyType Sub Main() Dim str1 As String Scen1(intDataField) Scen1(type1.intField) scen3(str1) scen3(type1) End Sub Sub Scen1(ByRef xx As Long) End Sub Sub Scen2(ByRef gg As Byte) End Sub Sub scen3(ByRef gg As Object) End Sub End Class Structure MyType Public intField As Short End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC32029: Option Strict On disallows narrowing from type 'Long' to type 'Integer' in copying the value of 'ByRef' parameter 'xx' back to the matching argument. Scen1(intDataField) ~~~~~~~~~~~~ BC32029: Option Strict On disallows narrowing from type 'Long' to type 'Short' in copying the value of 'ByRef' parameter 'xx' back to the matching argument. Scen1(type1.intField) ~~~~~~~~~~~~~~ BC32029: Option Strict On disallows narrowing from type 'Object' to type 'String' in copying the value of 'ByRef' parameter 'gg' back to the matching argument. scen3(str1) ~~~~ BC42104: Variable 'str1' is used before it has been assigned a value. A null reference exception could result at runtime. scen3(str1) ~~~~ BC32029: Option Strict On disallows narrowing from type 'Object' to type 'MyType' in copying the value of 'ByRef' parameter 'gg' back to the matching argument. scen3(type1) ~~~~~ </expected>) End Sub <Fact()> Public Sub BC32036ERR_NoUniqueConstructorOnBase2() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="NoUniqueConstructorOnBase2"> <file name="a.vb"> Class Base Sub New() End Sub Sub New(ByVal ParamArray a() As Integer) End Sub End Class Class Derived Inherits Base End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC32036: Class 'Derived' must declare a 'Sub New' because its base class 'Base' has more than one accessible 'Sub New' that can be called with no arguments. Class Derived ~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC32038ERR_RequiredNewCallTooMany2() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="RequiredNewCallTooMany2"> <file name="a.vb"> Class Base Sub New() End Sub Sub New(ByVal ParamArray a() As Integer) End Sub End Class Class Derived Inherits Base Sub New() End Sub End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC32038: First statement of this 'Sub New' must be a call to 'MyBase.New' or 'MyClass.New' because base class 'Base' of 'Derived' has more than one accessible 'Sub New' that can be called with no arguments. Sub New() ~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC32039ERR_ForCtlVarArraySizesSpecified() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="ForCtlVarArraySizesSpecified"> <file name="a.vb"> Imports System.Collections.Generic Class C1 Sub New() Dim arrayList As New List(Of Integer()) For Each listElement() As Integer In arrayList For Each listElement(1) As Integer In arrayList Next Next End Sub End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC30616: Variable 'listElement' hides a variable in an enclosing block. For Each listElement(1) As Integer In arrayList ~~~~~~~~~~~~~~ BC32039: Array declared as for loop control variable cannot be declared with an initial size. For Each listElement(1) As Integer In arrayList ~~~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC32045ERR_TypeOrMemberNotGeneric1() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="TypeOrMemberNotGeneric1"> <file name="a.vb"> Class Base(Of u) sub fun1(ByRef b1 As Integer) End sub End Class Class Derived(Of v) Inherits Base(Of v) Overloads sub fun1(Of T) (ByVal t1 As T, ByVal ParamArray t2() As UInteger) End sub End Class Friend Module M1F Sub FOO() Dim c1 As New Base(Of String) c1.fun1(Of Base(Of String)) (4.4@) End Sub End Module </file> </compilation>) Dim expectedErrors1 = <errors> BC32045: 'Public Sub fun1(ByRef b1 As Integer)' has no type parameters and so cannot have type arguments. c1.fun1(Of Base(Of String)) (4.4@) ~~~~~~~~~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC32045ERR_TypeOrMemberNotGeneric1_1() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="TypeOrMemberNotGeneric1"> <file name="a.vb"> Class Base(Of u) sub fun1(ByRef b1 As Integer) End sub End Class Class Derived(Of v) Inherits Base(Of v) Overloads sub fun1(Of T) (ByVal t1 As T, ByVal ParamArray t2() As UInteger) End sub End Class Friend Module M1F Sub FOO() Dim c1 As New Base(Of String) c1.fun1(Of Derived(Of String)) (3.3!, Nothing) End Sub End Module </file> </compilation>) Dim expectedErrors1 = <errors> BC32045: 'Public Sub fun1(ByRef b1 As Integer)' has no type parameters and so cannot have type arguments. c1.fun1(Of Derived(Of String)) (3.3!, Nothing) ~~~~~~~~~~~~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC32045ERR_TypeOrMemberNotGeneric1_2() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="TypeOrMemberNotGeneric1"> <file name="a.vb"> Class Base(Of u) sub fun1(ByRef b1 As Integer) End sub End Class Class Derived(Of v) Inherits Base(Of v) Overloads sub fun1(Of T) (ByVal t1 As T, ByVal ParamArray t2() As UInteger) End sub End Class Friend Module M1F Sub FOO() Dim c1 As New Base(Of String) c1.fun1(Of System.ValueType) (4.4@, 3US) End Sub End Module </file> </compilation>) Dim expectedErrors1 = <errors> BC32045: 'Public Sub fun1(ByRef b1 As Integer)' has no type parameters and so cannot have type arguments. c1.fun1(Of System.ValueType) (4.4@, 3US) ~~~~~~~~~~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC32045ERR_TypeOrMemberNotGeneric1_3() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="TypeOrMemberNotGeneric1"> <file name="a.vb"> Class Base(Of u) sub fun1(ByRef b1 As Integer) End sub End Class Class Derived(Of v) Inherits Base(Of v) Overloads sub fun1(Of T) (ByVal t1 As T, ByVal ParamArray t2() As UInteger) End sub End Class Friend Module M1F Sub FOO() Dim c1 As Base(Of String) = New Derived(Of String) c1.fun1(Of System.ValueType) (3@) End Sub End Module </file> </compilation>) Dim expectedErrors1 = <errors> BC32045: 'Public Sub fun1(ByRef b1 As Integer)' has no type parameters and so cannot have type arguments. c1.fun1(Of System.ValueType) (3@) ~~~~~~~~~~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC32045ERR_TypeOrMemberNotGeneric1_4() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="TypeOrMemberNotGeneric1"> <file name="a.vb"> Class Base(Of u) sub fun1(ByRef b1 As Integer) End sub End Class Class Derived(Of v) Inherits Base(Of v) Overloads sub fun1(Of T) (ByVal t1 As T, ByVal ParamArray t2() As UInteger) End sub End Class Friend Module M1F Sub FOO() Dim c1 As Base(Of String) = New Derived(Of String) c1.fun1(Of System.Delegate) ("c"c, 3@) End Sub End Module </file> </compilation>) Dim expectedErrors1 = <errors> BC32045: 'Public Sub fun1(ByRef b1 As Integer)' has no type parameters and so cannot have type arguments. c1.fun1(Of System.Delegate) ("c"c, 3@) ~~~~~~~~~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC32046ERR_NewIfNullOnGenericParam() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Structure S(Of T, U As New) Sub M(Of V)() Dim o o = New T() o = New U() o = New V() End Sub End Structure Class C(Of T1 As Structure, T2 As Class) Sub M(Of T3 As Structure, T4 As {Class, New})() Dim o o = New T1() o = New T2() o = New T3() o = New T4() End Sub End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC32046: 'New' cannot be used on a type parameter that does not have a 'New' constraint. o = New T() ~ BC32046: 'New' cannot be used on a type parameter that does not have a 'New' constraint. o = New V() ~ BC32046: 'New' cannot be used on a type parameter that does not have a 'New' constraint. o = New T2() ~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC32050ERR_UnboundTypeParam2() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="UnboundTypeParam2"> <file name="a.vb"> Option Strict Off Public Module M Sub Main() Foo(AddressOf Bar) End Sub Sub Foo(Of T)(ByVal a As System.Action(Of T)) End Sub Sub Bar(ByVal x As String) End Sub End Module </file> </compilation>) Dim expectedErrors1 = <errors> BC32050: Type parameter 'T' for 'Public Sub Foo(Of T)(a As Action(Of T))' cannot be inferred. Foo(AddressOf Bar) ~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC32052ERR_IsOperatorGenericParam1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Interface I End Interface Class A End Class Class B(Of T As Structure) End Class Class C(Of T) Shared o As Object Shared Sub M1(Of T1)(_1 As T1) If _1 Is o Then End If If o Is _1 Then End If End Sub Shared Sub M2(Of T2 As Class)(_2 As T2) If _2 Is o Then End If If o Is _2 Then End If End Sub Shared Sub M3(Of T3 As Structure)(_3 As T3) If _3 Is o Then End If If o Is _3 Then End If End Sub Shared Sub M4(Of T4 As New)(_4 As T4) If _4 Is o Then End If If o Is _4 Then End If End Sub Shared Sub M5(Of T5 As I)(_5 As T5) If _5 Is o Then End If If o Is _5 Then End If End Sub Shared Sub M6(Of T6 As A)(_6 As T6) If _6 Is o Then End If If o Is _6 Then End If End Sub Shared Sub M7(Of T7 As U, U)(_7 As T7) If _7 Is o Then End If If o Is _7 Then End If End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC32052: 'Is' operand of type 'T1' can be compared only to 'Nothing' because 'T1' is a type parameter with no class constraint. If _1 Is o Then ~~ BC32052: 'Is' operand of type 'T1' can be compared only to 'Nothing' because 'T1' is a type parameter with no class constraint. If o Is _1 Then ~~ BC30020: 'Is' operator does not accept operands of type 'T3'. Operands must be reference or nullable types. If _3 Is o Then ~~ BC30020: 'Is' operator does not accept operands of type 'T3'. Operands must be reference or nullable types. If o Is _3 Then ~~ BC32052: 'Is' operand of type 'T4' can be compared only to 'Nothing' because 'T4' is a type parameter with no class constraint. If _4 Is o Then ~~ BC32052: 'Is' operand of type 'T4' can be compared only to 'Nothing' because 'T4' is a type parameter with no class constraint. If o Is _4 Then ~~ BC32052: 'Is' operand of type 'T5' can be compared only to 'Nothing' because 'T5' is a type parameter with no class constraint. If _5 Is o Then ~~ BC32052: 'Is' operand of type 'T5' can be compared only to 'Nothing' because 'T5' is a type parameter with no class constraint. If o Is _5 Then ~~ BC32052: 'Is' operand of type 'T7' can be compared only to 'Nothing' because 'T7' is a type parameter with no class constraint. If _7 Is o Then ~~ BC32052: 'Is' operand of type 'T7' can be compared only to 'Nothing' because 'T7' is a type parameter with no class constraint. If o Is _7 Then ~~ </expected>) End Sub <Fact()> Public Sub BC32059ERR_OnlyNullLowerBound() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="IsOperatorGenericParam1"> <file name="a.vb"> Option Infer On Module M Sub Main() Dim arr1(0 To 0, 0 To -1) As Integer Dim arr3(-1 To 0, 0 To -1) As Integer 'Invalid Dim arr4(0 To 1, -1 To 0) As Integer 'Invalid Dim arr5(0D To 1, 0.0 To 0) As Integer 'Invalid Dim arr6(0! To 1, 0.0 To 0) As Integer 'Invalid End Sub End Module </file> </compilation>) Dim expectedErrors1 = <errors> BC32059: Array lower bounds can be only '0'. Dim arr3(-1 To 0, 0 To -1) As Integer 'Invalid ~~ BC32059: Array lower bounds can be only '0'. Dim arr4(0 To 1, -1 To 0) As Integer 'Invalid ~~ BC32059: Array lower bounds can be only '0'. Dim arr5(0D To 1, 0.0 To 0) As Integer 'Invalid ~~ BC32059: Array lower bounds can be only '0'. Dim arr5(0D To 1, 0.0 To 0) As Integer 'Invalid ~~~ BC32059: Array lower bounds can be only '0'. Dim arr6(0! To 1, 0.0 To 0) As Integer 'Invalid ~~ BC32059: Array lower bounds can be only '0'. Dim arr6(0! To 1, 0.0 To 0) As Integer 'Invalid ~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <WorkItem(542204, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542204")> <Fact()> Public Sub BC32079ERR_TypeParameterDisallowed() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> <![CDATA[ Imports System Class AttrCls1 Inherits Attribute Sub New(ByVal p As Type) End Sub End Class Structure S1(Of T) Dim i As Integer <AttrCls1(GetType(T))> _ Class Cls1 End Class End Structure ]]></file> </compilation>) Dim expectedErrors1 = <errors><![CDATA[ BC32079: Type parameters or types constructed with type parameters are not allowed in attribute arguments. <AttrCls1(GetType(T))> _ ~ ]]></errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <WorkItem(542204, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542204")> <Fact()> Public Sub BC32079ERR_OpenTypeDisallowed() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> <![CDATA[ Imports System Class AttrCls1 Inherits Attribute Sub New(ByVal p As Type) End Sub End Class Structure S1(Of T) Dim i As Integer <AttrCls1(GetType(S1(Of T)))> _ Class A End Class <AttrCls1(GetType(S1(Of T).A()))> _ Class B End Class End Structure ]]></file> </compilation>) Dim expectedErrors1 = <errors><![CDATA[ BC32079: Type parameters or types constructed with type parameters are not allowed in attribute arguments. <AttrCls1(GetType(S1(Of T)))> _ ~~~~~~~~ BC32079: Type parameters or types constructed with type parameters are not allowed in attribute arguments. <AttrCls1(GetType(S1(Of T).A()))> _ ~~~~~~~~~~~~ ]]></errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC32085ERR_NewArgsDisallowedForTypeParam() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="NewArgsDisallowedForTypeParam"> <file name="a.vb"> Module M1 Sub Sub1(Of T As New)(ByVal a As T) a = New T() a = New T(2) a = New T( 2, 3, 4 ) End Sub End Module </file> </compilation>) Dim expectedErrors1 = <errors> BC32085: Arguments cannot be passed to a 'New' used on a type parameter. a = New T(2) ~ BC32085: Arguments cannot be passed to a 'New' used on a type parameter. a = New T( 2, 3, ~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC32087ERR_NoTypeArgumentCountOverloadCand1() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="NoTypeArgumentCountOverloadCand1"> <file name="a.vb"> Option Strict Off Module M Sub Main() Dim x As Object = New Object() x.Equals(Of Integer)() x.Equals(Of Integer) = 1 End Sub End Module </file> </compilation>) Dim expectedErrors1 = <errors> BC32087: Overload resolution failed because no accessible 'Equals' accepts this number of type arguments. x.Equals(Of Integer)() ~~~~~~~~~~~~~~~~~~ BC32087: Overload resolution failed because no accessible 'Equals' accepts this number of type arguments. x.Equals(Of Integer) = 1 ~~~~~~~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC32096ERR_ForEachAmbiguousIEnumerable1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Option Strict On Imports System.Collections Imports System.Collections.Generic Class C1 Implements IEnumerable(Of String), IEnumerable(Of Integer) Public Function GetEnumerator_int() As IEnumerator(Of integer) Implements IEnumerable(Of integer).GetEnumerator Return Nothing End Function Public Function GetEnumerator_str() As IEnumerator(Of String) Implements IEnumerable(Of String).GetEnumerator Return Nothing End Function Public Function GetEnumerator1_str() As IEnumerator Implements IEnumerable.GetEnumerator Return Nothing End Function End Class Class C Shared Sub M(Of T1 As C1)(p As T1) For Each o As T1 In p Next End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC32096: 'For Each' on type 'T1' is ambiguous because the type implements multiple instantiations of 'System.Collections.Generic.IEnumerable(Of T)'. For Each o As T1 In p ~ </expected>) End Sub <WorkItem(3420, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub BC32095ERR_ArrayOfRawGenericInvalid() Dim code = <![CDATA[ Class C1(Of T) End Class Class C2 Public Sub Main() Dim x = GetType(C1(Of )()) End Sub End Class ]]>.Value ParseAndVerify(code, <errors> <error id="32095"/> </errors>) End Sub <WorkItem(543616, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543616")> <Fact()> Public Sub BC32096ERR_ForEachAmbiguousIEnumerable1_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="AmbiguousAcrossInterfaces3"> <file name="a.vb"> Imports System.Collections.Generic Class C Public Shared Sub Main() End Sub End Class Public Class C(Of T As {IEnumerable(Of Integer), IEnumerable(Of String)}) Public Shared Sub TestForeach(t As T) For Each i As Integer In t Next End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC32096: 'For Each' on type 'T' is ambiguous because the type implements multiple instantiations of 'System.Collections.Generic.IEnumerable(Of T)'. For Each i As Integer In t ~ </expected>) ' used to report, but this changed now ' "BC30685: 'GetEnumerator' is ambiguous across the inherited interfaces 'System.Collections.Generic.IEnumerable(Of Integer)' ' and 'System.Collections.Generic.IEnumerable(Of String)'." End Sub <Fact()> Public Sub BC32097ERR_IsNotOperatorGenericParam1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Interface I End Interface Class A End Class Class B(Of T As Structure) End Class Class C(Of T) Shared o As Object Shared Sub M1(Of T1)(_1 As T1) If _1 IsNot o Then End If If o IsNot _1 Then End If End Sub Shared Sub M2(Of T2 As Class)(_2 As T2) If _2 IsNot o Then End If If o IsNot _2 Then End If End Sub Shared Sub M3(Of T3 As Structure)(_3 As T3) If _3 IsNot o Then End If If o IsNot _3 Then End If End Sub Shared Sub M4(Of T4 As New)(_4 As T4) If _4 IsNot o Then End If If o IsNot _4 Then End If End Sub Shared Sub M5(Of T5 As I)(_5 As T5) If _5 IsNot o Then End If If o IsNot _5 Then End If End Sub Shared Sub M6(Of T6 As A)(_6 As T6) If _6 IsNot o Then End If If o IsNot _6 Then End If End Sub Shared Sub M7(Of T7 As U, U)(_7 As T7) If _7 IsNot o Then End If If o IsNot _7 Then End If End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC32097: 'IsNot' operand of type 'T1' can be compared only to 'Nothing' because 'T1' is a type parameter with no class constraint. If _1 IsNot o Then ~~ BC32097: 'IsNot' operand of type 'T1' can be compared only to 'Nothing' because 'T1' is a type parameter with no class constraint. If o IsNot _1 Then ~~ BC31419: 'IsNot' requires operands that have reference types, but this operand has the value type 'T3'. If _3 IsNot o Then ~~ BC31419: 'IsNot' requires operands that have reference types, but this operand has the value type 'T3'. If o IsNot _3 Then ~~ BC32097: 'IsNot' operand of type 'T4' can be compared only to 'Nothing' because 'T4' is a type parameter with no class constraint. If _4 IsNot o Then ~~ BC32097: 'IsNot' operand of type 'T4' can be compared only to 'Nothing' because 'T4' is a type parameter with no class constraint. If o IsNot _4 Then ~~ BC32097: 'IsNot' operand of type 'T5' can be compared only to 'Nothing' because 'T5' is a type parameter with no class constraint. If _5 IsNot o Then ~~ BC32097: 'IsNot' operand of type 'T5' can be compared only to 'Nothing' because 'T5' is a type parameter with no class constraint. If o IsNot _5 Then ~~ BC32097: 'IsNot' operand of type 'T7' can be compared only to 'Nothing' because 'T7' is a type parameter with no class constraint. If _7 IsNot o Then ~~ BC32097: 'IsNot' operand of type 'T7' can be compared only to 'Nothing' because 'T7' is a type parameter with no class constraint. If o IsNot _7 Then ~~ </expected>) End Sub <Fact()> Public Sub BC32098ERR_TypeParamQualifierDisallowed() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="TypeParamQualifierDisallowed"> <file name="a.vb"> Class C1(Of T As DataHolder) Sub Main() T.Var1 = 4 End Sub End Class Class DataHolder Public Var1 As Integer End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC32098: Type parameters cannot be used as qualifiers. T.Var1 = 4 ~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact(), WorkItem(545050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545050")> Public Sub BC32126ERR_AddressOfNullableMethod() CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="AddressOfNullableMethod"> <file name="a.vb"> Imports System Module M Sub Main() Dim x As Integer? = Nothing Dim ef1 As Func(Of Integer) = AddressOf x.GetValueOrDefault Dim ef2 As Func(Of Integer, Integer) = AddressOf x.GetValueOrDefault End Sub End Module </file> </compilation>).VerifyDiagnostics( Diagnostic(ERRID.ERR_AddressOfNullableMethod, "x.GetValueOrDefault").WithArguments("Integer?", "AddressOf"), Diagnostic(ERRID.ERR_AddressOfNullableMethod, "x.GetValueOrDefault").WithArguments("Integer?", "AddressOf")) End Sub <Fact()> Public Sub BC32127ERR_IsOperatorNullable1() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="IsOperatorNullable1"> <file name="a.vb"> Module M1 Sub FOO() Dim s1_a As S1? = New S1() Dim s1_b As S1? = New S1() Dim B = s1_a Is s1_b End Sub End Module Structure S1 End Structure </file> </compilation>) Dim expectedErrors1 = <errors> BC32127: 'Is' operand of type 'S1?' can be compared only to 'Nothing' because 'S1?' is a nullable type. Dim B = s1_a Is s1_b ~~~~ BC32127: 'Is' operand of type 'S1?' can be compared only to 'Nothing' because 'S1?' is a nullable type. Dim B = s1_a Is s1_b ~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC32128ERR_IsNotOperatorNullable1() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="IsNotOperatorNullable1"> <file name="a.vb"> Module M1 Sub FOO() Dim s1_a As S1? = New S1() Dim s1_b As S1? = New S1() Dim B = s1_a IsNot s1_b End Sub End Module Structure S1 End Structure </file> </compilation>) Dim expectedErrors1 = <errors> BC32128: 'IsNot' operand of type 'S1?' can be compared only to 'Nothing' because 'S1?' is a nullable type. Dim B = s1_a IsNot s1_b ~~~~ BC32128: 'IsNot' operand of type 'S1?' can be compared only to 'Nothing' because 'S1?' is a nullable type. Dim B = s1_a IsNot s1_b ~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <WorkItem(545669, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545669")> <Fact()> Public Sub BC32303ERR_IllegalCallOrIndex() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="IllegalCallOrIndex"> <file name="a.vb"> Class C1 Function Foo1() as Object return nothing() ' Error End Function Function Foo2() as Object Return CType(Nothing, Object)() ' Error End Function Function Foo3() as Object Return DirectCast(TryCast(CType(Nothing, Object), C1), Object)() ' No error End Function Sub FOO4() Dim testVariable As Object = Nothing(1) End Sub Sub FOO5() Nothing() ' Error, but a parsing error End Sub End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC32303: Illegal call expression or index expression. return nothing() ' Error ~~~~~~~~~ BC32303: Illegal call expression or index expression. Return CType(Nothing, Object)() ' Error ~~~~~~~~~~~~~~~~~~~~~~~~ BC32303: Illegal call expression or index expression. Dim testVariable As Object = Nothing(1) ~~~~~~~~~~ BC30035: Syntax error. Nothing() ' Error, but a parsing error ~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC33009ERR_ParamArrayIllegal1() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="UnacceptableLogicalOperator3"> <file name="a.vb"> Delegate Sub FooDel1(ParamArray p() as Integer) Delegate Function FooDel2(ParamArray p() as Integer) as Byte Module M1 Sub Main() End Sub End Module </file> </compilation>) Dim expectedErrors1 = <errors> BC33009: 'Delegate' parameters cannot be declared 'ParamArray'. Delegate Sub FooDel1(ParamArray p() as Integer) ~~~~~~~~~~ BC33009: 'Delegate' parameters cannot be declared 'ParamArray'. Delegate Function FooDel2(ParamArray p() as Integer) as Byte ~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC33034ERR_UnacceptableLogicalOperator3() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="UnacceptableLogicalOperator3"> <file name="a.vb"> Imports System Class c1 End Class Class c2 Inherits c1 Shared Operator And(ByVal x As c2, ByVal y As c1) As c2 Return New c2 End Operator Shared Operator Or(ByVal x As c2, ByVal y As c2) As c2 Return New c2 End Operator End Class Module M1 Sub Main() Dim o1 As New c2, o2 As New c2, o As Object o = o1 AndAlso o2 o = o1 OrElse o2 End Sub End Module </file> </compilation>) Dim expectedErrors1 = <errors> BC33034: Return and parameter types of 'Public Shared Operator And(x As c2, y As c1) As c2' must be 'c2' to be used in a 'AndAlso' expression. o = o1 AndAlso o2 ~~~~~~~~~~~~~ BC33035: Type 'c2' must define operator 'IsTrue' to be used in a 'OrElse' expression. o = o1 OrElse o2 ~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC33037ERR_CopyBackTypeMismatch3() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="CopyBackTypeMismatch3"> <file name="a.vb"> Class c2 Shared Widening Operator CType(ByVal x As c2) As Integer Return 9 End Operator End Class Module M1 Sub FOO() Dim o As New c2 FOO(o) End Sub Sub foo(ByRef x As Integer) x = 99 End Sub End Module </file> </compilation>) compilation1.VerifyDiagnostics(Diagnostic(ERRID.ERR_CopyBackTypeMismatch3, "o").WithArguments("x", "Integer", "c2")) End Sub ' Roslyn extra errors (last 3) <Fact()> Public Sub BC33038ERR_ForLoopOperatorRequired2() CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ForLoopOperatorRequired2"> <file name="a.vb"> Class S1 Public Shared Widening Operator CType(ByVal x As Integer) As S1 Return Nothing End Operator Sub foo() Dim v As S1 For i = 1 To v Next End Sub End Class </file> </compilation>).VerifyDiagnostics( Diagnostic(ERRID.ERR_ForLoopOperatorRequired2, "For i = 1 To v").WithArguments("S1", "+"), Diagnostic(ERRID.ERR_ForLoopOperatorRequired2, "For i = 1 To v").WithArguments("S1", "-"), Diagnostic(ERRID.ERR_ForLoopOperatorRequired2, "For i = 1 To v").WithArguments("S1", "<="), Diagnostic(ERRID.ERR_ForLoopOperatorRequired2, "For i = 1 To v").WithArguments("S1", ">="), Diagnostic(ERRID.WRN_DefAsgUseNullRef, "v").WithArguments("v")) End Sub ' Roslyn extra errors (last 2) <Fact()> Public Sub BC33039ERR_UnacceptableForLoopOperator2() CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="UnacceptableForLoopOperator2"> <file name="a.vb"> Module M1 Class C1(Of t) Shared Widening Operator CType(ByVal p1 As C1(Of t)) As Integer Return 1 End Operator Shared Widening Operator CType(ByVal p1 As Integer) As C1(Of t) Return Nothing End Operator Shared Operator -(ByVal p1 As C1(Of t), ByVal p2 As C1(Of t)) As C1(Of Short) Return Nothing End Operator Shared Operator +(ByVal p1 As C1(Of t), ByVal p2 As C1(Of t)) As C1(Of Integer) Return Nothing End Operator End Class Sub foo() For i As C1(Of Integer) = 1 To 10 Next End Sub End Module </file> </compilation>).VerifyDiagnostics( Diagnostic(ERRID.ERR_UnacceptableForLoopOperator2, "For i As C1(Of Integer) = 1 To 10").WithArguments("Public Shared Operator -(p1 As M1.C1(Of Integer), p2 As M1.C1(Of Integer)) As M1.C1(Of Short)", "M1.C1(Of Integer)"), Diagnostic(ERRID.ERR_ForLoopOperatorRequired2, "For i As C1(Of Integer) = 1 To 10").WithArguments("M1.C1(Of Integer)", "<="), Diagnostic(ERRID.ERR_ForLoopOperatorRequired2, "For i As C1(Of Integer) = 1 To 10").WithArguments("M1.C1(Of Integer)", ">=")) End Sub <Fact()> Public Sub BC33107ERR_IllegalCondTypeInIIF() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="IllegalCondTypeInIIF"> <file name="a.vb"> Option Infer On Imports System Class S1 Sub foo() Dim choice1 = 4 Dim choice2 = 5 Dim booleanVar = True Console.WriteLine(If(choice1 &lt; choice2, 1)) Console.WriteLine(If(booleanVar, "Test returns True.")) End Sub End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC33107: First operand in a binary 'If' expression must be a nullable value type, a reference type, or an unconstrained generic type. Console.WriteLine(If(choice1 &lt; choice2, 1)) ~~~~~~~~~~~~~~~~~ BC33107: First operand in a binary 'If' expression must be a nullable value type, a reference type, or an unconstrained generic type. Console.WriteLine(If(booleanVar, "Test returns True.")) ~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC33100ERR_CantSpecifyNullableOnBoth() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="CantSpecifyNullableOnBoth"> <file name="a.vb"> Class C1 Sub foo() Dim z? As Integer? End Sub End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC42024: Unused local variable: 'z'. Dim z? As Integer? ~ BC33100: Nullable modifier cannot be specified on both a variable and its type. Dim z? As Integer? ~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC36006ERR_BadAttributeConstructor2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BadAttributeConstructor2"> <file name="a.vb"><![CDATA[ Imports System Public Class MyAttr Inherits Attribute Public Sub New(ByVal i As Integer, ByRef V As Integer) End Sub End Class <MyAttr(1, 1)> Public Class MyTest End Class ]]></file> </compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_BadAttributeConstructor2, "MyAttr").WithArguments("Integer")) End Sub <Fact()> Public Sub BC36009ERR_GotoIntoUsing() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="GotoIntoUsing"> <file name="a.vb"> Imports System Class C1 Sub foo() If (True) GoTo label1 End If Using o as IDisposable = nothing label1: End Using End Sub End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC36009: 'GoTo label1' is not valid because 'label1' is inside a 'Using' statement that does not contain this statement. GoTo label1 ~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC36010ERR_UsingRequiresDisposePattern() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="UsingRequiresDisposePattern"> <file name="a.vb"> Class [IsNot] Public i As Integer End Class Class C1 Sub FOO() Dim c1 as [IsNot] = nothing, c2 As [IsNot] = nothing Using c1 IsNot c2 End Using Using new [IsNot]() End Using Using c3 As New [IsNot]() End Using Using c4 As [IsNot] = new [IsNot]() End Using End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36010: 'Using' operand of type 'Boolean' must implement 'System.IDisposable'. Using c1 IsNot c2 ~~~~~~~~~~~ BC36010: 'Using' operand of type '[IsNot]' must implement 'System.IDisposable'. Using new [IsNot]() ~~~~~~~~~~~~~ BC36010: 'Using' operand of type '[IsNot]' must implement 'System.IDisposable'. Using c3 As New [IsNot]() ~~~~~~~~~~~~~~~~~~~ BC36010: 'Using' operand of type '[IsNot]' must implement 'System.IDisposable'. Using c4 As [IsNot] = new [IsNot]() ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC36011ERR_UsingResourceVarNeedsInitializer() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="UsingResourceVarNeedsInitializer"> <file name="a.vb"> Option Strict On Option Infer Off Option Explicit Off Imports System Class MyDisposable Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub End Class Class C1 Public Shared Sub Main() Using foo As MyDisposable Console.WriteLine("Inside Using.") End Using Using foo2 As New MyDisposable() Console.WriteLine("Inside Using.") End Using End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36011: 'Using' resource variable must have an explicit initialization. Using foo As MyDisposable ~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC36012ERR_UsingResourceVarCantBeArray() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="UsingResourceVarNeedsInitializer"> <file name="a.vb"> Option Strict On Option Infer Off Option Explicit Off Imports System Structure MyDisposable Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub End Structure Class C1 Public Shared Sub Main() Using foo?() As MyDisposable = Nothing Console.WriteLine("Inside Using.") End Using End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36012: 'Using' resource variable type can not be array type. Using foo?() As MyDisposable = Nothing ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC36532ERR_LambdaBindingMismatch1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="LambdaBindingMismatch1"> <file name="a.vb"> Option Strict Off Imports System Public Module M Sub Main() Dim x As Func(Of Exception, Object) = Function(y$) y End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36532: Nested function does not have the same signature as delegate 'Func(Of Exception, Object)'. Dim x As Func(Of Exception, Object) = Function(y$) y ~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC36533ERR_CannotLiftByRefParamQuery1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="CannotLiftByRefParamQuery1"> <file name="a.vb"> Option Strict Off Imports System.Linq Imports System.Collections.Generic Public Module M Sub RunQuery(ByVal collection As List(Of Integer), _ ByRef filterValue As Integer) Dim queryResult = From num In collection _ Where num &lt; filterValue End Sub End Module </file> </compilation>, {Net40.SystemCore}) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36533: 'ByRef' parameter 'filterValue' cannot be used in a query expression. Where num &lt; filterValue ~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC36534ERR_ExpressionTreeNotSupported_NoError() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="ExpressionTreeNotSupported"> <file name="a.vb"> Imports System.Runtime.CompilerServices Imports System.Linq.Expressions Imports System Module M Sub Main() Dim x As Expression(Of Func(Of Action)) = Function() AddressOf 0.Foo End Sub &lt;Extension()&gt; Sub Foo(ByVal x As Integer) x = Nothing End Sub End Module </file> </compilation>, {Net40.SystemCore}) CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) End Sub <Fact()> Public Sub BC36534ERR_ExpressionTreeNotSupported() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="ExpressionTreeNotSupported"> <file name="a.vb"> Imports System.Runtime.CompilerServices Imports System.Linq.Expressions Imports System Module M Sub Main() Dim a As Integer Dim x As Expression(Of Func(Of Action)) = Function() Sub() a = 1 End Sub End Module </file> </compilation>, {Net40.SystemCore}) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36534: Expression cannot be converted into an expression tree. Dim x As Expression(Of Func(Of Action)) = Function() Sub() a = 1 ~~~~~ </expected>) End Sub <Fact()> Public Sub BC36535ERR_CannotLiftStructureMeQuery() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndReferences( <compilation name="CannotLiftStructureMeQuery"> <file name="a.vb"> Option Infer On Imports System.Linq Structure S1 Sub test() Dim col = New Integer() {1, 2, 3} Dim x = From i In col Let j = Me End Sub End Structure </file> </compilation>, {Net40.SystemCore}) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36535: Instance members and 'Me' cannot be used within query expressions in structures. Dim x = From i In col Let j = Me ~~ </expected>) End Sub <Fact()> Public Sub BC36535ERR_CannotLiftStructureMeQuery_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndReferences( <compilation name="CannotLiftStructureMeQuery_2"> <file name="a.vb"> Option Infer On Imports System.Linq Structure S1 Sub test() Dim col = New Integer() {1, 2, 3} Dim x = From i In col Let j = MyClass.ToString() End Sub End Structure </file> </compilation>, {Net40.SystemCore}) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36535: Instance members and 'Me' cannot be used within query expressions in structures. Dim x = From i In col Let j = MyClass.ToString() ~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC36536ERR_InferringNonArrayType1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="InferringNonArrayType1"> <file name="a.vb"> Option Strict Off Option Infer On Module M Sub Main() Dim x() = 1 End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36536: Variable cannot be initialized with non-array type 'Integer'. Dim x() = 1 ~ BC30311: Value of type 'Integer' cannot be converted to 'Object()'. Dim x() = 1 ~ </expected>) End Sub <Fact()> Public Sub BC36538ERR_ByRefParamInExpressionTree() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="ByRefParamInExpressionTree"> <file name="a.vb"> Imports System Imports System.Linq.Expressions Structure S1 Sub test() Foo(Function(ByRef x As Double, y As Integer) 1.1) End Sub End Structure Module Module1 Delegate Function MyFunc(Of T)(ByRef x As T, ByVal y As T) As T Sub Foo(Of T)(ByVal x As Expression(Of MyFunc(Of T))) End Sub End Module </file> </compilation>, references:={Net40.SystemCore}) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36538: References to 'ByRef' parameters cannot be converted to an expression tree. Foo(Function(ByRef x As Double, y As Integer) 1.1) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC36547ERR_DuplicateAnonTypeMemberName1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="DuplicateAnonTypeMemberName1"> <file name="a.vb"> Module M Sub Main() Dim at1 = New With {"".ToString} Dim at2 = New With {Key .a = 1, .GetHashCode = "A"} End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36547: Anonymous type member or property 'ToString' is already declared. Dim at1 = New With {"".ToString} ~~~~~~~~~~~ BC36547: Anonymous type member or property 'GetHashCode' is already declared. Dim at2 = New With {Key .a = 1, .GetHashCode = "A"} ~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC36548ERR_BadAnonymousTypeForExprTree() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndReferences( <compilation name="BadAnonymousTypeForExprTree"> <file name="a.vb"> Imports System Imports System.Linq.Expressions Module M Sub Main() Dim x As Expression(Of Func(Of Object)) = Function() New With {.x = 1, .y = .x} End Sub End Module </file> </compilation>, {Net40.System, Net40.SystemCore, Net40.MicrosoftVisualBasic}) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36548: Cannot convert anonymous type to an expression tree because a property of the type is used to initialize another property. Dim x As Expression(Of Func(Of Object)) = Function() New With {.x = 1, .y = .x} ~~ </expected>) End Sub <Fact()> Public Sub BC36549ERR_CannotLiftAnonymousType1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="CannotLiftAnonymousType1"> <file name="a.vb"> Imports System.Linq Module M Dim x = New With {.y = 1, .z = From y In "" Select .y} End Module </file> </compilation>, {Net40.SystemCore}) CompilationUtils.AssertTheseEmitDiagnostics(compilation, <expected> BC36549: Anonymous type property 'y' cannot be used in the definition of a lambda expression within the same initialization list. Dim x = New With {.y = 1, .z = From y In "" Select .y} ~~ </expected>) End Sub <Fact()> Public Sub BC36557ERR_NameNotMemberOfAnonymousType2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="NameNotMemberOfAnonymousType2"> <file name="a.vb"> Structure S1 Sub test() Dim x = New With {.prop1 = New With {.prop2 = .prop1}} End Sub End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36557: 'prop1' is not a member of '&lt;anonymous type&gt;'; it does not exist in the current context. Dim x = New With {.prop1 = New With {.prop2 = .prop1}} ~~~~~~ </expected>) End Sub <Fact()> Public Sub BC36558ERR_ExtensionAttributeInvalid() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Namespace System.Runtime.CompilerServices <AttributeUsage(AttributeTargets.Method Or AttributeTargets.Property Or AttributeTargets.Class)> Public Class ExtensionAttribute Inherits Attribute End Class End Namespace <System.Runtime.CompilerServices.Extension()> ' 1 Module Program <System.Runtime.CompilerServices.Extension()> ' 2 Sub boo(n As String) End Sub <System.Runtime.CompilerServices.Extension()> ' 3 Delegate Sub b() Sub Main(args As String()) End Sub End Module <System.Runtime.CompilerServices.Extension()> ' 4 Class T <System.Runtime.CompilerServices.Extension()> ' 5 Sub boo(n As String) End Sub End Class ]]> </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> <![CDATA[ BC36558: The custom-designed version of 'System.Runtime.CompilerServices.ExtensionAttribute' found by the compiler is not valid. Its attribute usage flags must be set to allow assemblies, classes, and methods. <System.Runtime.CompilerServices.Extension()> ' 1 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36558: The custom-designed version of 'System.Runtime.CompilerServices.ExtensionAttribute' found by the compiler is not valid. Its attribute usage flags must be set to allow assemblies, classes, and methods. <System.Runtime.CompilerServices.Extension()> ' 2 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30662: Attribute 'ExtensionAttribute' cannot be applied to 'b' because the attribute is not valid on this declaration type. <System.Runtime.CompilerServices.Extension()> ' 3 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36558: The custom-designed version of 'System.Runtime.CompilerServices.ExtensionAttribute' found by the compiler is not valid. Its attribute usage flags must be set to allow assemblies, classes, and methods. <System.Runtime.CompilerServices.Extension()> ' 4 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36550: 'Extension' attribute can be applied only to 'Module', 'Sub', or 'Function' declarations. Class T ~ BC36551: Extension methods can be defined only in modules. <System.Runtime.CompilerServices.Extension()> ' 5 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36558: The custom-designed version of 'System.Runtime.CompilerServices.ExtensionAttribute' found by the compiler is not valid. Its attribute usage flags must be set to allow assemblies, classes, and methods. <System.Runtime.CompilerServices.Extension()> ' 5 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]> </expected>) End Sub <Fact()> Public Sub BC36559ERR_AnonymousTypePropertyOutOfOrder1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="AnonymousTypePropertyOutOfOrder1"> <file name="a.vb"> Imports System.Runtime.CompilerServices Module M Sub Foo() Dim x = New With {.X = .X} End Sub &lt;Extension()&gt; Function X(ByVal y As Object) As Object Return Nothing End Function End Module </file> </compilation>, {Net40.SystemCore}) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36559: Anonymous type member property 'X' cannot be used to infer the type of another member property because the type of 'X' is not yet established. Dim x = New With {.X = .X} ~~ </expected>) End Sub <Fact()> Public Sub BC36560ERR_AnonymousTypeDisallowsTypeChar() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="AnonymousTypeDisallowsTypeChar"> <file name="a.vb"> Imports System.Runtime.CompilerServices Module M Sub Foo() Dim anon1 = New With {.ID$ = "abc"} Dim anon2 = New With {.ID$ = 42} End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36560: Type characters cannot be used in anonymous type declarations. Dim anon1 = New With {.ID$ = "abc"} ~~~~~~~~~~~~ BC36560: Type characters cannot be used in anonymous type declarations. Dim anon2 = New With {.ID$ = 42} ~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC36564ERR_DelegateBindingTypeInferenceFails() CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="DelegateBindingTypeInferenceFails"> <file name="a.vb"> Option Strict Off Imports System Public Module M Sub Main() Dim k = {Sub() Console.WriteLine(), AddressOf Foo} End Sub Sub Foo(Of T)() End Sub End Module </file> </compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_DelegateBindingTypeInferenceFails, "Foo")) End Sub <Fact()> Public Sub BC36574ERR_AnonymousTypeNeedField() CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="AnonymousTypeNeedField"> <file name="a.vb"> Public Module M Sub Main() Dim anonInstance = New With {} End Sub End Module </file> </compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_AnonymousTypeNeedField, "{")) End Sub <Fact()> Public Sub BC36582ERR_TooManyArgs2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="TooManyArgs2"> <file name="a.vb"> Module M1 Function IntegerExtension(ByVal a As Integer) As Integer Dim x1 As Integer x1.FooGeneric01(1) return nothing End Function End Module Module Extension01 &lt;System.Runtime.CompilerServices.Extension()&gt; Sub FooGeneric01(Of T1)(ByVal o As T1) End Sub End Module </file> </compilation>, {Net40.SystemCore}) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36582: Too many arguments to extension method 'Public Sub FooGeneric01()' defined in 'Extension01'. x1.FooGeneric01(1) ~ </expected>) End Sub <Fact(), WorkItem(543658, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543658")> Public Sub BC36583ERR_NamedArgAlsoOmitted3() CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="NamedArgAlsoOmitted3"> <file name="a.vb"> Imports System.Runtime.CompilerServices Public Module M &lt;Extension()&gt; _ Public Sub ABC(ByVal X As Integer, Optional ByVal Y As Byte = 0, _ Optional ByVal Z As Byte = 0) End Sub Sub FOO() Dim number As Integer number.ABC(, 4, Y:=5) End Sub End Module </file> </compilation>, {Net40.SystemCore}).VerifyDiagnostics(Diagnostic(ERRID.ERR_NamedArgAlsoOmitted3, "Y").WithArguments("Y", "Public Sub ABC([Y As Byte = 0], [Z As Byte = 0])", "M")) End Sub <Fact()> Public Sub BC36584ERR_NamedArgUsedTwice3() CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="NamedArgUsedTwice3"> <file name="a.vb"> Imports System.Runtime.CompilerServices Public Module M &lt;Extension()&gt; _ Public Sub ABC(ByVal X As Integer, ByVal Y As Byte, _ Optional ByVal Z As Byte = 0) End Sub Sub FOO() Dim number As Integer number.ABC(1, Y:=4, Y:=5) End Sub End Module </file> </compilation>, {Net40.SystemCore}).VerifyDiagnostics(Diagnostic(ERRID.ERR_NamedArgUsedTwice3, "Y").WithArguments("Y", "Public Sub ABC(Y As Byte, [Z As Byte = 0])", "M"), Diagnostic(ERRID.ERR_NamedArgUsedTwice3, "Y").WithArguments("Y", "Public Sub ABC(Y As Byte, [Z As Byte = 0])", "M")) End Sub <Fact()> Public Sub BC36589ERR_UnboundTypeParam3() CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="UnboundTypeParam3"> <file name="a.vb"> Delegate Function Func1(Of T0, S)(ByVal arg1 As T0) As S Delegate Sub Func2s(Of T0, T1, S)(ByVal arg1 As T0, ByVal arg2 As T1) Class C1 Function [Select](ByVal sel As Func1(Of Integer, Integer)) As C1 Return Me End Function End Class Module M1 &lt;System.Runtime.CompilerServices.Extension()&gt; _ Function GroupJoin(Of TKey, TResult)(ByVal col As C1, ByVal coll2 As C1, ByVal key As Func1(Of Integer, TKey), ByVal key2 As Func1(Of Integer, TKey), ByVal resultSelector As Func2s(Of Integer, System.Collections.Generic.IEnumerable(Of Integer), TResult)) As System.Collections.Generic.IEnumerable(Of TResult) Return Nothing End Function End Module Module M2 Sub foo() Dim x = New C1 Dim y = From i In x Select i Group Join j In x On i Equals j Into G = Group, Count() End Sub End Module </file> </compilation>, {Net40.SystemCore}).VerifyDiagnostics(Diagnostic(ERRID.ERR_QueryOperatorNotFound, "Group Join").WithArguments("GroupJoin")) End Sub <Fact()> Public Sub BC36590ERR_TooFewGenericArguments2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="TooFewGenericArguments2"> <file name="a.vb"> Module M1 Sub foo() Dim x As cLSIfooClass(Of Integer) x.foo(Of String)("RR") End Sub End Module Module Extension01 &lt;System.Runtime.CompilerServices.Extension()&gt; Sub foo(Of T1, t2, t3)(ByVal o As T1, ByVal p As t2, ByVal q As t3) End Sub End Module Public Interface Ifoo(Of t) End Interface Class cLSIfooClass(Of T) Implements Ifoo(Of T) End Class </file> </compilation>, {Net40.SystemCore}) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42104: Variable 'x' is used before it has been assigned a value. A null reference exception could result at runtime. x.foo(Of String)("RR") ~ BC36590: Too few type arguments to extension method 'Public Sub foo(Of t2, t3)(p As t2, q As t3)' defined in 'Extension01'. x.foo(Of String)("RR") ~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC36591ERR_TooManyGenericArguments2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="TooManyGenericArguments2"> <file name="a.vb"> Module M1 Sub foo() Dim x As cLSIfooClass(Of Integer) x.foo(Of Integer, String)("RR") End Sub End Module Module Extension01 &lt;System.Runtime.CompilerServices.Extension()&gt; Sub foo(Of T1, t2)(ByVal o As Ifoo(Of T1), ByVal p As t2) End Sub End Module Public Interface Ifoo(Of t) End Interface Class cLSIfooClass(Of T) Implements Ifoo(Of T) End Class </file> </compilation>, {Net40.SystemCore}) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42104: Variable 'x' is used before it has been assigned a value. A null reference exception could result at runtime. x.foo(Of Integer, String)("RR") ~ BC36591: Too many type arguments to extension method 'Public Sub foo(Of t2)(p As t2)' defined in 'Extension01'. x.foo(Of Integer, String)("RR") ~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC36593ERR_ExpectedQueryableSource() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="ExpectedQueryableSource"> <file name="a.vb"> Structure S1 Public Sub GetData() Dim query = From number In Me End Sub End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36593: Expression of type 'S1' is not queryable. Make sure you are not missing an assembly reference and/or namespace import for the LINQ provider. Dim query = From number In Me ~~ </expected>) End Sub <Fact()> Public Sub BC36594ERR_QueryOperatorNotFound() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="QueryOperatorNotFound"> <file name="a.vb"> Imports System Imports System.Collections.Generic Imports System.Linq Module M Sub Main() Dim x = (Aggregate y In {Function(e) 1} Into y()) End Sub End Module </file> </compilation>, {Net40.SystemCore}) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36594: Definition of method 'y' is not accessible in this context. Dim x = (Aggregate y In {Function(e) 1} Into y()) ~ </expected>) End Sub <Fact()> Public Sub BC36597ERR_CannotGotoNonScopeBlocksWithClosure() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="CannotGotoNonScopeBlocksWithClosure"> <file name="a.vb"> Module M Sub BadGoto() Dim x = 0 If x > 5 Then Label1: Dim y = 5 Dim f = Function() y End If GoTo Label1 End Sub End Module </file> </compilation>) AssertTheseEmitDiagnostics(compilation, <expected> BC36597: 'Goto Label1' is not valid because 'Label1' is inside a scope that defines a variable that is used in a lambda or query expression. GoTo Label1 ~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC36599ERR_QueryAnonymousTypeFieldNameInference() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="QueryAnonymousTypeFieldNameInference"> <file name="a.vb"> Option Strict On Imports System.Linq Module M Sub Foo() From x In {""} Select x, Nothing End Sub End Module </file> </compilation>, {Net40.SystemCore}) compilation.VerifyDiagnostics( Diagnostic(ERRID.ERR_QueryAnonymousTypeFieldNameInference, "Nothing"), Diagnostic(ERRID.ERR_ExpectedProcedure, "From x In {""""} Select x, Nothing")) ' Extra in Roslyn & NOT in vbc End Sub <Fact()> Public Sub BC36600ERR_QueryDuplicateAnonTypeMemberName1() CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="QueryDuplicateAnonTypeMemberName1"> <file name="a.vb"> Option Strict On Imports System Imports System.Runtime.CompilerServices Imports System.Linq Module M Sub Foo() Dim y = From x In "" Group By x Into Bar(), Bar(1) End Sub &lt;Extension()&gt; Function Bar(ByVal x As Object, ByVal y As Func(Of Char, Object)) As String Return Nothing End Function &lt;Extension()&gt; Function Bar(ByVal x As Object) As String Return Nothing End Function End Module </file> </compilation>, {Net40.SystemCore}).VerifyDiagnostics( Diagnostic(ERRID.ERR_QueryDuplicateAnonTypeMemberName1, "Bar").WithArguments("Bar")) End Sub <Fact()> Public Sub BC36601ERR_QueryAnonymousTypeDisallowsTypeChar() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="QueryAnonymousTypeDisallowsTypeChar"> <file name="a.vb"> Option Infer On Imports System.Linq Module M Dim q = From x% In New Integer() {1} End Module </file> </compilation>, {Net40.SystemCore}) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36601: Type characters cannot be used in range variable declarations. Dim q = From x% In New Integer() {1} ~~ </expected>) End Sub <Fact()> Public Sub BC36602ERR_ReadOnlyInClosure() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="ReadOnlyInClosure"> <file name="a.vb"> Class Class1 ReadOnly m As Integer Sub New() Dim f = Function() Test(m) End Sub Function Test(ByRef n As Integer) As String Return Nothing End Function End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36602: 'ReadOnly' variable cannot be the target of an assignment in a lambda expression inside a constructor. Dim f = Function() Test(m) ~ </expected>) End Sub <Fact()> Public Sub BC36602ERR_ReadOnlyInClosure1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="ReadOnlyInClosure"> <file name="a.vb"> Class Class1 ReadOnly property m As Integer Sub New() Dim f = Function() Test(m) End Sub Function Test(ByRef n As Integer) As String Return Nothing End Function End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36602: 'ReadOnly' variable cannot be the target of an assignment in a lambda expression inside a constructor. Dim f = Function() Test(m) ~ </expected>) End Sub <Fact()> Public Sub BC36603ERR_ExprTreeNoMultiDimArrayCreation() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="ExprTreeNoMultiDimArrayCreation"> <file name="a.vb"> Imports System Imports System.Linq.Expressions Module M Sub Main() Dim ex As Expression(Of Func(Of Object)) = Function() {{1}} End Sub End Module </file> </compilation>, {Net40.SystemCore}) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36603: Multi-dimensional array cannot be converted to an expression tree. Dim ex As Expression(Of Func(Of Object)) = Function() {{1}} ~~~~~ </expected>) End Sub <Fact()> Public Sub BC36604ERR_ExprTreeNoLateBind() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="ExprTreeNoLateBind"> <file name="a.vb"> Imports System Imports System.Linq.Expressions Module M Sub Main() Dim ex As Expression(Of Func(Of Object, Object)) = Function(x) x.Foo End Sub End Module </file> </compilation>, {Net40.SystemCore}) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36604: Late binding operations cannot be converted to an expression tree. Dim ex As Expression(Of Func(Of Object, Object)) = Function(x) x.Foo ~~~~~ </expected>) End Sub <Fact()> Public Sub BC36606ERR_QueryInvalidControlVariableName1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndReferences( <compilation name="QueryInvalidControlVariableName1"> <file name="a.vb"> Option Infer On Imports System.Linq Class M Dim x = From y In "" Select ToString() End Class </file> </compilation>, {Net40.SystemCore}) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36606: Range variable name cannot match the name of a member of the 'Object' class. Dim x = From y In "" Select ToString() ~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC36610ERR_QueryNameNotDeclared() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(references:={Net40.SystemCore}, source:= <compilation name="QueryNameNotDeclared"> <file name="a.vb"> Imports System Imports System.Linq Module M Sub Main() Dim c = From x In {1} Group By y = 0, z = y Into Count() End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36610: Name 'y' is either not declared or not in the current scope. Dim c = From x In {1} Group By y = 0, z = y Into Count() ~ </expected>) End Sub <Fact()> Public Sub BC36614ERR_QueryAnonTypeFieldXMLNameInference() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Imports System.Xml.Linq Imports System.Collections.Generic Imports System.Linq Imports <xmlns:ns="5"> Imports <xmlns:n-s="b"> Module M1 Sub foo() Dim x = From i In (<ns:e <%= <ns:e><%= "hello" %></ns:e> %>></ns:e>.<ns:e>) _ Where i.Value <> (<<%= <ns:e></ns:e>.Name %>></>.Value) _ Select <e><%= i %></e>.<ns:e-e>, i End Sub End Module ]]></file> </compilation>, references:=XmlReferences) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC36614: Range variable name cannot be inferred from an XML identifier that is not a valid Visual Basic identifier. Select <e><%= i %></e>.<ns:e-e>, i ~~~ ]]></errors>) End Sub <Fact()> Public Sub BC36617ERR_TypeCharOnAggregation() CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="TypeCharOnAggregation"> <file name="a.vb"> Option Strict On Imports System.Runtime.CompilerServices Imports System Imports System.Linq Module M Sub Foo() Dim y = From x In "" Group By x Into Bar$(1) End Sub &lt;Extension()&gt; Function Bar$(ByVal x As Object, ByVal y As Func(Of Char, Object)) Return Nothing End Function End Module </file> </compilation>, {Net40.SystemCore}).VerifyDiagnostics(Diagnostic(ERRID.ERR_TypeCharOnAggregation, "Bar$"), Diagnostic(ERRID.ERR_QueryAnonymousTypeDisallowsTypeChar, "Bar$")) End Sub <Fact()> Public Sub BC36625ERR_LambdaNotDelegate1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="LambdaNotDelegate1"> <file name="a.vb"> Module LambdaSyntax Sub LambdaSyntax() If Function() True Then ElseIf Function(x As Boolean) x Then End If End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36625: Lambda expression cannot be converted to 'Boolean' because 'Boolean' is not a delegate type. If Function() True Then ~~~~~~~~~~~~~~~ BC36625: Lambda expression cannot be converted to 'Boolean' because 'Boolean' is not a delegate type. ElseIf Function(x As Boolean) x Then ~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC36628ERR_CannotInferNullableForVariable1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="CannotInferNullableForVariable1"> <file name="a.vb"> Option Infer on Imports System Module M Sub Foo() Dim except? = New Exception Dim obj? = New Object Dim stringVar? = "Open the application." End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36628: A nullable type cannot be inferred for variable 'except'. Dim except? = New Exception ~~~~~~ BC36628: A nullable type cannot be inferred for variable 'obj'. Dim obj? = New Object ~~~ BC36628: A nullable type cannot be inferred for variable 'stringVar'. Dim stringVar? = "Open the application." ~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC36633ERR_IterationVariableShadowLocal2() CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="IterationVariableShadowLocal2"> <file name="a.vb"> Option Explicit Off Imports System Imports System.Linq Imports System.Collections.Generic Module M1 &lt;System.Runtime.CompilerServices.Extension()&gt; _ Sub Show(Of T)(ByVal collection As IEnumerable(Of T)) For Each element In collection Console.WriteLine(element) Next End Sub Sub Scen1() implicit = 1 'COMPILEERROR : BC36633, "implicit" Dim x = From implicit In New Integer() {1, 2, 3} Let implicit = jj Select implicit 'COMPILEERROR : BC36633, "implicit" Dim y = From i In New Integer() {1, 2, 3} Let implicit = i Select implicit 'COMPILEERROR : BC36633, "implicit" Dim z = From i In New Integer() {1, 2, 3} Let j = implicit Select implicit 'COMPILEERROR : BC36633, "implicit" Dim u = From i In New Integer() {1, 2, 3} Let j = implicit Group i By i Into implicit = Group 'COMPILEERROR : BC36633, "implicit" Dim v = From i In New Integer() {1, 2, 3} Let j = implicit Group implicit By i Into implicit() 'COMPILEERROR : BC36633, "implicit" Dim w = From i In New Integer() {1, 2, 3} Let j = implicit Group i By implicit Into implicit() 'COMPILEERROR : BC36633, "implicit", BC36633, "implicit" Dim a = From i In New Integer() {1, 2, 3} Let j = implicit Group implicit By implicit Into implicit() 'COMPILEERROR : BC36633, "implicit" Dim b = From i In New Integer() {1, 2, 3}, j In New Integer() {1, 2, 3} Let k = implicit Group Join implicit In New Integer() {1, 2, 3} On i Equals implicit Into implicit() 'COMPILEERROR : BC36633, "implicit" Dim c = From i In New Integer() {1, 2, 3}, j In New Integer() {1, 2, 3} Let k = implicit Group Join l In New Integer() {1, 2, 3} On i Equals l Into implicit = Group End Sub Sub Scen2() 'COMPILEERROR : BC36633, "implicit", BC36633, "implicit" Dim x = From implicit In New Integer() {1, 2, 3} Let implicit = jj Select implicit 'COMPILEERROR : BC36633, "implicit", BC36633, "implicit" Dim y = From i In New Integer() {1, 2, 3} Let implicit = i Select implicit 'COMPILEERROR : BC36633, "implicit" Dim z = From i In New Integer() {1, 2, 3} Let j = implicit Select implicit 'COMPILEERROR : BC36633, "implicit" Dim u = From i In New Integer() {1, 2, 3} Let j = implicit Group i By i Into implicit = Group 'COMPILEERROR : BC36633, "implicit" Dim v = From i In New Integer() {1, 2, 3} Let j = implicit Group implicit By i Into implicit() 'COMPILEERROR : BC36633, "implicit" Dim w = From i In New Integer() {1, 2, 3} Let j = implicit Group i By implicit Into implicit() 'COMPILEERROR : BC36633, "implicit", BC36633, "implicit" Dim a = From i In New Integer() {1, 2, 3} Let j = implicit Group implicit By implicit Into implicit() 'COMPILEERROR : BC36633, "implicit" Dim b = From i In New Integer() {1, 2, 3}, j In New Integer() {1, 2, 3} Let k = implicit Group Join implicit In New Integer() {1, 2, 3} On i Equals implicit Into implicit() 'COMPILEERROR : BC36633, "implicit" Dim c = From i In New Integer() {1, 2, 3}, j In New Integer() {1, 2, 3} Let k = implicit Group Join l In New Integer() {1, 2, 3} On i Equals l Into implicit = Group implicit = 1 End Sub End Module </file> </compilation>, {Net40.SystemCore}).VerifyDiagnostics(Diagnostic(ERRID.ERR_IterationVariableShadowLocal2, "implicit").WithArguments("implicit"), Diagnostic(ERRID.ERR_IterationVariableShadowLocal2, "implicit").WithArguments("implicit"), Diagnostic(ERRID.ERR_IterationVariableShadowLocal2, "implicit").WithArguments("implicit"), Diagnostic(ERRID.ERR_IterationVariableShadowLocal2, "implicit").WithArguments("implicit"), Diagnostic(ERRID.ERR_IterationVariableShadowLocal2, "implicit").WithArguments("implicit"), Diagnostic(ERRID.ERR_IterationVariableShadowLocal2, "implicit").WithArguments("implicit"), Diagnostic(ERRID.ERR_IterationVariableShadowLocal2, "implicit").WithArguments("implicit"), Diagnostic(ERRID.ERR_IterationVariableShadowLocal2, "implicit").WithArguments("implicit"), Diagnostic(ERRID.ERR_QueryOperatorNotFound, "implicit").WithArguments("implicit"), Diagnostic(ERRID.ERR_IterationVariableShadowLocal2, "implicit").WithArguments("implicit"), Diagnostic(ERRID.ERR_IterationVariableShadowLocal2, "implicit").WithArguments("implicit"), Diagnostic(ERRID.ERR_QueryOperatorNotFound, "implicit").WithArguments("implicit"), Diagnostic(ERRID.ERR_QueryDuplicateAnonTypeMemberName1, "implicit").WithArguments("implicit"), Diagnostic(ERRID.ERR_IterationVariableShadowLocal2, "implicit").WithArguments("implicit"), Diagnostic(ERRID.ERR_IterationVariableShadowLocal2, "implicit").WithArguments("implicit"), Diagnostic(ERRID.ERR_QueryOperatorNotFound, "implicit").WithArguments("implicit"), Diagnostic(ERRID.ERR_QueryDuplicateAnonTypeMemberName1, "implicit").WithArguments("implicit"), Diagnostic(ERRID.ERR_IterationVariableShadowLocal2, "implicit").WithArguments("implicit"), Diagnostic(ERRID.ERR_QueryOperatorNotFound, "implicit").WithArguments("implicit"), Diagnostic(ERRID.ERR_IterationVariableShadowLocal2, "implicit").WithArguments("implicit"), Diagnostic(ERRID.ERR_IterationVariableShadowLocal2, "implicit").WithArguments("implicit"), Diagnostic(ERRID.WRN_DefAsgUseNullRef, "jj").WithArguments("jj"), Diagnostic(ERRID.ERR_IterationVariableShadowLocal2, "implicit").WithArguments("implicit"), Diagnostic(ERRID.ERR_IterationVariableShadowLocal2, "implicit").WithArguments("implicit"), Diagnostic(ERRID.ERR_IterationVariableShadowLocal2, "implicit").WithArguments("implicit"), Diagnostic(ERRID.ERR_IterationVariableShadowLocal2, "implicit").WithArguments("implicit"), Diagnostic(ERRID.ERR_IterationVariableShadowLocal2, "implicit").WithArguments("implicit"), Diagnostic(ERRID.ERR_IterationVariableShadowLocal2, "implicit").WithArguments("implicit"), Diagnostic(ERRID.ERR_IterationVariableShadowLocal2, "implicit").WithArguments("implicit"), Diagnostic(ERRID.ERR_IterationVariableShadowLocal2, "implicit").WithArguments("implicit"), Diagnostic(ERRID.ERR_QueryOperatorNotFound, "implicit").WithArguments("implicit"), Diagnostic(ERRID.ERR_IterationVariableShadowLocal2, "implicit").WithArguments("implicit"), Diagnostic(ERRID.ERR_IterationVariableShadowLocal2, "implicit").WithArguments("implicit"), Diagnostic(ERRID.ERR_QueryOperatorNotFound, "implicit").WithArguments("implicit"), Diagnostic(ERRID.ERR_QueryDuplicateAnonTypeMemberName1, "implicit").WithArguments("implicit"), Diagnostic(ERRID.ERR_IterationVariableShadowLocal2, "implicit").WithArguments("implicit"), Diagnostic(ERRID.ERR_IterationVariableShadowLocal2, "implicit").WithArguments("implicit"), Diagnostic(ERRID.ERR_QueryOperatorNotFound, "implicit").WithArguments("implicit"), Diagnostic(ERRID.ERR_QueryDuplicateAnonTypeMemberName1, "implicit").WithArguments("implicit"), Diagnostic(ERRID.ERR_IterationVariableShadowLocal2, "implicit").WithArguments("implicit"), Diagnostic(ERRID.ERR_QueryOperatorNotFound, "implicit").WithArguments("implicit"), Diagnostic(ERRID.ERR_IterationVariableShadowLocal2, "implicit").WithArguments("implicit"), Diagnostic(ERRID.ERR_IterationVariableShadowLocal2, "implicit").WithArguments("implicit"), Diagnostic(ERRID.WRN_DefAsgUseNullRef, "jj").WithArguments("jj"), Diagnostic(ERRID.WRN_DefAsgUseNullRef, "implicit").WithArguments("implicit")) End Sub <Fact()> Public Sub BC36635ERR_LambdaInSelectCaseExpr() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="LambdaInSelectCaseExpr"> <file name="a.vb"> Public Module M Sub LambdaAttribute() Select Case (Function(arg) arg Is Nothing) End Select End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36635: Lambda expressions are not valid in the first expression of a 'Select Case' statement. Select Case (Function(arg) arg Is Nothing) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC36638ERR_CannotLiftStructureMeLambda() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="CannotLiftStructureMeLambda"> <file name="a.vb"> Imports System Imports System.Collections.Generic Imports System.Linq Imports System.Linq.Expressions Structure S Sub New(ByVal x As S) Dim a As Expression(Of Action) = Sub() ToString() Dim b As Expression(Of Action) = Sub() Console.WriteLine(Me) End Sub End Structure </file> </compilation>, references:={Net40.SystemCore}) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36638: Instance members and 'Me' cannot be used within a lambda expression in structures. Dim a As Expression(Of Action) = Sub() ToString() ~~~~~~~~ BC36638: Instance members and 'Me' cannot be used within a lambda expression in structures. Dim b As Expression(Of Action) = Sub() Console.WriteLine(Me) ~~ </expected>) End Sub <Fact()> Public Sub BC36638ERR_CannotLiftStructureMeLambda_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="CannotLiftStructureMeLambda_2"> <file name="a.vb"> Imports System Structure S Sub New(ByVal x As S) Dim a As Action = Sub() ToString() Dim b As Action = Sub() Console.WriteLine(Me) End Sub End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36638: Instance members and 'Me' cannot be used within a lambda expression in structures. Dim a As Action = Sub() ToString() ~~~~~~~~ BC36638: Instance members and 'Me' cannot be used within a lambda expression in structures. Dim b As Action = Sub() Console.WriteLine(Me) ~~ </expected>) End Sub <Fact()> Public Sub BC36638ERR_CannotLiftStructureMeLambda_3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="CannotLiftStructureMeLambda_3"> <file name="a.vb"> Imports System Structure S Sub New(ByVal x As S) Dim a As Action = Sub() MyClass.ToString() Dim b As Action = Sub() Console.WriteLine(MyClass.ToString()) End Sub End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36638: Instance members and 'Me' cannot be used within a lambda expression in structures. Dim a As Action = Sub() MyClass.ToString() ~~~~~~~ BC36638: Instance members and 'Me' cannot be used within a lambda expression in structures. Dim b As Action = Sub() Console.WriteLine(MyClass.ToString()) ~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC36639ERR_CannotLiftByRefParamLambda1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="CannotLiftByRefParamLambda1"> <file name="a.vb"> Imports System Public Module M Sub Foo(ByRef x As String) Dim a As Action = Sub() Console.WriteLine(x) End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36639: 'ByRef' parameter 'x' cannot be used in a lambda expression. Dim a As Action = Sub() Console.WriteLine(x) ~ </expected>) End Sub <Fact()> Public Sub BC36640ERR_CannotLiftRestrictedTypeLambda() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="CannotLiftRestrictedTypeLambda"> <file name="a.vb"> Imports System Public Module M Sub LiftRestrictedType() Dim x As ArgIterator = Nothing Dim f As Action = Sub() x.GetNextArgType().GetModuleHandle() End Sub End Module </file> </compilation>) compilation.VerifyEmitDiagnostics( Diagnostic(ERRID.ERR_CannotLiftRestrictedTypeLambda, "x").WithArguments("System.ArgIterator")) End Sub <Fact()> Public Sub BC36641ERR_LambdaParamShadowLocal1() ' Roslyn - extra warning CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="LambdaParamShadowLocal1"> <file name="a.vb"> Module M1 Class Class1 Function FOO() Dim x = Function() As Object Dim z = Function() Sub(FOO) FOO = FOO End Function ' 1 End Function ' 2 End Class End Module </file> </compilation>).AssertTheseDiagnostics(<expected><![CDATA[ BC36641: Lambda parameter 'FOO' hides a variable in an enclosing block, a previously defined range variable, or an implicitly declared variable in a query expression. Dim z = Function() Sub(FOO) FOO = FOO ~~~ BC42105: Function '<anonymous method>' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used. End Function ' 1 ~~~~~~~~~~~~ BC42105: Function 'FOO' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used. End Function ' 2 ~~~~~~~~~~~~ ]]></expected>) End Sub <Fact()> Public Sub BC36641ERR_LambdaParamShadowLocal1_2() CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="LambdaParamShadowLocal1"> <file name="a.vb"> Option Infer Off Module Program Sub Main(args As String()) Dim X = 1 Dim Y = 1 Dim S = If(True, _ Function(x As Integer) As Integer Return 0 End Function, Y = Y + 1) End Sub End Module </file> </compilation>).VerifyDiagnostics( Diagnostic(ERRID.ERR_LambdaParamShadowLocal1, "x").WithArguments("x") ) End Sub <Fact()> Public Sub BC36642ERR_StrictDisallowImplicitObjectLambda() CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="StrictDisallowImplicitObjectLambda"> <file name="a.vb"> Option Strict On Module M Sub Main() Dim x = Function(y) 1 End Sub End Module </file> </compilation>).VerifyDiagnostics( Diagnostic(ERRID.ERR_StrictDisallowImplicitObjectLambda, "y") ) End Sub <Fact> Public Sub BC36645ERR_TypeInferenceFailureAddressOfLateBound() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="TypeInferenceFailure2"> <file name="a.vb"> Option Strict Off Imports System Class Module1 Sub Foo(Of T As Structure, S As Structure)(ByVal x As T, ByVal f As Func(Of T?, S?)) End Sub Class Class2 Function Bar(ByVal x As Integer) As Integer? Return Nothing End Function End Class Shared Sub Main() Dim o As Object = New Class2 Foo(1, AddressOf o.Bar) Dim qo As IQueryable(Of Integer) Dim r = qo.Select(AddressOf o.Fee) End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36645: Data type(s) of the type parameter(s) in method 'Public Sub Foo(Of T As Structure, S As Structure)(x As T, f As Func(Of T?, S?))' cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error. Foo(1, AddressOf o.Bar) ~~~ BC30002: Type 'IQueryable' is not defined. Dim qo As IQueryable(Of Integer) ~~~~~~~~~~~~~~~~~~~~~~ BC42104: Variable 'qo' is used before it has been assigned a value. A null reference exception could result at runtime. Dim r = qo.Select(AddressOf o.Fee) ~~ </expected>) End Sub <Fact()> Public Sub BC36657ERR_TypeInferenceFailureNoBest2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="TypeInferenceFailureNoBest2"> <file name="a.vb"> Option Strict On Imports System Public Module M Sub Main() Dim x As Action(Of String()) Dim y As Action(Of Object()) Foo(x, y) End Sub Sub Foo(Of T)(ByVal x As Action(Of T()), ByVal y As Action(Of T())) End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36657: Data type(s) of the type parameter(s) in method 'Public Sub Foo(Of T)(x As Action(Of T()), y As Action(Of 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. Foo(x, y) ~~~ BC42104: Variable 'x' is used before it has been assigned a value. A null reference exception could result at runtime. Foo(x, y) ~ BC42104: Variable 'y' is used before it has been assigned a value. A null reference exception could result at runtime. Foo(x, y) ~ </expected>) End Sub <Fact()> Public Sub BC36663ERR_DelegateBindingMismatchStrictOff2() CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="DelegateBindingMismatchStrictOff2"> <file name="a.vb"> Option Strict On Public Module M Sub Main() Dim k = {Function() "", AddressOf System.Console.Read} End Sub End Module </file> </compilation>).VerifyDiagnostics( Diagnostic(ERRID.ERR_DelegateBindingMismatchStrictOff2, "System.Console.Read").WithArguments("Public Shared Overloads Function Read() As Integer", "AnonymousType Function <generated method>() As String")) End Sub <WorkItem(528732, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528732")> <Fact()> Public Sub BC36666ERR_InaccessibleReturnTypeOfMember2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="InaccessibleReturnTypeOfMember2"> <file name="a.vb"> Option Infer On Imports System Class TestClass Dim pt As PrivateType Public name As PrivateType Property prop As PrivateType Protected Class PrivateType End Class Function foo() As PrivateType Return pt End Function End Class Module Module1 Sub Main() Dim tc As TestClass = New TestClass() Console.WriteLine(tc.name) Console.WriteLine(tc.foo) Console.WriteLine(tc.prop) End Sub End Module </file> </compilation>).VerifyDiagnostics( Diagnostic(ERRID.ERR_AccessMismatch6, "PrivateType").WithArguments("name", "TestClass.PrivateType", "namespace", "<Default>", "class", "TestClass"), Diagnostic(ERRID.ERR_AccessMismatch6, "PrivateType").WithArguments("prop", "TestClass.PrivateType", "namespace", "<Default>", "class", "TestClass"), Diagnostic(ERRID.ERR_AccessMismatch6, "PrivateType").WithArguments("foo", "TestClass.PrivateType", "namespace", "<Default>", "class", "TestClass"), Diagnostic(ERRID.ERR_InaccessibleReturnTypeOfMember2, "tc.name").WithArguments("Public TestClass.name As TestClass.PrivateType"), Diagnostic(ERRID.ERR_InaccessibleReturnTypeOfMember2, "tc.foo").WithArguments("Public Function TestClass.foo() As TestClass.PrivateType"), Diagnostic(ERRID.ERR_InaccessibleReturnTypeOfMember2, "tc.prop").WithArguments("Public Property TestClass.prop As TestClass.PrivateType")) End Sub <Fact()> Public Sub BC36667ERR_LocalNamedSameAsParamInLambda1() CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="LocalNamedSameAsParamInLambda1"> <file name="a.vb"> Module M1 Sub Fun() Dim x = Sub(y) Dim y = 5 End Sub End Sub End Module </file> </compilation>).VerifyDiagnostics( Diagnostic(ERRID.ERR_LocalNamedSameAsParamInLambda1, "y").WithArguments("y") ) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:="https://github.com/dotnet/roslyn/issues/29568")> Public Sub BC36670ERR_LambdaBindingMismatch2() CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="LambdaBindingMismatch2"> <file name="a.vb"> Imports System Module M1 Sub Action() End Sub Sub [Sub](ByRef x As Action) x = Sub() Action() x() End Sub Sub Fun() [Sub]((Sub(x As Integer(,)) Action() End Sub)) End Sub End Module </file> </compilation>, {Net40.SystemCore}).VerifyDiagnostics(Diagnostic(ERRID.ERR_LambdaBindingMismatch2, <![CDATA[Sub(x As Integer(,)) Action() End Sub]]>.Value.Replace(vbLf, Environment.NewLine)).WithArguments("System.Action") ) End Sub ' Different error <ConditionalFact(GetType(WindowsOnly), Reason:="https://github.com/dotnet/roslyn/issues/29531")> Public Sub BC36675ERR_StatementLambdaInExpressionTree() CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="StatementLambdaInExpressionTree"> <file name="a.vb"> Imports System Module M1 Sub Fun() Dim x = 1 Dim y As System.Linq.Expressions.Expression(Of func(Of Integer)) = Function() Return x End Function End Sub End Module </file> </compilation>, {Net40.SystemCore}).VerifyDiagnostics( Diagnostic(ERRID.ERR_StatementLambdaInExpressionTree, <![CDATA[Function() Return x End Function]]>.Value.Replace(vbLf, Environment.NewLine))) End Sub <Fact()> Public Sub BC36709ERR_DelegateBindingMismatchStrictOff3() CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="DelegateBindingMismatchStrictOff3"> <file name="a.vb"> Option Strict On Module M Delegate Function del1g(Of g)(ByVal x As g) As String Sub foo() Dim o As New cls1 Dim x As New del1g(Of String)(AddressOf o.moo(Of Integer)) End Sub End Module Class cls1 Public Function foo(Of G)(ByVal y As G) As String Return "Instance" End Function End Class Module m1 &lt;System.Runtime.CompilerServices.Extension()&gt; _ Public Function moo(Of G)(ByVal this As cls1, ByVal y As G) As String Return "Extension" End Function End Module </file> </compilation>, {Net40.SystemCore}).VerifyDiagnostics( Diagnostic(ERRID.ERR_DelegateBindingMismatchStrictOff3, "o.moo(Of Integer)").WithArguments("Public Function moo(Of Integer)(y As Integer) As String", "Delegate Function M.del1g(Of String)(x As String) As String", "m1")) End Sub <Fact()> Public Sub BC36710ERR_DelegateBindingIncompatible3() Dim compilation = CreateCompilation( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports System.Runtime.CompilerServices Imports System.Xml.Linq Delegate Function D() As Object Module M Private F1 As New D(AddressOf <x/>.E1) Private F2 As New D(AddressOf <x/>.E2) <Extension()> Function E1(x As XElement) As Object Return Nothing End Function <Extension()> Function E2(x As XElement, y As Object) As Object Return Nothing End Function End Module ]]></file> </compilation>, targetFramework:=TargetFramework.Mscorlib45AndVBRuntime, references:=Net451XmlReferences) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC36710: Extension Method 'Public Function E2(y As Object) As Object' defined in 'M' does not have a signature compatible with delegate 'Delegate Function D() As Object'. Private F2 As New D(AddressOf <x/>.E2) ~~~~~~~ ]]></errors>) End Sub <Fact()> Public Sub BC36718ERR_NotACollection1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="NotACollection1"> <file name="a.vb"> Module M1 Dim a As New Object() From {} End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36718: Cannot initialize the type 'Object' with a collection initializer because it is not a collection type. Dim a As New Object() From {} ~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC36719ERR_NoAddMethod1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="NoAddMethod1"> <file name="a.vb"> Imports System.Collections.Generic Module M1 Dim x As UDCollection1(Of Integer) = New UDCollection1(Of Integer) From {1, 2, 3} End Module Class UDCollection1(Of t) Implements IEnumerable(Of t) Public Function GetEnumerator() As System.Collections.Generic.IEnumerator(Of t) Implements System.Collections.Generic.IEnumerable(Of t).GetEnumerator Return Nothing End Function Public Function GetEnumerator1() As System.Collections.IEnumerator Implements System.Collections.IEnumerable.GetEnumerator Return Nothing End Function End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36719: Cannot initialize the type 'UDCollection1(Of Integer)' with a collection initializer because it does not have an accessible 'Add' method. Dim x As UDCollection1(Of Integer) = New UDCollection1(Of Integer) From {1, 2, 3} ~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC36721ERR_EmptyAggregateInitializer() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="NoAddMethod1"> <file name="a.vb"> Option Strict On Imports System.Collections.Generic Public Module X Sub Foo(ByVal x As Boolean) Dim y As New List(Of Integer) From {1, 2, {}} End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36721: An aggregate collection initializer entry must contain at least one element. Dim y As New List(Of Integer) From {1, 2, {}} ~~ </expected>) End Sub <Fact()> Public Sub BC36734ERR_LambdaTooManyTypesObjectDisallowed() CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="LambdaTooManyTypesObjectDisallowed"> <file name="a.vb"> Option Strict On Imports System Module M1 Dim y As Action(Of Integer) = Function(a As Integer) Return 1 Return "" End Function End Module </file> </compilation>).VerifyDiagnostics( Diagnostic(ERRID.ERR_LambdaTooManyTypesObjectDisallowed, "Function(a As Integer)") ) End Sub <Fact()> Public Sub BC36751ERR_LambdaNoType() CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="LambdaNoType"> <file name="a.vb"> Module M1 Dim x = Function() Return AddressOf System.Console.WriteLine End Function End Module </file> </compilation>).VerifyDiagnostics( Diagnostic(ERRID.ERR_LambdaNoType, "Function()")) End Sub ' Different error <Fact()> Public Sub BC36754ERR_VarianceConversionFailedOut6() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="VarianceConversionFailedOut6"> <file name="a.vb"> Option Strict On Interface IVariance(Of Out T) : Function Foo() As T : End Interface Interface IVariance2(Of In T) : Sub Foo(ByVal s As T) : End Interface Class Variance(Of T) : Implements IVariance(Of T), IVariance2(Of T) Public Function Foo() As T Implements IVariance(Of T).Foo End Function Public Sub Foo1(ByVal s As T) Implements IVariance2(Of T).Foo End Sub End Class Module M1 Dim x As IVariance(Of Double) = New Variance(Of Short) End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36754: 'Variance(Of Short)' cannot be converted to 'IVariance(Of Double)' because 'Short' is not derived from 'Double', as required for the 'Out' generic parameter 'T' in 'Interface IVariance(Of Out T)'. Dim x As IVariance(Of Double) = New Variance(Of Short) ~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub ' Different error <Fact()> Public Sub BC36755ERR_VarianceConversionFailedIn6() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="VarianceConversionFailedIn6"> <file name="a.vb"> Option Strict On Interface IVariance(Of Out T) : Function Foo() As T : End Interface Interface IVariance2(Of In T) : Sub Foo(ByVal s As T) : End Interface Class Variance(Of T) : Implements IVariance(Of T), IVariance2(Of T) Public Function Foo() As T Implements IVariance(Of T).Foo End Function Public Sub Foo1(ByVal s As T) Implements IVariance2(Of T).Foo End Sub End Class Module M1 Dim x As IVariance2(Of Short) = New Variance(Of Double) End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36755: 'Variance(Of Double)' cannot be converted to 'IVariance2(Of Short)' because 'Short' is not derived from 'Double', as required for the 'In' generic parameter 'T' in 'Interface IVariance2(Of In T)'. Dim x As IVariance2(Of Short) = New Variance(Of Double) ~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub ' Different error <Fact()> Public Sub BC36756ERR_VarianceIEnumerableSuggestion3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="VarianceIEnumerableSuggestion3"> <file name="a.vb"> Imports System.Collections.Generic Public Class Animals : End Class Public Class Cheetah : Inherits Animals : End Class Module M1 Dim x As List(Of Animals) = New List(Of Cheetah) End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36756: 'List(Of Cheetah)' cannot be converted to 'List(Of Animals)'. Consider using 'IEnumerable(Of Animals)' instead. Dim x As List(Of Animals) = New List(Of Cheetah) ~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC36757ERR_VarianceConversionFailedTryOut4() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="VarianceConversionFailedTryOut4"> <file name="a.vb"> Option Strict On Public Class Animals : End Class Public Class Cheetah : Inherits Animals : End Class Interface IFoo(Of T) : End Interface Class MyFoo(Of T) Implements IFoo(Of T) End Class Module M1 Dim x As IFoo(Of Animals) = New MyFoo(Of Cheetah) End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36757: 'MyFoo(Of Cheetah)' cannot be converted to 'IFoo(Of Animals)'. Consider changing the 'T' in the definition of 'Interface IFoo(Of T)' to an Out type parameter, 'Out T'. Dim x As IFoo(Of Animals) = New MyFoo(Of Cheetah) ~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub ' Different error <Fact()> Public Sub BC36758ERR_VarianceConversionFailedTryIn4() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="VarianceConversionFailedTryIn4"> <file name="a.vb"> Option Strict On Public Class Animals : End Class Public Class Vertebrates : Inherits Animals : End Class Public Class Mammals : Inherits Vertebrates : End Class Public Class Carnivora : Inherits Mammals : End Class Class Variance(Of T) Interface IVariance(Of In S, Out R) End Interface End Class Class Variance2(Of T, R As New) Implements Variance(Of T).IVariance(Of T, R) End Class Module M1 Dim x As Variance(Of Mammals).IVariance(Of Mammals, Mammals) = New Variance2(Of Animals, Carnivora) End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36758: 'Variance2(Of Animals, Carnivora)' cannot be converted to 'Variance(Of Mammals).IVariance(Of Mammals, Mammals)'. Consider changing the 'T' in the definition of 'Class Variance(Of T)' to an In type parameter, 'In T'. Dim x As Variance(Of Mammals).IVariance(Of Mammals, Mammals) = New Variance2(Of Animals, Carnivora) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC36760ERR_IdentityDirectCastForFloat() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="LambdaParamShadowLocal1"> <file name="a.vb"> Module Test Sub Main() Dim a As Double = 1 Dim b As Integer = DirectCast(a, Double) * 1000 End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36760: Using DirectCast operator to cast a floating-point value to the same type is not supported. Dim b As Integer = DirectCast(a, Double) * 1000 ~ </expected>) End Sub <Fact()> Public Sub BC36807ERR_TypeDisallowsElements() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports System.Collections.Generic Imports System.Xml.Linq Class MyElement Inherits XElement Public Sub New(name As XName) MyBase.New(name) End Sub End Class Module M Function F(Of T)() As T Return Nothing End Function Sub M() Dim x As Object x = F(Of Object).<x> x = F(Of XObject).<x> x = F(Of XContainer).<x> x = F(Of XElement).<x> x = F(Of XDocument).<x> x = F(Of XAttribute).<x> x = F(Of MyElement).<x> x = F(Of Object()).<x> x = F(Of XObject()).<x> x = F(Of XContainer()).<x> x = F(Of XElement()).<x> x = F(Of XDocument()).<x> x = F(Of XAttribute()).<x> x = F(Of MyElement()).<x> x = F(Of IEnumerable(Of Object)).<x> x = F(Of IEnumerable(Of XObject)).<x> x = F(Of IEnumerable(Of XContainer)).<x> x = F(Of IEnumerable(Of XElement)).<x> x = F(Of IEnumerable(Of XDocument)).<x> x = F(Of IEnumerable(Of XAttribute)).<x> x = F(Of IEnumerable(Of MyElement)).<x> End Sub End Module ]]></file> </compilation>, references:=XmlReferences) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC31168: XML axis properties do not support late binding. x = F(Of Object).<x> ~~~~~~~~~~~~~~~~ BC36807: XML elements cannot be selected from type 'XObject'. x = F(Of XObject).<x> ~~~~~~~~~~~~~~~~~ BC36807: XML elements cannot be selected from type 'XAttribute'. x = F(Of XAttribute).<x> ~~~~~~~~~~~~~~~~~~~~ BC36807: XML elements cannot be selected from type 'Object()'. x = F(Of Object()).<x> ~~~~~~~~~~~~~~~~~~ BC36807: XML elements cannot be selected from type 'XObject()'. x = F(Of XObject()).<x> ~~~~~~~~~~~~~~~~~~~ BC36807: XML elements cannot be selected from type 'XAttribute()'. x = F(Of XAttribute()).<x> ~~~~~~~~~~~~~~~~~~~~~~ BC36807: XML elements cannot be selected from type 'IEnumerable(Of Object)'. x = F(Of IEnumerable(Of Object)).<x> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36807: XML elements cannot be selected from type 'IEnumerable(Of XObject)'. x = F(Of IEnumerable(Of XObject)).<x> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36807: XML elements cannot be selected from type 'IEnumerable(Of XAttribute)'. x = F(Of IEnumerable(Of XAttribute)).<x> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></errors>) End Sub <Fact()> Public Sub BC36808ERR_TypeDisallowsAttributes() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports System.Collections.Generic Imports System.Xml.Linq Class MyElement Inherits XElement Public Sub New(name As XName) MyBase.New(name) End Sub End Class Module M Function F(Of T)() As T Return Nothing End Function Sub M() Dim x As Object x = F(Of Object).@a x = F(Of XObject).@a x = F(Of XContainer).@a x = F(Of XElement).@a x = F(Of XDocument).@a x = F(Of XAttribute).@a x = F(Of MyElement).@a x = F(Of Object()).@a x = F(Of XObject()).@a x = F(Of XContainer()).@a x = F(Of XElement()).@a x = F(Of XDocument()).@a x = F(Of XAttribute()).@a x = F(Of MyElement()).@a x = F(Of IEnumerable(Of Object)).@a x = F(Of IEnumerable(Of XObject)).@a x = F(Of IEnumerable(Of XContainer)).@a x = F(Of IEnumerable(Of XElement)).@a x = F(Of IEnumerable(Of XDocument)).@a x = F(Of IEnumerable(Of XAttribute)).@a x = F(Of IEnumerable(Of MyElement)).@a End Sub End Module ]]></file> </compilation>, references:=XmlReferences) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC31168: XML axis properties do not support late binding. x = F(Of Object).@a ~~~~~~~~~~~~~~~ BC36808: XML attributes cannot be selected from type 'XObject'. x = F(Of XObject).@a ~~~~~~~~~~~~~~~~ BC36808: XML attributes cannot be selected from type 'XContainer'. x = F(Of XContainer).@a ~~~~~~~~~~~~~~~~~~~ BC36808: XML attributes cannot be selected from type 'XDocument'. x = F(Of XDocument).@a ~~~~~~~~~~~~~~~~~~ BC36808: XML attributes cannot be selected from type 'XAttribute'. x = F(Of XAttribute).@a ~~~~~~~~~~~~~~~~~~~ BC36808: XML attributes cannot be selected from type 'Object()'. x = F(Of Object()).@a ~~~~~~~~~~~~~~~~~ BC36808: XML attributes cannot be selected from type 'XObject()'. x = F(Of XObject()).@a ~~~~~~~~~~~~~~~~~~ BC36808: XML attributes cannot be selected from type 'XContainer()'. x = F(Of XContainer()).@a ~~~~~~~~~~~~~~~~~~~~~ BC36808: XML attributes cannot be selected from type 'XDocument()'. x = F(Of XDocument()).@a ~~~~~~~~~~~~~~~~~~~~ BC36808: XML attributes cannot be selected from type 'XAttribute()'. x = F(Of XAttribute()).@a ~~~~~~~~~~~~~~~~~~~~~ BC36808: XML attributes cannot be selected from type 'IEnumerable(Of Object)'. x = F(Of IEnumerable(Of Object)).@a ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36808: XML attributes cannot be selected from type 'IEnumerable(Of XObject)'. x = F(Of IEnumerable(Of XObject)).@a ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36808: XML attributes cannot be selected from type 'IEnumerable(Of XContainer)'. x = F(Of IEnumerable(Of XContainer)).@a ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36808: XML attributes cannot be selected from type 'IEnumerable(Of XDocument)'. x = F(Of IEnumerable(Of XDocument)).@a ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36808: XML attributes cannot be selected from type 'IEnumerable(Of XAttribute)'. x = F(Of IEnumerable(Of XAttribute)).@a ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></errors>) ' Note: The last error above ("BC30518: Overload resolution failed ...") ' should not be generated after variance conversions are supported. End Sub <Fact()> Public Sub BC36809ERR_TypeDisallowsDescendants() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports System.Collections.Generic Imports System.Xml.Linq Class MyElement Inherits XElement Public Sub New(name As XName) MyBase.New(name) End Sub End Class Module M Function F(Of T)() As T Return Nothing End Function Sub M() Dim x As Object x = F(Of Object)...<x> x = F(Of XObject)...<x> x = F(Of XContainer)...<x> x = F(Of XElement)...<x> x = F(Of XDocument)...<x> x = F(Of XAttribute)...<x> x = F(Of MyElement)...<x> x = F(Of Object())...<x> x = F(Of XObject())...<x> x = F(Of XContainer())...<x> x = F(Of XElement())...<x> x = F(Of XDocument())...<x> x = F(Of XAttribute())...<x> x = F(Of MyElement())...<x> x = F(Of IEnumerable(Of Object))...<x> x = F(Of IEnumerable(Of XObject))...<x> x = F(Of IEnumerable(Of XContainer))...<x> x = F(Of IEnumerable(Of XElement))...<x> x = F(Of IEnumerable(Of XDocument))...<x> x = F(Of IEnumerable(Of XAttribute))...<x> x = F(Of IEnumerable(Of MyElement))...<x> End Sub End Module ]]></file> </compilation>, references:=XmlReferences) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC31168: XML axis properties do not support late binding. x = F(Of Object)...<x> ~~~~~~~~~~~~~~~~~~ BC36809: XML descendant elements cannot be selected from type 'XObject'. x = F(Of XObject)...<x> ~~~~~~~~~~~~~~~~~~~ BC36809: XML descendant elements cannot be selected from type 'XAttribute'. x = F(Of XAttribute)...<x> ~~~~~~~~~~~~~~~~~~~~~~ BC36809: XML descendant elements cannot be selected from type 'Object()'. x = F(Of Object())...<x> ~~~~~~~~~~~~~~~~~~~~ BC36809: XML descendant elements cannot be selected from type 'XObject()'. x = F(Of XObject())...<x> ~~~~~~~~~~~~~~~~~~~~~ BC36809: XML descendant elements cannot be selected from type 'XAttribute()'. x = F(Of XAttribute())...<x> ~~~~~~~~~~~~~~~~~~~~~~~~ BC36809: XML descendant elements cannot be selected from type 'IEnumerable(Of Object)'. x = F(Of IEnumerable(Of Object))...<x> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36809: XML descendant elements cannot be selected from type 'IEnumerable(Of XObject)'. x = F(Of IEnumerable(Of XObject))...<x> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36809: XML descendant elements cannot be selected from type 'IEnumerable(Of XAttribute)'. x = F(Of IEnumerable(Of XAttribute))...<x> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></errors>) End Sub <Fact()> Public Sub BC36907ERR_TypeOrMemberNotGeneric2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="TypeOrMemberNotGeneric2"> <file name="a.vb"> Option Strict On Imports System Module M1 Sub FOO() Dim x1 As Integer x1.FooGeneric01(Of Integer)() End Sub End Module Module Extension01 &lt;System.Runtime.CompilerServices.Extension()&gt; Sub FooGeneric01(Of T1)(ByVal o As T1) End Sub End Module </file> </compilation>, {Net40.SystemCore}) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36907: Extension method 'Public Sub FooGeneric01()' defined in 'Extension01' is not generic (or has no free type parameters) and so cannot have type arguments. x1.FooGeneric01(Of Integer)() ~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC36913ERR_IfTooManyTypesObjectDisallowed() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict On Public Module X Sub Foo(ByVal x As Boolean) Dim f = If(x, Function() 1, Function() "") End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36913: Cannot infer a common type because more than one type is possible. Dim f = If(x, Function() 1, Function() "") ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC36916ERR_LambdaNoTypeObjectDisallowed() CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="LambdaNoTypeObjectDisallowed"> <file name="a.vb"> Option Strict On Imports System Module M1 Dim x As Action = Function() Dim a = 2 End Function End Module </file> </compilation>).VerifyDiagnostics( Diagnostic(ERRID.ERR_LambdaNoTypeObjectDisallowed, "Function()"), Diagnostic(ERRID.WRN_DefAsgNoRetValFuncRef1, "End Function").WithArguments("<anonymous method>") ) End Sub #End Region #Region "Targeted Warning Tests" <Fact()> Public Sub BC40052WRN_SelectCaseInvalidRange() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="SelectCaseInvalidRange"> <file name="a.vb"> Module M1 Sub foo() Select Case #1/2/0003# Case Date.MaxValue To Date.MinValue End Select Select Case 1 Case 1 To 0 End Select End Sub End Module </file> </compilation>, TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.Custom)) Dim expectedErrors1 = <errors> BC40052: Range specified for 'Case' statement is not valid. Make sure that the lower bound is less than or equal to the upper bound. Case 1 To 0 ~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC40052WRN_SelectCaseInvalidRange_02() ' Dev10 doesn't report WRN_SelectCaseInvalidRange for each invalid case range. ' It is performed only if bounds for all clauses in the Select are integer constants and ' all clauses are either range clauses or equality clause. ' Doing this differently will produce warnings in more scenarios - breaking change, ' hence we maintain compatibility with Dev10. Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="SelectCaseInvalidRange"> <file name="a.vb"> Module M1 Sub foo() ' NO WARNING CASES ' with relational clause Select Case 1 Case 1 To 0 Case Is > 10 End Select ' with relational clause in different order Select Case 1 Case Is > 10 Case 1 To 0 End Select ' with non constant integer clause Dim number As Integer = 10 Select Case 1 Case 1 To 0 Case number End Select ' with non integer clause Dim obj As Object = 10 Select Case 1 Case 1 To 0 Case obj End Select ' WARNING CASES ' with all integer constant equality clauses Select Case 1 Case 1 To 0 Case Is = 2 Case 1, 2, 3 End Select ' with all integer constant equality clauses in different order Select Case 1 Case Is = 2 Case 1, 2, 3 Case 1 To 0 End Select End Sub End Module </file> </compilation>) Dim expectedErrors1 = <errors> BC40052: Range specified for 'Case' statement is not valid. Make sure that the lower bound is less than or equal to the upper bound. Case 1 To 0 ~~~~~~ BC40052: Range specified for 'Case' statement is not valid. Make sure that the lower bound is less than or equal to the upper bound. Case 1 To 0 ~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact> <WorkItem(759127, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/759127")> Public Sub BC41000WRN_AttributeSpecifiedMultipleTimes() ' No warnings Expected - Previously would generate a BC41000. The signature of Attribute ' determined From attribute used in original bug. ' We want to verify that the diagnostics do not appear and that the attributes are both added. ' No values provided for attribute Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="Class1"> <file name="a.vb"> Imports System &lt;System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1019:DefineAccessorsForAttributeArguments")&gt; &lt;AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class, AllowMultiple:=True)&gt; Public Class ESAttribute Inherits System.Attribute Public Sub New(assemblyGUID As String) If (assemblyGUID Is Nothing) Then Throw New System.ArgumentNullException("assemblyGuid") End If End Sub Public Sub New() End Sub End Class </file> <file name="b.vb"> &lt;Assembly:ESAttribute()&gt; Class Class1 Sub Blah() End Sub End Class </file> <file name="c.vb"> &lt;Assembly:ESAttribute()&gt; Module Module1 Sub Main() End Sub End Module </file> </compilation>) Dim expectedErrors1 = <errors> </errors> CompilationUtils.AssertTheseDiagnostics(compilation, expectedErrors1) ' One value provided for attribute, the other does not have argument compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="Class1"> <file name="a.vb"> Imports System &lt;System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1019:DefineAccessorsForAttributeArguments")&gt; &lt;AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class, AllowMultiple:=True)&gt; Public Class ESAttribute Inherits System.Attribute Public Sub New(assemblyGUID As String) If (assemblyGUID Is Nothing) Then Throw New System.ArgumentNullException("assemblyGuid") End If End Sub Public Sub New() End Sub End Class </file> <file name="b.vb"> &lt;Assembly:ESAttribute()&gt; Class Class1 Sub Blah() End Sub End Class </file> <file name="c.vb"> &lt;Assembly:ESAttribute("Test")&gt; Module Module1 Sub Main() End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, expectedErrors1) ' Different values for argument provided for attribute usage compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="Class1"> <file name="a.vb"> Imports System &lt;System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1019:DefineAccessorsForAttributeArguments")&gt; &lt;AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class, AllowMultiple:=True)&gt; Public Class ESAttribute Inherits System.Attribute Public Sub New(assemblyGUID As String) If (assemblyGUID Is Nothing) Then Throw New System.ArgumentNullException("assemblyGuid") End If End Sub Public Sub New() End Sub End Class </file> <file name="b.vb"> &lt;Assembly:ESAttribute("test2")&gt; Class Class1 Sub Blah() End Sub End Class </file> <file name="c.vb"> &lt;Assembly:ESAttribute("Test")&gt; Module Module1 Sub Main() End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, expectedErrors1) Assert.Equal(2, compilation.Assembly.GetAttributes.Count) Assert.Equal("ESAttribute(""test2"")", compilation.Assembly.GetAttributes.Item(0).ToString) Assert.Equal("ESAttribute(""Test"")", compilation.Assembly.GetAttributes.Item(1).ToString) ' Different values for argument provided for attribute usage - Different Order To check the order is ' not sorted but merely the order it was located in compilation compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="Class1"> <file name="a.vb"> Imports System &lt;System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1019:DefineAccessorsForAttributeArguments")&gt; &lt;AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class, AllowMultiple:=True)&gt; Public Class ESAttribute Inherits System.Attribute Public Sub New(assemblyGUID As String) If (assemblyGUID Is Nothing) Then Throw New System.ArgumentNullException("assemblyGuid") End If End Sub Public Sub New() End Sub End Class </file> <file name="b.vb"> &lt;Assembly:ESAttribute("Test")&gt; Class Class1 Sub Blah() End Sub End Class </file> <file name="c.vb"> &lt;Assembly:ESAttribute("Test2")&gt; Module Module1 Sub Main() End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, expectedErrors1) Assert.Equal(2, compilation.Assembly.GetAttributes.Count) Assert.Equal("ESAttribute(""Test"")", compilation.Assembly.GetAttributes.Item(0).ToString) Assert.Equal("ESAttribute(""Test2"")", compilation.Assembly.GetAttributes.Item(1).ToString) End Sub <Fact> Public Sub BC41001WRN_NoNonObsoleteConstructorOnBase3() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="NoNonObsoleteConstructorOnBase4"> <file name="a.vb"> Imports System Class C1 &lt;Obsolete&gt; Sub New() End Sub End Class Class C2 Inherits C1 End Class </file> </compilation>, TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.Custom)) Dim expectedErrors1 = <errors> BC41001: Class 'C2' should declare a 'Sub New' because the 'Public Sub New()' in its base class 'C1' is marked obsolete. Class C2 ~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact> Public Sub BC41002WRN_NoNonObsoleteConstructorOnBase4() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="NoNonObsoleteConstructorOnBase4"> <file name="a.vb"> Imports System Class C1 &lt;Obsolete("hello", False)&gt; Sub New() End Sub End Class Class C2 Inherits C1 End Class </file> </compilation>, TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.Custom)) Dim expectedErrors1 = <errors> BC41002: Class 'C2' should declare a 'Sub New' because the 'Public Sub New()' in its base class 'C1' is marked obsolete: 'hello'. Class C2 ~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact> Public Sub BC41003WRN_RequiredNonObsoleteNewCall3() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="RequiredNonObsoleteNewCall4"> <file name="a.vb"> Imports System Class C1 &lt;Obsolete&gt; Sub New() End Sub End Class Class C2 Inherits C1 Sub New() End Sub End Class </file> </compilation>, TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.Custom)) Dim expectedErrors1 = <errors> BC41003: First statement of this 'Sub New' should be an explicit call to 'MyBase.New' or 'MyClass.New' because the 'Public Sub New()' in the base class 'C1' of 'C2' is marked obsolete. Sub New() ~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact> Public Sub BC41004WRN_RequiredNonObsoleteNewCall4() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="RequiredNonObsoleteNewCall4"> <file name="a.vb"> Imports System Class C1 &lt;Obsolete("hello", False)&gt; Sub New() End Sub End Class Class C2 Inherits C1 Sub New() End Sub End Class </file> </compilation>, TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.Custom)) Dim expectedErrors1 = <errors> BC41004: First statement of this 'Sub New' should be an explicit call to 'MyBase.New' or 'MyClass.New' because the 'Public Sub New()' in the base class 'C1' of 'C2' is marked obsolete: 'hello' Sub New() ~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact> Public Sub BC41007WRN_ConditionalNotValidOnFunction() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ConditionalNotValidOnFunction"> <file name="a.vb"> Imports System.Diagnostics Public Structure S1 &lt;Conditional("hello")&gt; Public Shared Operator +(ByVal v As S1, ByVal w As S1) As Object Return Nothing End Operator End Structure </file> </compilation>, TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.Custom)) Dim expectedErrors1 = <errors> BC41007: Attribute 'Conditional' is only valid on 'Sub' declarations. Public Shared Operator +(ByVal v As S1, ByVal w As S1) As Object ~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> <CompilerTrait(CompilerFeature.IOperation)> <WorkItem(23282, "https://github.com/dotnet/roslyn/issues/23282")> Public Sub BC41998WRN_RecursiveAddHandlerCall() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="RecursiveAddHandlerCall"> <file name="a.vb"> Module M1 Public Delegate Sub test_x() Sub test_d1() End Sub Public Custom Event t As test_x AddHandler(ByVal value As test_x) AddHandler t, AddressOf test_d1 End AddHandler RemoveHandler(ByVal value As test_x) RemoveHandler t, AddressOf test_d1 End RemoveHandler RaiseEvent() RaiseEvent t() End RaiseEvent End Event End Module </file> </compilation>, TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.Custom)) Dim expectedErrors1 = <errors> BC41998: Statement recursively calls the containing 'AddHandler' for event 't'. AddHandler t, AddressOf test_d1 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC41998: Statement recursively calls the containing 'RemoveHandler' for event 't'. RemoveHandler t, AddressOf test_d1 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC41998: Statement recursively calls the containing 'RaiseEvent' for event 't'. RaiseEvent t() ~~~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation, expectedErrors1) Dim tree = compilation.SyntaxTrees.Single() Dim model = compilation.GetSemanticModel(tree) Dim add = tree.GetRoot().DescendantNodes().OfType(Of AddRemoveHandlerStatementSyntax)().First() Assert.Equal("AddHandler t, AddressOf test_d1", add.ToString()) compilation.VerifyOperationTree(add, expectedOperationTree:= <![CDATA[ IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'AddHandler ... sOf test_d1') Expression: IEventAssignmentOperation (EventAdd) (OperationKind.EventAssignment, Type: null, IsImplicit) (Syntax: 'AddHandler ... sOf test_d1') Event Reference: IEventReferenceOperation: Event M1.t As M1.test_x (Static) (OperationKind.EventReference, Type: M1.test_x) (Syntax: 't') Instance Receiver: null Handler: IDelegateCreationOperation (OperationKind.DelegateCreation, Type: M1.test_x, IsImplicit) (Syntax: 'AddressOf test_d1') Target: IMethodReferenceOperation: Sub M1.test_d1() (Static) (OperationKind.MethodReference, Type: null) (Syntax: 'AddressOf test_d1') Instance Receiver: null ]]>.Value) Assert.Equal("Event M1.t As M1.test_x", model.GetSymbolInfo(add.EventExpression).Symbol.ToTestDisplayString()) Dim remove = tree.GetRoot().DescendantNodes().OfType(Of AddRemoveHandlerStatementSyntax)().Last() Assert.Equal("RemoveHandler t, AddressOf test_d1", remove.ToString()) compilation.VerifyOperationTree(remove, expectedOperationTree:= <![CDATA[ IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'RemoveHandl ... sOf test_d1') Expression: IEventAssignmentOperation (EventRemove) (OperationKind.EventAssignment, Type: null, IsImplicit) (Syntax: 'RemoveHandl ... sOf test_d1') Event Reference: IEventReferenceOperation: Event M1.t As M1.test_x (Static) (OperationKind.EventReference, Type: M1.test_x) (Syntax: 't') Instance Receiver: null Handler: IDelegateCreationOperation (OperationKind.DelegateCreation, Type: M1.test_x, IsImplicit) (Syntax: 'AddressOf test_d1') Target: IMethodReferenceOperation: Sub M1.test_d1() (Static) (OperationKind.MethodReference, Type: null) (Syntax: 'AddressOf test_d1') Instance Receiver: null ]]>.Value) Assert.Equal("Event M1.t As M1.test_x", model.GetSymbolInfo(remove.EventExpression).Symbol.ToTestDisplayString()) Dim raise = tree.GetRoot().DescendantNodes().OfType(Of RaiseEventStatementSyntax)().Single() Assert.Equal("RaiseEvent t()", raise.ToString()) compilation.VerifyOperationTree(raise, expectedOperationTree:= <![CDATA[ IRaiseEventOperation (OperationKind.RaiseEvent, Type: null) (Syntax: 'RaiseEvent t()') Event Reference: IEventReferenceOperation: Event M1.t As M1.test_x (Static) (OperationKind.EventReference, Type: M1.test_x) (Syntax: 't') Instance Receiver: null Arguments(0) ]]>.Value) Assert.Equal("Event M1.t As M1.test_x", model.GetSymbolInfo(raise.Name).Symbol.ToTestDisplayString()) End Sub <Fact()> Public Sub BC41999WRN_ImplicitConversionCopyBack() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ImplicitConversionCopyBack"> <file name="a.vb"> Namespace ns1 Module M1 Sub foo(ByRef x As Object) End Sub Sub FOO1() Dim o As New System.Exception foo(o) End Sub End Module End Namespace </file> </compilation>, TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.Custom)) Dim expectedErrors1 = <errors> BC41999: Implicit conversion from 'Object' to 'Exception' in copying the value of 'ByRef' parameter 'x' back to the matching argument. foo(o) ~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC42016WRN_ImplicitConversionSubst1() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ImplicitConversionSubst1"> <file name="a.vb"> Module Module1 Sub Main() Dim a As Integer = 2 Dim b As Integer = 2 Dim c As Integer = a / b a = c End Sub End Module </file> </compilation>, TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.Custom)) Dim expectedErrors1 = <errors> BC42016: Implicit conversion from 'Double' to 'Integer'. Dim c As Integer = a / b ~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC42018WRN_ObjectMath1() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ObjectMath1"> <file name="a.vb"> Module Module1 Sub Main() Dim o As New Object o = o = 1 End Sub End Module </file> </compilation>, TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.Custom)) Dim expectedErrors1 = <errors> BC42018: Operands of type Object used for operator '='; use the 'Is' operator to test object identity. o = o = 1 ~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC42019WRN_ObjectMath2_1() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ObjectMath2"> <file name="a.vb"> Module Module1 Sub Main() Dim o As New Object o = o + 1 End Sub End Module </file> </compilation>, TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.Custom)) Dim expectedErrors1 = <errors> BC42019: Operands of type Object used for operator '+'; runtime errors could occur. o = o + 1 ~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC42019WRN_ObjectMath2_2() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ObjectMath2"> <file name="a.vb"> Module Module1 function Main() Dim o As New Object return o * o End function End Module </file> </compilation>, TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.Custom)) Dim expectedErrors1 = <errors> BC42021: Function without an 'As' clause; return type of Object assumed. function Main() ~~~~ BC42019: Operands of type Object used for operator '*'; runtime errors could occur. return o * o ~ BC42019: Operands of type Object used for operator '*'; runtime errors could occur. return o * o ~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC42024WRN_UnusedLocal() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="UnusedLocal"> <file name="a.vb"> Public Module Module1 Public Sub Main() Dim c1 As Class1 End Sub Class Class1 End Class End Module </file> </compilation>) Dim expectedErrors1 = <errors> BC42024: Unused local variable: 'c1'. Dim c1 As Class1 ~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC42025WRN_SharedMemberThroughInstance_1() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module Module1 Structure S1 Structure S1 Public Shared strTemp As String End Structure End Structure Sub Main() Dim obj As New S1.S1 obj.strTemp = "S" End Sub End Module </file> </compilation>) Dim expectedErrors1 = <errors> BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. obj.strTemp = "S" ~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC42025WRN_SharedMemberThroughInstance_2() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C Shared Property P Get Return Nothing End Get Set(ByVal value) End Set End Property Sub M() Dim o = Me.P Me.P = o End Sub End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. Dim o = Me.P ~~~~ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. Me.P = o ~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <WorkItem(528718, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528718")> <Fact()> Public Sub BC42025WRN_SharedMemberThroughInstance_3() CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="a.vb"> Option Infer On Imports System.Runtime.CompilerServices Module M Sub Main() For Each y In 1 Next End Sub &lt;Extension()&gt; Function GetEnumerator(x As Integer) As E Return New E End Function End Module Class E Function MoveNext() As Boolean Return True End Function Shared Property Current As Boolean Get Return True End Get Set(ByVal value As Boolean) End Set End Property End Class </file> </compilation>, {Net40.SystemCore}).VerifyDiagnostics( Diagnostic(ERRID.WRN_SharedMemberThroughInstance, "1")) End Sub <Fact()> Public Sub BC42025WRN_SharedMemberThroughInstance_4() Dim comp = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Enum E A B = B.A + 1 End Enum </file> </compilation>) comp.AssertTheseDiagnostics(<errors> BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. B = B.A + 1 ~~~ </errors>) End Sub <Fact(), WorkItem(528734, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528734")> Public Sub BC42026WRN_RecursivePropertyCall() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="RecursivePropertyCall"> <file name="a.vb"> Module Module1 Class c1 ReadOnly Property Name() As String Get Return Me.Name End Get End Property End Class End Module Module Program Sub PassByRef(ByRef x As Integer) End Sub Sub PassByVal(x As Integer) End Sub Property P1 As Integer Get If Date.Now.Day = 2 Then Return P1() + 1 ' 1 ElseIf Date.Now.Day = 3 Then P1() += 1 ' 2 Mid(P1(), 1) = 2 ' 3 PassByRef(P1()) '4 PassByVal(P1()) '5 Else P1() = 2 End If Return 0 End Get Set(value As Integer) If Date.Now.Day = 2 Then P1() = value '6 ElseIf Date.Now.Day = 3 Then P1() += 1 '7 Mid(P1(), 1) = 2 '8 PassByRef(P1()) '9 PassByVal(P1()) Else Dim x = P1() End If End Set End Property Property P2(a As Integer) As Integer Get If Date.Now.Day = 2 Then Return P2(a) + 1 ElseIf Date.Now.Day = 3 Then P2(a) += 2 Mid(P2(a), 1) = 2 PassByRef(P2(a)) PassByVal(P2(a)) Else P2(a) = 2 End If Return 0 End Get Set(value As Integer) If Date.Now.Day = 2 Then P2(a) = value ElseIf Date.Now.Day = 3 Then P2(a) += 2 Mid(P2(a), 1) = 2 PassByRef(P2(a)) PassByVal(P2(a)) Else Dim x = P2(a) End If End Set End Property End Module Class Class1 Property P3 As Integer Get If Date.Now.Day = 2 Then Return P3() + 1 '10 ElseIf Date.Now.Day = 3 Then P3() += 2 ' 11 Mid(P3(), 1) = 2 ' 12 PassByRef(P3()) ' 13 PassByVal(P3()) ' 14 Else P3() = 2 End If Return 0 End Get Set(value As Integer) If Date.Now.Day = 2 Then P3() = value ' 15 ElseIf Date.Now.Day = 3 Then P3() += 2 ' 16 Mid(P3(), 1) = 2 ' 17 PassByRef(P3()) ' 18 PassByVal(P3()) Else Dim x = P3() End If End Set End Property Property P4 As Integer Get If Date.Now.Day = 2 Then Return P4 + 1 ElseIf Date.Now.Day = 3 Then P4 += 2 Mid(P4, 1) = 2 PassByRef(P4) PassByVal(P4) Else P4 = 2 End If Return 0 End Get Set(value As Integer) If Date.Now.Day = 2 Then P4 = value ' 19 ElseIf Date.Now.Day = 3 Then P4 += 2 ' 20 Mid(P4, 1) = 2 ' 21 PassByRef(P4) ' 22 PassByVal(P4) Else Dim x = P4 End If End Set End Property Property P5 As Integer Get If Date.Now.Day = 2 Then Return Me.P5 + 1 ' 23 ElseIf Date.Now.Day = 3 Then Me.P5 += 2 ' 24 Mid(Me.P5, 1) = 2 ' 25 PassByRef(Me.P5) ' 26 PassByVal(Me.P5) ' 27 Else Me.P5 = 2 End If Return 0 End Get Set(value As Integer) If Date.Now.Day = 2 Then Me.P5 = value ' 28 ElseIf Date.Now.Day = 3 Then Me.P5 += 2 ' 29 Mid(Me.P5, 1) = 2 ' 30 PassByRef(Me.P5) ' 31 PassByVal(Me.P5) Else Dim x = Me.P5 End If End Set End Property Property P6(a As Integer) As Integer Get If Date.Now.Day = 2 Then Return P6(a) + 1 ElseIf Date.Now.Day = 3 Then P6(a) += 2 Mid(P6(a), 1) = 2 PassByRef(P6(a)) PassByVal(P6(a)) Else P6(a) = 2 End If Return 0 End Get Set(value As Integer) If Date.Now.Day = 2 Then P6(a) = value ElseIf Date.Now.Day = 3 Then P6(a) += 2 Mid(P6(a), 1) = 2 PassByRef(P6(a)) PassByVal(P6(a)) Else Dim x = P6(a) End If End Set End Property Property P7 As Integer Get Dim x = Me If Date.Now.Day = 2 Then Return x.P7() + 1 ElseIf Date.Now.Day = 3 Then x.P7() += 2 Mid(x.P7(), 1) = 2 PassByRef(x.P7()) PassByVal(x.P7()) Else x.P7() = 2 End If Return 0 End Get Set(value As Integer) Dim x = Me If Date.Now.Day = 2 Then x.P7() = value ElseIf Date.Now.Day = 3 Then x.P7() += 2 Mid(x.P7(), 1) = 2 PassByRef(x.P7()) PassByVal(x.P7()) Else Dim y = x.P7() End If End Set End Property End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC42026: Expression recursively calls the containing property 'Public ReadOnly Property Name As String'. Return Me.Name ~~~~~~~ BC42026: Expression recursively calls the containing property 'Public Property P1 As Integer'. Return P1() + 1 ' 1 ~~~~ BC42026: Expression recursively calls the containing property 'Public Property P1 As Integer'. P1() += 1 ' 2 ~~~~ BC42026: Expression recursively calls the containing property 'Public Property P1 As Integer'. Mid(P1(), 1) = 2 ' 3 ~~~~ BC42026: Expression recursively calls the containing property 'Public Property P1 As Integer'. PassByRef(P1()) '4 ~~~~ BC42026: Expression recursively calls the containing property 'Public Property P1 As Integer'. PassByVal(P1()) '5 ~~~~ BC42026: Expression recursively calls the containing property 'Public Property P1 As Integer'. P1() = value '6 ~~~~ BC42026: Expression recursively calls the containing property 'Public Property P1 As Integer'. P1() += 1 '7 ~~~~ BC42026: Expression recursively calls the containing property 'Public Property P1 As Integer'. Mid(P1(), 1) = 2 '8 ~~~~ BC42026: Expression recursively calls the containing property 'Public Property P1 As Integer'. PassByRef(P1()) '9 ~~~~ BC42026: Expression recursively calls the containing property 'Public Property P3 As Integer'. Return P3() + 1 '10 ~~~~ BC42026: Expression recursively calls the containing property 'Public Property P3 As Integer'. P3() += 2 ' 11 ~~~~ BC42026: Expression recursively calls the containing property 'Public Property P3 As Integer'. Mid(P3(), 1) = 2 ' 12 ~~~~ BC42026: Expression recursively calls the containing property 'Public Property P3 As Integer'. PassByRef(P3()) ' 13 ~~~~ BC42026: Expression recursively calls the containing property 'Public Property P3 As Integer'. PassByVal(P3()) ' 14 ~~~~ BC42026: Expression recursively calls the containing property 'Public Property P3 As Integer'. P3() = value ' 15 ~~~~ BC42026: Expression recursively calls the containing property 'Public Property P3 As Integer'. P3() += 2 ' 16 ~~~~ BC42026: Expression recursively calls the containing property 'Public Property P3 As Integer'. Mid(P3(), 1) = 2 ' 17 ~~~~ BC42026: Expression recursively calls the containing property 'Public Property P3 As Integer'. PassByRef(P3()) ' 18 ~~~~ BC42026: Expression recursively calls the containing property 'Public Property P4 As Integer'. P4 = value ' 19 ~~ BC42026: Expression recursively calls the containing property 'Public Property P4 As Integer'. P4 += 2 ' 20 ~~ BC42026: Expression recursively calls the containing property 'Public Property P4 As Integer'. Mid(P4, 1) = 2 ' 21 ~~ BC42026: Expression recursively calls the containing property 'Public Property P4 As Integer'. PassByRef(P4) ' 22 ~~ BC42026: Expression recursively calls the containing property 'Public Property P5 As Integer'. Return Me.P5 + 1 ' 23 ~~~~~ BC42026: Expression recursively calls the containing property 'Public Property P5 As Integer'. Me.P5 += 2 ' 24 ~~~~~ BC42026: Expression recursively calls the containing property 'Public Property P5 As Integer'. Mid(Me.P5, 1) = 2 ' 25 ~~~~~ BC42026: Expression recursively calls the containing property 'Public Property P5 As Integer'. PassByRef(Me.P5) ' 26 ~~~~~ BC42026: Expression recursively calls the containing property 'Public Property P5 As Integer'. PassByVal(Me.P5) ' 27 ~~~~~ BC42026: Expression recursively calls the containing property 'Public Property P5 As Integer'. Me.P5 = value ' 28 ~~~~~ BC42026: Expression recursively calls the containing property 'Public Property P5 As Integer'. Me.P5 += 2 ' 29 ~~~~~ BC42026: Expression recursively calls the containing property 'Public Property P5 As Integer'. Mid(Me.P5, 1) = 2 ' 30 ~~~~~ BC42026: Expression recursively calls the containing property 'Public Property P5 As Integer'. PassByRef(Me.P5) ' 31 ~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC42029WRN_OverlappingCatch() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Module Module1 Sub foo1() Try Catch ex As Exception Catch ex As SystemException Console.WriteLine(ex) End Try End Sub End Module </file> </compilation>) Dim expectedErrors1 = <errors> BC42029: 'Catch' block never reached, because 'SystemException' inherits from 'Exception'. Catch ex As SystemException ~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC42030WRN_DefAsgUseNullRefByRef1() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C Shared Sub M() Dim o As Object M(o) End Sub Shared Sub M(ByRef o As Object) End Sub End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC42030: Variable 'o' is passed by reference before it has been assigned a value. A null reference exception could result at runtime. M(o) ~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC42030WRN_DefAsgUseNullRefByRef2() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="DefAsgUseNullRefByRef"> <file name="a.vb"> Module M1 Sub foo(ByRef x As Object) End Sub Structure S1 Dim o As Object Dim e As Object End Structure Sub Main() Dim x1 As S1 x1.o = Nothing foo(x1.e) End Sub End Module </file> </compilation>) Dim expectedErrors1 = <errors> BC42030: Variable 'e' is passed by reference before it has been assigned a value. A null reference exception could result at runtime. foo(x1.e) ~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC42031WRN_DuplicateCatch() CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="DuplicateCatch"> <file name="a.vb"> Imports System Module Module1 Sub foo() Try Catch ex As Exception Catch ex As Exception End Try End Sub End Module </file> </compilation>).VerifyDiagnostics( Diagnostic(ERRID.WRN_DuplicateCatch, "Catch ex As Exception").WithArguments("System.Exception")) End Sub <Fact()> Public Sub BC42032WRN_ObjectMath1Not() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ObjectMath1Not"> <file name="a.vb"> Module Module1 Sub Main() Dim Result Dim X If Result &lt;&gt; 13 Or X &lt;&gt; Nothing Then End If End Sub End Module </file> </compilation>, TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.Custom)) Dim expectedErrors1 = <errors> BC42020: Variable declaration without an 'As' clause; type of Object assumed. Dim Result ~~~~~~ BC42020: Variable declaration without an 'As' clause; type of Object assumed. Dim X ~ BC42032: Operands of type Object used for operator '&lt;&gt;'; use the 'IsNot' operator to test object identity. If Result &lt;&gt; 13 Or X &lt;&gt; Nothing Then ~~~~~~ BC42104: Variable 'Result' is used before it has been assigned a value. A null reference exception could result at runtime. If Result &lt;&gt; 13 Or X &lt;&gt; Nothing Then ~~~~~~ BC42019: Operands of type Object used for operator 'Or'; runtime errors could occur. If Result &lt;&gt; 13 Or X &lt;&gt; Nothing Then ~~~~~~~~~~~~ BC42016: Implicit conversion from 'Object' to 'Boolean'. If Result &lt;&gt; 13 Or X &lt;&gt; Nothing Then ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42032: Operands of type Object used for operator '&lt;&gt;'; use the 'IsNot' operator to test object identity. If Result &lt;&gt; 13 Or X &lt;&gt; Nothing Then ~ BC42104: Variable 'X' is used before it has been assigned a value. A null reference exception could result at runtime. If Result &lt;&gt; 13 Or X &lt;&gt; Nothing Then ~ BC42019: Operands of type Object used for operator 'Or'; runtime errors could occur. If Result &lt;&gt; 13 Or X &lt;&gt; Nothing Then ~~~~~~~~~~~~ BC42032: Operands of type Object used for operator '&lt;&gt;'; use the 'IsNot' operator to test object identity. If Result &lt;&gt; 13 Or X &lt;&gt; Nothing Then ~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub 'vbc module1.vb /target:library /noconfig /optionstrict:custom <Fact()> Public Sub BC42036WRN_ObjectMathSelectCase() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ObjectMathSelectCase"> <file name="a.vb"> Module M1 Sub Main() Dim o As Object = 1 Select Case o Case 1 End Select End Sub End Module </file> </compilation>, New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptionStrict(OptionStrict.Custom)) Dim expectedErrors1 = <errors> BC42036: Operands of type Object used in expressions for 'Select', 'Case' statements; runtime errors could occur. Select Case o ~ BC42016: Implicit conversion from 'Object' to 'Boolean'. Case 1 ~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC42036WRN_ObjectMathSelectCase_02() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ObjectMathSelectCase"> <file name="a.vb"> Module M1 Sub Main() Dim o As Object = 1 Select Case 1 Case 2, o End Select End Sub End Module </file> </compilation>, New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptionStrict(OptionStrict.Custom)) Dim expectedErrors1 = <errors> BC42016: Implicit conversion from 'Object' to 'Boolean'. Case 2, o ~~~~~~~~~ BC42036: Operands of type Object used in expressions for 'Select', 'Case' statements; runtime errors could occur. Case 2, o ~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC42037WRN_EqualToLiteralNothing() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="EqualToLiteralNothing"> <file name="a.vb"> Module M Sub F(o As Integer?) Dim b As Boolean b = (o = Nothing) b = (Nothing = o) End Sub End Module </file> </compilation>) Dim expectedErrors1 = <errors> BC42037: This expression will always evaluate to Nothing (due to null propagation from the equals operator). To check if the value is null consider using 'Is Nothing'. b = (o = Nothing) ~~~~~~~~~~~ BC42037: This expression will always evaluate to Nothing (due to null propagation from the equals operator). To check if the value is null consider using 'Is Nothing'. b = (Nothing = o) ~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC42038WRN_NotEqualToLiteralNothing() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> <![CDATA[ Module M Sub F(o As Integer?) Dim b As Boolean b = (o <> Nothing) b = (Nothing <> o) End Sub End Module ]]> </file> </compilation>) Dim expectedErrors1 = <errors> <![CDATA[ BC42038: This expression will always evaluate to Nothing (due to null propagation from the equals operator). To check if the value is not null consider using 'IsNot Nothing'. b = (o <> Nothing) ~~~~~~~~~~~~ BC42038: This expression will always evaluate to Nothing (due to null propagation from the equals operator). To check if the value is not null consider using 'IsNot Nothing'. b = (Nothing <> o) ~~~~~~~~~~~~ ]]> </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC42104WRN_DefAsgUseNullRef() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C Shared Function F() Dim v As String Return v End Function End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC42104: Variable 'v' is used before it has been assigned a value. A null reference exception could result at runtime. Return v ~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <WorkItem(546820, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546820")> <Fact()> Public Sub BC42104WRN_DefAsgUseNullRef_StaticLocal() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Module Program Sub Main() Static TypeCharacterTable As System.Collections.Generic.Dictionary(Of String, String) If TypeCharacterTable Is Nothing Then TypeCharacterTable = New System.Collections.Generic.Dictionary(Of String, String) End If End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors></errors>) End Sub <WorkItem(542080, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542080")> <Fact()> Public Sub BC42104WRN_DefAsgUseNullRef_1() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System Class C Public Shared Sub Main() Dim x As Action For Each x In New Action() {} x.Invoke() Next x.Invoke() End Sub End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC42104: Variable 'x' is used before it has been assigned a value. A null reference exception could result at runtime. x.Invoke() ~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC42104WRN_DefAsgUseNullRef_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C Public Shared Sub Main() Dim S As String For Each x As String In "abc" For Each S In "abc" If S = "B"c Then Continue For End If Next S Next x System.Console.WriteLine(S) End Sub End Class </file> </compilation>) AssertTheseEmitDiagnostics(compilation, <errors> BC35000: Requested operation is not available because the runtime library function 'Microsoft.VisualBasic.CompilerServices.Conversions.ToString' is not defined. For Each x As String In "abc" ~~~~~ BC35000: Requested operation is not available because the runtime library function 'Microsoft.VisualBasic.CompilerServices.Conversions.ToString' is not defined. For Each S In "abc" ~~~~~ BC35000: Requested operation is not available because the runtime library function 'Microsoft.VisualBasic.CompilerServices.Operators.CompareString' is not defined. If S = "B"c Then ~~~~~~~~ BC42104: Variable 'S' is used before it has been assigned a value. A null reference exception could result at runtime. System.Console.WriteLine(S) ~ </errors>) End Sub <WorkItem(542080, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542080")> <Fact()> Public Sub BC42104WRN_DefAsgUseNullRef_3() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Class C Public Shared Sub Main() For Each x As String In "abc" Dim S As String For Each S In "abc" If S = "B"c Then Continue For End If Next S System.Console.WriteLine(S) Next x End Sub End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC42104: Variable 'S' is used before it has been assigned a value. A null reference exception could result at runtime. System.Console.WriteLine(S) ~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <WorkItem(542080, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542080")> <Fact()> Public Sub BC42104WRN_DefAsgUseNullRef_4() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Structure S Public X As Integer Public Y As String End Structure Public Module Program2 Public Sub Main(args() As String) Dim a, b As New S() With {.Y = b.Y} Dim c, d As New S() With {.Y = c.Y} Dim e, f As New S() With {.Y = .Y} End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC42104: Variable 'Y' is used before it has been assigned a value. A null reference exception could result at runtime. Dim a, b As New S() With {.Y = b.Y} ~~~ </errors>) End Sub <WorkItem(542080, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542080")> <Fact()> Public Sub BC42104WRN_DefAsgUseNullRef_5() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Structure S Public X As String Public Y As Object End Structure Public Module Program2 Public Sub Main(args() As String) Dim a, b, c As New S() With {.Y = b.X, .X = c.Y} End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC42104: Variable 'X' is used before it has been assigned a value. A null reference exception could result at runtime. Dim a, b, c As New S() With {.Y = b.X, .X = c.Y} ~~~ BC42104: Variable 'Y' is used before it has been assigned a value. A null reference exception could result at runtime. Dim a, b, c As New S() With {.Y = b.X, .X = c.Y} ~~~ </errors>) End Sub ''' <summary> ''' No warning reported for expression that will not be evaluated. ''' </summary> <Fact()> Public Sub BC42104WRN_DefAsgUseNullRef_ConstantUnevaluatedReceiver() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class A Const F As Object = Nothing Shared Function M() As Object Dim o As A Return (o).F End Function End Class </file> </compilation>) compilation.AssertTheseDiagnostics(<errors> BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. Return (o).F ~~~~~ </errors>) End Sub ''' <summary> ''' No warning reported for expression that will not be evaluated. ''' </summary> <Fact()> Public Sub BC42104WRN_DefAsgUseNullRef_CallUnevaluatedReceiver() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class A Shared Function F() As Object Return Nothing End Function Shared Function M() As Object Dim o As A Return o.F() End Function End Class </file> </compilation>) compilation.AssertTheseDiagnostics(<errors> BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. Return o.F() ~~~ </errors>) End Sub ''' <summary> ''' No warning reported for expression that will not be evaluated. ''' </summary> <Fact()> Public Sub BC42104WRN_DefAsgUseNullRef_AddressOfUnevaluatedReceiver() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class A Shared Sub M() End Sub Shared Function F() As System.Action Dim o As A Return AddressOf (o).M End Function End Class </file> </compilation>) compilation.AssertTheseDiagnostics(<errors> BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. Return AddressOf (o).M ~~~~~~~~~~~~~~~ </errors>) End Sub ''' <summary> ''' No warning reported for expression that will not be evaluated. ''' </summary> <Fact()> Public Sub BC42104WRN_DefAsgUseNullRef_TypeExpressionUnevaluatedReceiver() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class A Class B Friend Const F As Object = Nothing End Class Shared Function M() As Object Dim o As A Return o.B.F End Function End Class </file> </compilation>) compilation.AssertTheseDiagnostics(<errors> BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. Return o.B.F ~~~ </errors>) End Sub <WorkItem(528735, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528735")> <Fact()> Public Sub BC42105WRN_DefAsgNoRetValFuncRef1() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BC42105WRN_DefAsgNoRetValFuncRef1"> <file name="a.vb"> Interface I End Interface Class A End Class Class C(Of T1, T2 As Class, T3 As Structure, T4 As New, T5 As I, T6 As A, T7 As U, U) Function F0() As Object End Function ' F0 Function F1() As T1 End Function ' F1 Function F2() As T2 End Function ' F2 Function F3() As T3 End Function ' F3 Function F4() As T4 End Function ' F4 Function F5() As T5 End Function ' F5 Function F6() As T6 End Function ' F6 Function F7() As T7 End Function ' F7 End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC42105: Function 'F0' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used. End Function ' F0 ~~~~~~~~~~~~ BC42105: Function 'F2' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used. End Function ' F2 ~~~~~~~~~~~~ BC42105: Function 'F6' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used. End Function ' F6 ~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <WorkItem(545313, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545313")> <Fact()> Public Sub BC42105WRN_DefAsgNoRetValFuncRef1b() ' Make sure initializers are analyzed for errors/warnings Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="BC42105WRN_DefAsgNoRetValFuncRef1b"> <file name="a.vb"> Option Strict On Imports System Module Module1 Dim f As Func(Of String) = Function() As String End Function Sub S() Dim l As Func(Of String) = Function() As String End Function End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors><![CDATA[ BC42105: Function '<anonymous method>' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used. End Function ~~~~~~~~~~~~ BC42105: Function '<anonymous method>' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used. End Function ~~~~~~~~~~~~ ]]> </errors>) End Sub <WorkItem(837973, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/837973")> <Fact()> Public Sub Bug837973() Dim compilation1 = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation> <file name="a.vb"> Imports System Imports System.Runtime.CompilerServices Imports System.Runtime.InteropServices Imports System.Threading.Tasks 'COMPILEERRORTOTAL: 2 Public Module Async_Regress134668 Public Function MethodFunction(x As Func(Of Object)) As Integer Return 1 End Function Public Async Sub Async_Regress134668_Test() Await Task.Yield Dim i1 = MethodFunction(Async Function() As Task Await Task.Yield End Function) Dim i2 = MethodFunction(Function() As Task 'COMPILEWARNING: BC42105, "End Function" End Function) ' 1 Dim i4 = MethodFunction(Function() As Task return Nothing End Function) ' 1 Dim i3 = MethodFunction(Async Function() As Task(Of Integer) Await Task.Delay(10) 'COMPILEWARNING: BC42105, "End Function" End Function) ' 2 End Sub Public Function Async_Regress134668_Test2() As Object Async_Regress134668_Test2 = Nothing Dim i2 = MethodFunction(Function() As Task End Function) ' 3 End Function ' 4 Public Function Async_Regress134668_Test3() As Object Dim i2 = MethodFunction(Function() As Task Return Nothing End Function) End Function ' 5 End Module </file> </compilation>, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseDll) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors><![CDATA[ BC42105: Function '<anonymous method>' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used. End Function) ' 1 ~~~~~~~~~~~~ BC42105: Function '<anonymous method>' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used. End Function) ' 2 ~~~~~~~~~~~~ BC42105: Function '<anonymous method>' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used. End Function) ' 3 ~~~~~~~~~~~~ BC42105: Function 'Async_Regress134668_Test3' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used. End Function ' 5 ~~~~~~~~~~~~ ]]></errors>) End Sub <WorkItem(545313, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545313")> <Fact()> Public Sub BC42105WRN_DefAsgNoRetValFuncRef1c() ' Make sure initializers are analyzed for errors/warnings ONLY ONCE Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="BC42105WRN_DefAsgNoRetValFuncRef1c"> <file name="a.vb"> Option Strict On Imports System Class C1 Private s As Func(Of String) = Function() As String End Function Public Sub New() End Sub Public Sub New(i As Integer) MyClass.New() End Sub Public Sub New(i As Long) End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> <![CDATA[ BC42105: Function '<anonymous method>' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used. End Function ~~~~~~~~~~~~ ]]> </errors>) End Sub <Fact()> Public Sub BC42106WRN_DefAsgNoRetValOpRef1() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="DefAsgNoRetValOpSubst1"> <file name="a.vb"> Interface I End Interface Class A End Class Class C(Of T1, T2 As Class, T3 As Structure, T4 As New, T5 As I, T6 As A, T7 As U, U) Class C0 Shared Operator -(o As C0) As Object End Operator ' C0 End Class Class C1 Shared Operator -(o As C1) As T1 End Operator ' C1 End Class Class C2 Shared Operator -(o As C2) As T2 End Operator ' C2 End Class Class C3 Shared Operator -(o As C3) As T3 End Operator ' C3 End Class Class C4 Shared Operator -(o As C4) As T4 End Operator ' C4 End Class Class C5 Shared Operator -(o As C5) As T5 End Operator ' C5 End Class Class C6 Shared Operator -(o As C6) As T6 End Operator ' C6 End Class Class C7 Shared Operator -(o As C7) As T7 End Operator ' C7 End Class End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC42106: Operator '-' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used. End Operator ' C0 ~~~~~~~~~~~~ BC42106: Operator '-' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used. End Operator ' C2 ~~~~~~~~~~~~ BC42106: Operator '-' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used. End Operator ' C6 ~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC42107WRN_DefAsgNoRetValPropRef1() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="DefAsgNoRetValPropSubst1"> <file name="a.vb"> Interface I End Interface Class A End Class Class C(Of T1, T2 As Class, T3 As Structure, T4 As New, T5 As I, T6 As A, T7 As U, U) ReadOnly Property P0 As Object Get End Get ' P0 End Property ReadOnly Property P1 As T1 Get End Get ' P1 End Property ReadOnly Property P2 As T2 Get End Get ' P2 End Property ReadOnly Property P3 As T3 Get End Get ' P3 End Property ReadOnly Property P4 As T4 Get End Get ' P4 End Property ReadOnly Property P5 As T5 Get End Get ' P5 End Property ReadOnly Property P6 As T6 Get End Get ' P6 End Property ReadOnly Property P7 As T7 Get End Get ' P7 End Property End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC42107: Property 'P0' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used. End Get ' P0 ~~~~~~~ BC42107: Property 'P2' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used. End Get ' P2 ~~~~~~~ BC42107: Property 'P6' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used. End Get ' P6 ~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <WorkItem(540421, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540421")> <Fact()> Public Sub BC42108WRN_DefAsgUseNullRefByRefStr() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Structure S Public Fld As String End Structure Class C Shared Sub M(p1 As String, ByRef p2 As String) Dim s1 As S Dim s2 As S Dim l1 As String Dim a1 As String() = New String(3) {} a1(2) = "abc" M(s1) M(s2.Fld) M(l1) M(p1) M(p2) M(a1(2)) End Sub Shared Sub M(ByRef o As Object) End Sub End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC42108: Variable 's1' is passed by reference before it has been assigned a value. A null reference exception could result at runtime. Make sure the structure or all the reference members are initialized before use M(s1) ~~ BC42030: Variable 'Fld' is passed by reference before it has been assigned a value. A null reference exception could result at runtime. M(s2.Fld) ~~~~~~ BC42030: Variable 'l1' is passed by reference before it has been assigned a value. A null reference exception could result at runtime. M(l1) ~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC42108_NoWarningForOutParameter() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Structure SSS Public F As String End Structure Module Program Sub Main(args As String()) Dim s As SSS Call (New Dictionary(Of Integer, SSS)).TryGetValue(1, s) End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC42108: Variable 's' is passed by reference before it has been assigned a value. A null reference exception could result at runtime. Make sure the structure or all the reference members are initialized before use Call (New Dictionary(Of Integer, SSS)).TryGetValue(1, s) ~ </errors>) End Sub <Fact()> Public Sub BC42108_StillWarningForLateBinding() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Structure SSS Public F As String End Structure Module Program Sub Main(args As String()) Dim s As SSS Dim o As Object = New Dictionary(Of Integer, SSS) o.TryGetValue(1, s) End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC42108: Variable 's' is passed by reference before it has been assigned a value. A null reference exception could result at runtime. Make sure the structure or all the reference members are initialized before use o.TryGetValue(1, s) ~ </errors>) End Sub <WorkItem(540421, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540421")> <Fact()> Public Sub BC42108WRN_DefAsgUseNullRefByRefStr2() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Class C Public Fld As String End Class Class CC Public FldC As C Public FldS As S End Class Structure S Public Fld As String End Structure Structure SS Public FldC As C Public FldS As S End Structure Class Main Shared Sub M(p1 As String, ByRef p2 As String) Dim s1 As S Dim s2 As SS Dim s3 As SS Dim c1 As C Dim c2 As CC Dim c3 As CC M(s1.Fld) M(s2.FldS.Fld) M(s3.FldC.Fld) M(c1.Fld) M(c2.FldS.Fld) M(c3.FldC.Fld) End Sub Shared Sub M(ByRef o As Object) End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC42030: Variable 'Fld' is passed by reference before it has been assigned a value. A null reference exception could result at runtime. M(s1.Fld) ~~~~~~ BC42030: Variable 'Fld' is passed by reference before it has been assigned a value. A null reference exception could result at runtime. M(s2.FldS.Fld) ~~~~~~~~~~~ BC42104: Variable 'FldC' is used before it has been assigned a value. A null reference exception could result at runtime. M(s3.FldC.Fld) ~~~~~~~ BC42104: Variable 'c1' is used before it has been assigned a value. A null reference exception could result at runtime. M(c1.Fld) ~~ BC42104: Variable 'c2' is used before it has been assigned a value. A null reference exception could result at runtime. M(c2.FldS.Fld) ~~ BC42104: Variable 'c3' is used before it has been assigned a value. A null reference exception could result at runtime. M(c3.FldC.Fld) ~~ </errors>) End Sub <Fact()> Public Sub BC42109WRN_DefAsgUseNullRefStr() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Structure S Public F As Object End Structure Class C Shared Sub M() Dim s As S M(s) End Sub Shared Sub M(o As Object) End Sub End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC42109: Variable 's' is used before it has been assigned a value. A null reference exception could result at runtime. Make sure the structure or all the reference members are initialized before use M(s) ~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <WorkItem(546818, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546818")> <Fact()> Public Sub BC42109WRN_DefAsgUseNullRefStr_NoError() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System Public Structure AccObjFromWindow Public hwnd As IntPtr Public ppvObject As Object End Structure Class SSS Public Sub S() Dim input As AccObjFromWindow input.hwnd = IntPtr.Zero input.ppvObject = Nothing Dim a = input End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors></errors>) End Sub <WorkItem(547098, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547098")> <Fact()> Public Sub BC42109WRN_DefAsgUseNullRefStr_NoError2() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Module Module1 Sub Main() Dim s As str1 Dim sTmp As String = "" AddHandler s.e1, AddressOf s.sub1 Call s.revent(True, sTmp) AddHandler s.e1, AddressOf s.sub2 sTmp = "" Call s.revent(True, sTmp) ' place BP here End Sub End Module Structure str1 Dim i As Integer Public Event e1(ByVal b As Boolean, ByRef s As String) Sub revent(ByVal b As Boolean, ByRef s As String) RaiseEvent e1(b, s) End Sub Sub sub1(ByVal b As Boolean, ByRef s As String) s = s &amp; "1" End Sub Sub sub2(ByVal b As Boolean, ByRef s As String) s = s &amp; "2" End Sub End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors></errors>) End Sub <WorkItem(546377, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546377")> <WorkItem(546423, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546423")> <WorkItem(546420, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546420")> <Fact()> Public Sub Bug15747() Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Module Program Sub Main() Dim hscr As IntPtr Try hscr = New IntPtr Catch ex As Exception If Not hscr.Equals(IntPtr.Zero) Then End If End Try End Sub End Module </file> </compilation>).VerifyDiagnostics() End Sub <WorkItem(546377, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546377")> <WorkItem(546423, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546423")> <WorkItem(546420, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546420")> <Fact()> Public Sub Bug15747b() Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Module Program Sub Main() Dim hscr As UIntPtr Try hscr = New UIntPtr Catch ex As Exception If Not hscr.Equals(UIntPtr.Zero) Then End If End Try End Sub End Module </file> </compilation>).VerifyDiagnostics() End Sub <WorkItem(546175, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546175")> <Fact()> Public Sub BC42109WRN_DefAsgUseNullRefStr_Dev11Compat() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Public Structure NonGenericReference Private s As String Public Structure GenericReference(Of T) Private s As String End Structure End Structure Public Structure GenericReference(Of T) Private s As String Public Structure NonGenericReference Private s As String End Structure End Structure Public Structure GenericReference2(Of T) Private s2 As Integer End Structure </file> </compilation>) Dim reference1 = compilation1.EmitToImageReference() Dim reference2 = CreateReferenceFromIlCode(<![CDATA[ .class public sequential ansi sealed beforefieldinit GenericWithPtr`1<T> extends [mscorlib]System.ValueType { //.field private int32* aa } // end of class GenericWithPtr`1 ]]>.Value) Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim a As NonGenericReference Dim b As GenericReference(Of Integer) Dim c As GenericReference(Of String) Dim d As NonGenericReference.GenericReference(Of Integer) Dim e As NonGenericReference.GenericReference(Of String) Dim f As GenericReference(Of Integer).NonGenericReference Dim g As GenericReference(Of String).NonGenericReference Dim i As GenericReference2(Of Integer) Dim j As GenericReference2(Of String) Dim k As GenericWithPtr(Of Integer) Dim z1 = a ' No Warning Dim z2 = b Dim z3 = c Dim z4 = d Dim z5 = e Dim z6 = f Dim z7 = g Dim z8 = i ' No Warning Dim z9 = j ' No Warning Dim za = k ' No Warning End Sub End Module </file> </compilation>, references:={reference1, reference2}). VerifyDiagnostics(Diagnostic(ERRID.WRN_DefAsgUseNullRefStr, "b").WithArguments("b"), Diagnostic(ERRID.WRN_DefAsgUseNullRefStr, "c").WithArguments("c"), Diagnostic(ERRID.WRN_DefAsgUseNullRefStr, "d").WithArguments("d"), Diagnostic(ERRID.WRN_DefAsgUseNullRefStr, "e").WithArguments("e"), Diagnostic(ERRID.WRN_DefAsgUseNullRefStr, "f").WithArguments("f"), Diagnostic(ERRID.WRN_DefAsgUseNullRefStr, "g").WithArguments("g")) End Sub <WorkItem(546175, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546175")> <Fact()> Public Sub BC42109WRN_DefAsgUseNullRefStr_Dev11Compat2() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Public Structure NonGenericReference Private s As String Public Structure GenericReference(Of T) Private s As String End Structure End Structure Public Structure GenericReference(Of T) Private s As String Public Structure NonGenericReference Private s As String End Structure End Structure Public Structure GenericReference2(Of T) Private s2 As Integer End Structure </file> </compilation>) Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim a As NonGenericReference Dim b As GenericReference(Of Integer) Dim c As GenericReference(Of String) Dim d As NonGenericReference.GenericReference(Of Integer) Dim e As NonGenericReference.GenericReference(Of String) Dim f As GenericReference(Of Integer).NonGenericReference Dim g As GenericReference(Of String).NonGenericReference Dim i As GenericReference2(Of Integer) Dim j As GenericReference2(Of String) Dim z1 = a ' Warning!!! Dim z2 = b Dim z3 = c Dim z4 = d Dim z5 = e Dim z6 = f Dim z7 = g Dim z8 = i ' No Warning Dim z9 = j ' No Warning End Sub End Module </file> </compilation>, references:={New VisualBasicCompilationReference(compilation1)}). VerifyDiagnostics(Diagnostic(ERRID.WRN_DefAsgUseNullRefStr, "a").WithArguments("a"), Diagnostic(ERRID.WRN_DefAsgUseNullRefStr, "b").WithArguments("b"), Diagnostic(ERRID.WRN_DefAsgUseNullRefStr, "c").WithArguments("c"), Diagnostic(ERRID.WRN_DefAsgUseNullRefStr, "d").WithArguments("d"), Diagnostic(ERRID.WRN_DefAsgUseNullRefStr, "e").WithArguments("e"), Diagnostic(ERRID.WRN_DefAsgUseNullRefStr, "f").WithArguments("f"), Diagnostic(ERRID.WRN_DefAsgUseNullRefStr, "g").WithArguments("g")) End Sub <WorkItem(652008, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/652008")> <Fact()> Public Sub BC42110WRN_FieldInForNotExplicit_DiagnosticRemoved() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="FieldInForNotExplicit"> <file name="a.vb"> Class Customer Private Index As Integer Sub Main() For Index = 1 To 10 Next End Sub End Class </file> </compilation>) Dim expectedErrors1 = <errors></errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC42322WRN_InterfaceConversion2() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim xx As System.Collections.Generic.IEnumerator(Of Integer) = "hello" End Sub End Module </file> </compilation>) Dim expectedErrors1 = <errors> BC42322: Runtime errors might occur when converting 'String' to 'IEnumerator(Of Integer)'. Dim xx As System.Collections.Generic.IEnumerator(Of Integer) = "hello" ~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <WorkItem(545479, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545479")> <Fact()> Public Sub BC42322WRN_InterfaceConversion2_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="c.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Public Interface I End Interface <C(DirectCast(New C(""), I))> <ComImport()> NotInheritable Class C Inherits Attribute Public Sub New(s As String) End Sub End Class ]]></file> </compilation>) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC30934: Conversion from 'I' to 'String' cannot occur in a constant expression used as an argument to an attribute. <C(DirectCast(New C(""), I))> ~~~~~~~~~~~~~~~~~~~~~~~~ BC42322: Runtime errors might occur when converting 'I' to 'String'. <C(DirectCast(New C(""), I))> ~~~~~~~~~~~~~~~~~~~~~~~~ ]]></errors>) End Sub <Fact()> Public Sub BC42324WRN_LiftControlVariableLambda() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="LiftControlVariableLambda"> <file name="a.vb"> Imports System Class Customer Sub Main() For i As Integer = 1 To (function() i + 10)() Dim exampleFunc1 As Func(Of Integer) = Function() i Next ' since Dev11 the scope for foreach loops has been changed; no warnings here For each j as integer in (function(){1+j, 2+j})() Dim exampleFunc2 As Func(Of Integer) = Function() j Next End Sub End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC42324: Using the iteration variable in a lambda expression may have unexpected results. Instead, create a local variable within the loop and assign it the value of the iteration variable. For i As Integer = 1 To (function() i + 10)() ~ BC42324: Using the iteration variable in a lambda expression may have unexpected results. Instead, create a local variable within the loop and assign it the value of the iteration variable. Dim exampleFunc1 As Func(Of Integer) = Function() i ~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC42326WRN_LambdaPassedToRemoveHandler() CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="LambdaPassedToRemoveHandler"> <file name="a.vb"> Module Module1 Event ProcessInteger(ByVal x As Integer) Sub Main() AddHandler ProcessInteger, Function(m As Integer) m RemoveHandler ProcessInteger, Function(m As Integer) m End Sub End Module </file> </compilation>).VerifyDiagnostics(Diagnostic(ERRID.WRN_LambdaPassedToRemoveHandler, "Function(m As Integer) m")) End Sub <WorkItem(545252, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545252")> <Fact()> Public Sub BC30413ERR_WithEventsIsDelegate() CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="LambdaPassedToRemoveHandler"> <file name="a.vb"> Imports System Class Derived WithEvents e As Action = Sub() Exit Sub WithEvents e1, e2 As New Integer() End Class </file> </compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_WithEventsAsStruct, "e"), Diagnostic(ERRID.ERR_WithEventsAsStruct, "e1"), Diagnostic(ERRID.ERR_WithEventsAsStruct, "e2")) End Sub <WorkItem(545195, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545195")> <Fact()> Public Sub BC42328WRN_RelDelegatePassedToRemoveHandler() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="RelDelegatePassedToRemoveHandler"> <file name="a.vb"> Class A Public Val As Integer Sub New(ByVal i As Integer) Val = i End Sub End Class Class B Inherits A Sub New(ByVal i As Integer) MyBase.New(i) End Sub End Class Class C1 Delegate Sub HandlerNum(ByVal i As Integer) Delegate Sub HandlerCls(ByVal a As B) Dim WithEvents inner As C1 Event evtNum As HandlerNum Event evtCls As HandlerCls Sub HandleLong1(ByVal l As Long) End Sub Sub HandlesWithNum(ByVal l As Long) Handles inner.evtNum End Sub Sub foo() RemoveHandler evtNum, AddressOf HandleLong1 inner = New C1() RemoveHandler inner.evtNum, AddressOf HandlesWithNum End Sub End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC42328: The 'AddressOf' expression has no effect in this context because the method argument to 'AddressOf' requires a relaxed conversion to the delegate type of the event. Assign the 'AddressOf' expression to a variable, and use the variable to add or remove the method as the handler. RemoveHandler evtNum, AddressOf HandleLong1 ~~~~~~~~~~~ BC42328: The 'AddressOf' expression has no effect in this context because the method argument to 'AddressOf' requires a relaxed conversion to the delegate type of the event. Assign the 'AddressOf' expression to a variable, and use the variable to add or remove the method as the handler. RemoveHandler inner.evtNum, AddressOf HandlesWithNum ~~~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC42335WRN_TypeInferenceAssumed3() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="TypeInferenceAssumed3"> <file name="a.vb"> Option Strict On Imports System.Collections.Generic Module M1 Sub foo() foo1({}) foo1({Nothing}) Foo2({}, {}) Foo2({Nothing}, {Nothing}) Foo2({Nothing}, {}) End Sub Sub foo1(Of t)(ByVal x As t()) End Sub Sub Foo2(Of t)(ByVal x As t, ByVal y As t) End Sub End Module </file> </compilation>) Dim expectedErrors1 = <errors> BC42335: Data type of 't' in 'Public Sub foo1(Of t)(x As t())' could not be inferred. 'Object' assumed. foo1({}) ~~ BC42335: Data type of 't' in 'Public Sub foo1(Of t)(x As t())' could not be inferred. 'Object' assumed. foo1({Nothing}) ~~~~~~~~~ BC42335: Data type of 't' in 'Public Sub Foo2(Of t)(x As t, y As t)' could not be inferred. 'Object()' assumed. Foo2({}, {}) ~~ BC42335: Data type of 't' in 'Public Sub Foo2(Of t)(x As t, y As t)' could not be inferred. 'Object()' assumed. Foo2({Nothing}, {Nothing}) ~~~~~~~~~ BC42335: Data type of 't' in 'Public Sub Foo2(Of t)(x As t, y As t)' could not be inferred. 'Object()' assumed. Foo2({Nothing}, {}) ~~~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC42349WRN_ObsoleteIdentityDirectCastForValueType() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="ObsoleteIdentityDirectCastForValueType"> <file name="a.vb"> Class cls Sub test() Dim l1 = DirectCast(1L, Long) End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42349: Using DirectCast operator to cast a value-type to the same type is obsolete. Dim l1 = DirectCast(1L, Long) ~~ </expected>) End Sub <Fact()> Public Sub BC42349WRN_ObsoleteIdentityDirectCastForValueType_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="ObsoleteIdentityDirectCastForValueType"> <file name="a.vb"> Class C1 function test() return DirectCast(True, Boolean) End function End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42349: Using DirectCast operator to cast a value-type to the same type is obsolete. return DirectCast(True, Boolean) ~~~~ </expected>) End Sub <Fact()> Public Sub BC42351WRN_MutableStructureInUsing() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="MutableStructureInUsing"> <file name="a.vb"> Imports System Structure MutableStructure Implements IDisposable Dim dummy As Integer ' this field triggers the warning Public Sub Dispose() Implements System.IDisposable.Dispose End Sub End Structure Structure ImmutableStructure Implements IDisposable Public Shared disposed As Integer Public Sub Dispose() Implements System.IDisposable.Dispose disposed = disposed + 1 End Sub End Structure Class ReferenceType Implements IDisposable Dim dummy As Integer Public Sub Dispose() Implements System.IDisposable.Dispose End Sub End Class Module M1 Sub foo() ' resource type is a concrete structure + immutable (OK) Using a As New ImmutableStructure() End Using Using New ImmutableStructure() ' ok End Using ' resource type is a concrete structure + mutable (Warning) Using b As New MutableStructure() End Using Using New MutableStructure() ' as expression also ok. End Using ' reference types + mutable (OK) Using c As New ReferenceType() End Using Using New ReferenceType() ' ok End Using End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42351: Local variable 'b' is read-only and its type is a structure. Invoking its members or passing it ByRef does not change its content and might lead to unexpected results. Consider declaring this variable outside of the 'Using' block. Using b As New MutableStructure() ~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC42351WRN_MutableStructureInUsingGenericConstraints() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="BC42351WRN_MutableStructureInUsingGenericConstraints"> <file name="a.vb"> Imports System Structure MutableStructure Implements IDisposable Dim dummy As Integer ' this field triggers the warning Public Sub Dispose() Implements System.IDisposable.Dispose End Sub End Structure Structure ImmutableStructure Implements IDisposable Public Shared disposed As Integer Public Sub Dispose() Implements System.IDisposable.Dispose disposed = disposed + 1 End Sub End Structure Class ReferenceType Implements IDisposable Dim dummy As Integer Public Sub Dispose() Implements System.IDisposable.Dispose End Sub End Class Module M1 Sub foo(Of T as {Structure, IDisposable}, U as {ReferenceType, New, IDisposable}, V as {Structure})() ' resource type is a type parameter with a structure constraint (Warning, always) Using a As T = Directcast(new MutableStructure(), IDisposable) End Using ' resource type is a type parameter with a reference type constraint (OK) Using b As U = TryCast(new ReferenceType(), U) End Using ' resource type is a type parameter with a structure constraint (Warning, always) Using c As V = DirectCast(new ImmutableStructure(), IDisposable) End Using End Sub End Module ' Getting a concrete structure as a class constraint through overridden generic methods Class BaseGeneric(Of S) Public Overridable Sub MySub(Of T As S)(param As T) End Sub End Class Class DerivedImmutable Inherits BaseGeneric(Of ImmutableStructure) Public Overrides Sub MySub(Of T As ImmutableStructure)(param As T) Using immutable As T = New ImmutableStructure() ' OK End Using End Sub End Class Class DerivedMutable Inherits BaseGeneric(Of MutableStructure) Public Overrides Sub MySub(Of T As MutableStructure)(param As T) Using mutable As T = New MutableStructure() ' shows warning End Using End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42351: Local variable 'a' is read-only and its type is a structure. Invoking its members or passing it ByRef does not change its content and might lead to unexpected results. Consider declaring this variable outside of the 'Using' block. Using a As T = Directcast(new MutableStructure(), IDisposable) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36010: 'Using' operand of type 'V' must implement 'System.IDisposable'. Using c As V = DirectCast(new ImmutableStructure(), IDisposable) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42351: Local variable 'c' is read-only and its type is a structure. Invoking its members or passing it ByRef does not change its content and might lead to unexpected results. Consider declaring this variable outside of the 'Using' block. Using c As V = DirectCast(new ImmutableStructure(), IDisposable) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42351: Local variable 'mutable' is read-only and its type is a structure. Invoking its members or passing it ByRef does not change its content and might lead to unexpected results. Consider declaring this variable outside of the 'Using' block. Using mutable As T = New MutableStructure() ' shows warning ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC42352WRN_MutableGenericStructureInUsing() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="MutableGenericStructureInUsing"> <file name="a.vb"> Imports System Module M1 Class ReferenceType Implements IDisposable Dim dummy As Integer Public Sub Dispose() Implements System.IDisposable.Dispose End Sub End Class Sub Foo(Of T As {New, IDisposable}, U As {New, IDisposable})(ByVal x As T) 'COMPILEWARNING: BC42352, "a", BC42352, "b" Using a as T = DirectCast(New ReferenceType(), IDisposable), b As New U() End Using End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42352: Local variable 'a' is read-only. When its type is a structure, invoking its members or passing it ByRef does not change its content and might lead to unexpected results. Consider declaring this variable outside of the 'Using' block. Using a as T = DirectCast(New ReferenceType(), IDisposable), b As New U() ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42352: Local variable 'b' is read-only. When its type is a structure, invoking its members or passing it ByRef does not change its content and might lead to unexpected results. Consider declaring this variable outside of the 'Using' block. Using a as T = DirectCast(New ReferenceType(), IDisposable), b As New U() ~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC42353WRN_DefAsgNoRetValFuncVal1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Structure gStr1(Of T) Function Fun1(ByVal t1 As T) As Boolean End Function End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42353: Function 'Fun1' doesn't return a value on all code paths. Are you missing a 'Return' statement? End Function ~~~~~~~~~~~~ </expected>) End Sub <WorkItem(542802, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542802")> <Fact()> Public Sub BC42353WRN_DefAsgNoRetValFuncVal1_Lambda() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="a.vb"> Imports System.Linq Class BaseClass Sub Method() Dim x = New Integer() {} x.Where(Function(y) Exit Function Return y = "" End Function) End Sub End Class Class DerivedClass Inherits BaseClass Shared Sub Main() End Sub End Class </file> </compilation>, {Net40.SystemCore}) VerifyDiagnostics(compilation, Diagnostic(ERRID.WRN_DefAsgNoRetValFuncVal1, "End Function").WithArguments("<anonymous method>")) End Sub <WorkItem(542816, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542816")> <Fact()> Public Sub BC42353WRN_DefAsgNoRetValFuncVal1_Lambda_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="a.vb"> Imports System.Linq Class BaseClass Function Method() Dim x = New Integer() {} x.Where(Function(y) Exit Function ' 0 Return y = "" End Function) ' 1 End Function ' 2 End Class Class DerivedClass Inherits BaseClass Shared Sub Main() End Sub End Class </file> </compilation>, {Net40.SystemCore}) AssertTheseDiagnostics(compilation, <expected><![CDATA[ BC42353: Function '<anonymous method>' doesn't return a value on all code paths. Are you missing a 'Return' statement? End Function) ' 1 ~~~~~~~~~~~~ BC42105: Function 'Method' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used. End Function ' 2 ~~~~~~~~~~~~ ]]></expected>) End Sub <Fact()> Public Sub BC42353WRN_DefAsgNoRetValFuncVal1_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Structure gStr1 Function Fun1(y As Integer) As Boolean Exit Function 'Return y = "" End Function End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42353: Function 'Fun1' doesn't return a value on all code paths. Are you missing a 'Return' statement? End Function ~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC42353WRN_DefAsgNoRetValFuncVal1_Query_Lambda() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports System.Runtime.CompilerServices Class BaseClass Sub Method() Dim x = New Integer() {} x.Where(Function(y) Exit Function Return y = "" End Function) End Sub End Class Class DerivedClass Inherits BaseClass Shared Sub Main() End Sub End Class </file> </compilation>, {Net40.SystemCore}) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42353: Function '&lt;anonymous method&gt;' doesn't return a value on all code paths. Are you missing a 'Return' statement? End Function) ~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC42354WRN_DefAsgNoRetValOpVal1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C Shared Operator -(x As C) As Integer End Operator End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42354: Operator '-' doesn't return a value on all code paths. Are you missing a 'Return' statement? End Operator ~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC42355WRN_DefAsgNoRetValPropVal1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C Shared F As Boolean Shared ReadOnly Property P As Integer Get If F Then Return 0 End If End Get End Property End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42355: Property 'P' doesn't return a value on all code paths. Are you missing a 'Return' statement? End Get ~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC42356WRN_UnreachableCode_MethodBody() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Module M1 Sub Main() dim x as integer = 0 goto l1 if x > 0 then l1: Console.WriteLine("hello 1.") end if goto l2 Console.WriteLine("hello 2.") Console.WriteLine("hello 3.") l2: End Sub End Module </file> </compilation>) Dim expectedErrors1 = <errors> </errors> CompilationUtils.AssertTheseDiagnostics(compilation, expectedErrors1) End Sub <Fact()> Public Sub BC42356WRN_UnreachableCode_LambdaBody() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Module M1 Sub Main() dim y as Action = sub() dim x as integer = 0 goto l1 if x > 0 then l1: Console.WriteLine("hello 1.") end if goto l2 Console.WriteLine("hello 2.") Console.WriteLine("hello 3.") l2: End Sub End Sub End Module </file> </compilation>) Dim expectedErrors1 = <errors> </errors> CompilationUtils.AssertTheseDiagnostics(compilation, expectedErrors1) End Sub <Fact()> Public Sub BC42359WRN_EmptyPrefixAndXmlnsLocalName() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports <xmlns:empty=""> Module M Private F As Object = <x empty:xmlns="http://roslyn"/> End Module ]]></file> </compilation>, references:=XmlReferences) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC42368: The xmlns attribute has special meaning and should not be written with a prefix. Private F As Object = <x empty:xmlns="http://roslyn"/> ~~~~~~~~~~~ ]]></errors>) End Sub <Fact()> Public Sub BC42360WRN_PrefixAndXmlnsLocalName() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports <xmlns:p1="http://roslyn/"> Module M Private F1 As Object = <x p1:xmlns="http://roslyn/1"/> Private F2 As Object = <x p2:xmlns="http://roslyn/2"/> Private F3 As Object = <x xmlns:p3="http://roslyn/3a" p3:xmlns="http://roslyn/3b"/> End Module ]]></file> </compilation>, references:=XmlReferences) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC42360: It is not recommended to have attributes named xmlns. Did you mean to write 'xmlns:p1' to define a prefix named 'p1'? Private F1 As Object = <x p1:xmlns="http://roslyn/1"/> ~~~~~~~~ BC31148: XML namespace prefix 'p2' is not defined. Private F2 As Object = <x p2:xmlns="http://roslyn/2"/> ~~ BC42360: It is not recommended to have attributes named xmlns. Did you mean to write 'xmlns:p2' to define a prefix named 'p2'? Private F2 As Object = <x p2:xmlns="http://roslyn/2"/> ~~~~~~~~ BC42360: It is not recommended to have attributes named xmlns. Did you mean to write 'xmlns:p3' to define a prefix named 'p3'? Private F3 As Object = <x xmlns:p3="http://roslyn/3a" p3:xmlns="http://roslyn/3b"/> ~~~~~~~~ ]]></errors>) End Sub #End Region <Fact> Public Sub Bug17315_CompilationUnit() Dim c = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation name="C"> <file> End Class </file> </compilation>, Enumerable.Empty(Of MetadataReference)()) c.AssertTheseDiagnostics( <errors> BC30002: Type 'System.Void' is not defined. End Class ~~~~~~~~~ BC30460: 'End Class' must be preceded by a matching 'Class'. End Class ~~~~~~~~~ BC31091: Import of type 'Object' from assembly or module 'C.dll' failed. End Class ~~~~~~~~~ </errors>) End Sub <WorkItem(938459, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/938459")> <Fact> Public Sub UnimplementedMethodsIncorrectSquiggleLocationInterfaceInheritanceOrdering() Dim c = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="C"> <file> Module Module1 Sub Main() End Sub End Module Interface IBase Sub method1() End Interface Interface IBase2 Sub method2() End Interface Interface IDerived Inherits IBase Sub method3() End Interface Interface IDerived2 Inherits IDerived Sub method4() End Interface Class foo Implements IDerived2, IDerived, IBase, IBase2 Public Sub method1() Implements IBase.method1 End Sub Public Sub method2() Implements IBase2.method2 End Sub Public Sub method4() Implements IDerived2.method4 End Sub End Class </file> </compilation>) c.AssertTheseDiagnostics( <errors> BC30149: Class 'foo' must implement 'Sub method3()' for interface 'IDerived'. Implements IDerived2, IDerived, IBase, IBase2 ~~~~~~~~ </errors>) ' Change order so interfaces are defined in a completely different order. ' The bug related to order of interfaces. c = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="C"> <file> Module Module1 Sub Main() End Sub End Module Interface IBase Sub method1() End Interface Interface IBase2 Sub method2() End Interface Interface IDerived Inherits IBase Sub method3() End Interface Interface IDerived2 Inherits IDerived Sub method4() End Interface Class foo Implements IBase, IBase2, IDerived2, IDerived Public Sub method4() Implements IDerived2.method4 End Sub Public Sub method1() Implements IBase.method1 End Sub Public Sub method2() Implements IBase2.method2 End Sub End Class </file> </compilation>) c.AssertTheseDiagnostics( <errors> BC30149: Class 'foo' must implement 'Sub method3()' for interface 'IDerived'. Implements IBase, IBase2, IDerived2, IDerived ~~~~~~~~ </errors>) End Sub <Fact> Public Sub Bug17315_Namespace() Dim c = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation name="C"> <file> Namespace N Sub Foo End Sub End Namespace </file> </compilation>, Enumerable.Empty(Of MetadataReference)()) c.AssertTheseDiagnostics( <errors> BC30002: Type 'System.Void' is not defined. Namespace N ~~~~~~~~~~~~ BC31091: Import of type 'Object' from assembly or module 'C.dll' failed. Namespace N ~~~~~~~~~~~~ BC30001: Statement is not valid in a namespace. Sub Foo ~~~~~~~ BC30002: Type 'System.Void' is not defined. Sub Foo ~~~~~~~~ </errors>) End Sub <Fact(), WorkItem(530126, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530126")> Public Sub Bug_15314_Class() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="NotYetImplementedInRoslyn"> <file name="a.vb"> Public Class C Public Sub New() Protected Class D Public Sub New() End Class End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC30026: 'End Sub' expected. Public Sub New() ~~~~~~~~~~~~~~~~ BC30289: Statement cannot appear within a method body. End of method assumed. Protected Class D ~~~~~~~~~~~~~~~~~ BC30026: 'End Sub' expected. Public Sub New() ~~~~~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact(), WorkItem(530126, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530126")> Public Sub Bug_15314_Interface() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="NotYetImplementedInRoslyn"> <file name="a.vb"> Public Class C Public Sub New() Protected Interface D End Interface End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC30026: 'End Sub' expected. Public Sub New() ~~~~~~~~~~~~~~~~ BC30289: Statement cannot appear within a method body. End of method assumed. Protected Interface D ~~~~~~~~~~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact(), WorkItem(530126, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530126")> Public Sub Bug_15314_Enum() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="NotYetImplementedInRoslyn"> <file name="a.vb"> Public Class CE Public Sub New() Protected Enum DE blah End Enum End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC30026: 'End Sub' expected. Public Sub New() ~~~~~~~~~~~~~~~~ BC30289: Statement cannot appear within a method body. End of method assumed. Protected Enum DE ~~~~~~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact(), WorkItem(530126, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530126")> Public Sub Bug_15314_Structure() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="NotYetImplementedInRoslyn"> <file name="a.vb"> Public Class CS Public Sub New() Protected Structure DS End Structure End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC30026: 'End Sub' expected. Public Sub New() ~~~~~~~~~~~~~~~~ BC30289: Statement cannot appear within a method body. End of method assumed. Protected Structure DS ~~~~~~~~~~~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub Bug4185() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="NotYetImplementedInRoslyn"> <file name="a.vb"> Public Class Hello5 Public Shared Sub Main(args As String()) System.Console.WriteLine("Hello, World!") Environent.ExitCode = 0 End Sub End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC30451: 'Environent' is not declared. It may be inaccessible due to its protection level. Environent.ExitCode = 0 ~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact(), WorkItem(545179, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545179")> Public Sub Bug13459() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="NotYetImplementedInRoslyn"> <file name="a.vb"> Imports System Module Program Function ReturnVoid() As System.Void Throw New Exception() End Function Sub Main() Dim x = Function() As System.Void Throw New Exception() End Function End Sub End Module </file> </compilation>) Dim expectedErrors1 = <errors> BC31422: 'System.Void' can only be used in a GetType expression. Function ReturnVoid() As System.Void ~~~~~~~~~~~ BC31422: 'System.Void' can only be used in a GetType expression. Dim x = Function() As System.Void ~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <WorkItem(541066, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541066")> <Fact()> Public Sub BaseConstructorImplicitCallWithoutSystemVoid() Dim compilation1 = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation name="BaseConstructorImplicitCallWithoutSystemVoid"> <file name="a.vb"> Public Class C1 Public Sub New() End Sub End Class Public Class C2 Inherits C1 End Class </file> </compilation>, Enumerable.Empty(Of MetadataReference)()) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC31091: Import of type 'Object' from assembly or module 'BaseConstructorImplicitCallWithoutSystemVoid.dll' failed. Public Class C1 ~~ BC30002: Type 'System.Void' is not defined. Public Sub New() ~~~~~~~~~~~~~~~~~ BC30002: Type 'System.Void' is not defined. Public Class C2 ~~~~~~~~~~~~~~~~~ </errors>) End Sub <WorkItem(541066, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541066")> <Fact()> Public Sub ParamArrayBindingCheckForAttributeConstructor() Dim compilation1 = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation name="ParamArrayBindingCheckForAttributeConstructor"> <file name="a.vb"> Public Class C1 Public Sub S(ParamArray p As String()) End Sub End Class </file> </compilation>, Enumerable.Empty(Of MetadataReference)()) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC30002: Type 'System.Void' is not defined. Public Class C1 ~~~~~~~~~~~~~~~~~ BC31091: Import of type 'Object' from assembly or module 'ParamArrayBindingCheckForAttributeConstructor.dll' failed. Public Class C1 ~~ BC30002: Type 'System.Void' is not defined. Public Sub S(ParamArray p As String()) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC35000: Requested operation is not available because the runtime library function 'System.ParamArrayAttribute..ctor' is not defined. Public Sub S(ParamArray p As String()) ~~~~~~~~~~~~~~~~~~~~~~~~ BC30002: Type 'System.String' is not defined. Public Sub S(ParamArray p As String()) ~~~~~~ </errors>) End Sub <WorkItem(541066, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541066")> <Fact()> Public Sub DefaultPropertyBindingCheckForAttributeConstructor() Dim compilation1 = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation name="DefaultPropertyBindingCheckForAttributeConstructor"> <file name="a.vb"> Public Class C1 Public Default Property P(prop As String) Get Return Nothing End Get Set End Set End Property End Class </file> </compilation>, Enumerable.Empty(Of MetadataReference)()) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC30002: Type 'System.Void' is not defined. Public Class C1 ~~~~~~~~~~~~~~~~ BC31091: Import of type 'Object' from assembly or module 'DefaultPropertyBindingCheckForAttributeConstructor.dll' failed. Public Class C1 ~~ BC35000: Requested operation is not available because the runtime library function 'System.Reflection.DefaultMemberAttribute..ctor' is not defined. Public Default Property P(prop As String) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30002: Type 'System.Object' is not defined. Public Default Property P(prop As String) ~ BC30002: Type 'System.String' is not defined. Public Default Property P(prop As String) ~~~~~~ BC30002: Type 'System.Void' is not defined. Set ~~~ </errors>) End Sub <WorkItem(541066, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541066")> <Fact()> Public Sub ConstBindingCheckForDateTimeConstantConstructor() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="DefaultPropertyBindingCheckForAttributeConstructor"> <file name="a.vb"> Imports System Public Class C1 Const DT1 As DateTime = #01/01/2000# Const DT2 = #01/01/2000# End Class </file> <file name="b.vb"> Namespace System.Runtime.CompilerServices Public Class DateTimeConstantAttribute Public Sub New(a As String) End Sub End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC35000: Requested operation is not available because the runtime library function 'System.Runtime.CompilerServices.DateTimeConstantAttribute..ctor' is not defined. Const DT1 As DateTime = #01/01/2000# ~~~~~~~~~~~~~~ BC35000: Requested operation is not available because the runtime library function 'System.Runtime.CompilerServices.DateTimeConstantAttribute..ctor' is not defined. Const DT2 = #01/01/2000# ~~~~~~~~~~~~~~ </errors>) End Sub <WorkItem(541066, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541066")> <Fact()> Public Sub ConstBindingCheckForDecimalConstantConstructor() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="DefaultPropertyBindingCheckForAttributeConstructor"> <file name="a.vb"> Imports System Public Class C1 Const DT1 As Decimal = 12d Const DT2 = 12d End Class </file> <file name="b.vb"> Namespace System.Runtime.CompilerServices Public Class DecimalConstantAttribute Public Sub New(a As String) End Sub End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC35000: Requested operation is not available because the runtime library function 'System.Runtime.CompilerServices.DecimalConstantAttribute..ctor' is not defined. Const DT1 As Decimal = 12d ~~~~~ BC35000: Requested operation is not available because the runtime library function 'System.Runtime.CompilerServices.DecimalConstantAttribute..ctor' is not defined. Const DT2 = 12d ~~~~~ </errors>) End Sub <WorkItem(541066, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541066")> <Fact()> Public Sub SynthesizedInstanceConstructorBinding() Dim compilation1 = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation name="SynthesizedInstanceConstructorBinding"> <file name="a.vb"> Public Class C1 End Class </file> </compilation>, Enumerable.Empty(Of MetadataReference)()) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC30002: Type 'System.Void' is not defined. Public Class C1 ~~~~~~~~~~~~~~~~ BC31091: Import of type 'Object' from assembly or module 'SynthesizedInstanceConstructorBinding.dll' failed. Public Class C1 ~~ </errors>) End Sub <WorkItem(541066, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541066")> <Fact()> Public Sub SynthesizedSharedConstructorBinding() Dim compilation1 = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation name="SynthesizedInstanceConstructorBinding"> <file name="a.vb"> Public Class C1 Const DA As DateTime = #1/1/1# End Class </file> </compilation>, Enumerable.Empty(Of MetadataReference)()) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC30002: Type 'System.Void' is not defined. Public Class C1 ~~~~~~~~~~~~~~~~ BC31091: Import of type 'Object' from assembly or module 'SynthesizedInstanceConstructorBinding.dll' failed. Public Class C1 ~~ BC30002: Type 'DateTime' is not defined. Const DA As DateTime = #1/1/1# ~~~~~~~~ BC31091: Import of type 'Object' from assembly or module 'SynthesizedInstanceConstructorBinding.dll' failed. Const DA As DateTime = #1/1/1# ~~~~~~~~ BC30002: Type 'System.DateTime' is not defined. Const DA As DateTime = #1/1/1# ~~~~~~~ </errors>) End Sub <WorkItem(541066, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541066")> <Fact()> Public Sub EnumWithoutMscorReference() Dim compilation1 = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation name="EnumWithoutMscorReference"> <file name="a.vb"> Enum E A End Enum </file> </compilation>, Enumerable.Empty(Of MetadataReference)()) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC30002: Type 'System.Void' is not defined. Enum E ~~~~~~~ BC30002: Type 'System.Int32' is not defined. Enum E ~ BC31091: Import of type '[Enum]' from assembly or module 'EnumWithoutMscorReference.dll' failed. Enum E ~ </errors>) End Sub <WorkItem(541468, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541468")> <Fact()> Public Sub TypeUsedViaAlias01() Dim compilation1 = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation name="TypeUsedViaAlias01"> <file name="a.vb"> Imports DnT = Microsoft.VisualBasic.DateAndTime Class c Sub S0() Dim a = DnT.DateString End Sub End Class </file> </compilation>, {MsvbRef}) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors><![CDATA[ BC30002: Type 'System.Void' is not defined. Class c ~~~~~~~~ BC30652: Reference required to assembly '<Missing Core Assembly>, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' containing the type 'Object'. Add one to your project. Class c ~ BC30002: Type 'System.Void' is not defined. Sub S0() ~~~~~~~~~ BC30002: Type 'System.Object' is not defined. Dim a = DnT.DateString ~ BC30652: Reference required to assembly '<Missing Core Assembly>, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' containing the type 'Object'. Add one to your project. Dim a = DnT.DateString ~~~ BC30652: Reference required to assembly '<Missing Core Assembly>, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' containing the type 'String'. Add one to your project. Dim a = DnT.DateString ~~~~~~~~~~~~~~ BC30652: Reference required to assembly 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' containing the type '[Object]'. Add one to your project. Dim a = DnT.DateString ~~~~~~~~~~~~~~ ]]></errors>) End Sub <WorkItem(541468, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541468")> <Fact()> Public Sub TypeUsedViaAlias02() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndReferences( <compilation name="TypeUsedViaAlias02"> <file name="a.vb"> Imports MyClass1 = Class1 Class c Dim _myclass As MyClass1 = Nothing End Class </file> </compilation>, {TestReferences.SymbolsTests.NoPia.NoPIAGenericsAsm1}) compilation1.AssertTheseDiagnostics( <errors> BC36924: Type 'List(Of FooStruct)' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type. Dim _myclass As MyClass1 = Nothing ~~~~~~~~ </errors>) End Sub <WorkItem(541468, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541468")> <Fact()> Public Sub TypeUsedViaAlias03() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndReferences( <compilation name="TypeUsedViaAlias03"> <file name="a.vb"> Imports MyClass1 = Class1 Class c Sub S0() Dim _myclass = MyClass1.Class1Foo End Sub End Class </file> </compilation>, {TestReferences.SymbolsTests.NoPia.NoPIAGenericsAsm1}) compilation1.AssertTheseDiagnostics( <errors> BC36924: Type 'List(Of FooStruct)' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type. Dim _myclass = MyClass1.Class1Foo ~~~~~~~~ BC36924: Type 'List(Of FooStruct)' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type. Dim _myclass = MyClass1.Class1Foo ~~~~~~~~~~~~~~~~~~ </errors>) End Sub <WorkItem(541468, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541468")> <Fact()> Public Sub TypeUsedViaAlias04() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndReferences( <compilation name="TypeUsedViaAlias04"> <file name="a.vb"> Imports MyClass1 = Class1 Class c Sub S0() Dim _myclass = directcast(nothing, MyClass1) End Sub End Class </file> </compilation>, {TestReferences.SymbolsTests.NoPia.NoPIAGenericsAsm1}) compilation1.AssertTheseDiagnostics( <errors> BC36924: Type 'List(Of FooStruct)' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type. Dim _myclass = directcast(nothing, MyClass1) ~~~~~~~~ </errors>) End Sub <Fact()> Public Sub Bug8522() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ArrayInitNoType"> <file name="a.vb"> Imports System Class A Sub New(x As Action) End Sub Public Const X As Integer = 0 End Class Class C Inherits Attribute Sub New(x As Integer) End Sub End Class Module M Friend Const main As Object=Main Sub Main End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30500: Constant 'main' cannot depend on its own value. Friend Const main As Object=Main ~~~~ BC30260: 'Main' is already declared as 'Friend Const main As Object' in this module. Sub Main ~~~~ </expected>) End Sub <WorkItem(542596, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542596")> <Fact()> Public Sub RegularArgumentAfterNamed() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="RegularArgumentAfterNamed"> <file name="a.vb"> Module Module1 Sub M1(x As Integer, y As Integer) End Sub Sub M1(x As Integer, y As Long) End Sub Sub M2(x As Integer, y As Integer) End Sub Sub Main() M1(x:=2, 3) 'BIND:"M1(x:=2, 3)" M2(x:=2, 3) End Sub End Module </file> </compilation>, parseOptions:=TestOptions.Regular.WithLanguageVersion(LanguageVersion.VisualBasic15)) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30241: Named argument expected. Please use language version 15.5 or greater to use non-trailing named arguments. M1(x:=2, 3) 'BIND:"M1(x:=2, 3)" ~ BC30241: Named argument expected. Please use language version 15.5 or greater to use non-trailing named arguments. M2(x:=2, 3) ~ </expected>) End Sub <Fact()> Public Sub EventMissingName() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="EventMissingName"> <file name="a.vb"> Imports System Imports System.Collections.Generic Module Program Event Sub Main(args As String()) End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC30203: Identifier expected. Event ~ </errors>) End Sub <Fact()> Public Sub EventClashSynthetic() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="EventClashSynthetic"> <file name="a.vb"> Imports System Imports System.Collections.Generic Module Program Event E() Dim EEvent As Integer Sub Main(args As String()) End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC31060: event 'E' implicitly defines 'EEvent', which conflicts with a member of the same name in module 'Program'. Event E() ~ </errors>) End Sub <Fact()> Public Sub EventClashSyntheticDelegate() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="EventClashSyntheticDelegate"> <file name="a.vb"> Imports System Imports System.Collections.Generic Module Program Event E() Dim EEventHandler As Integer Sub Main(args As String()) End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC31060: event 'E' implicitly defines 'EEventHandler', which conflicts with a member of the same name in module 'Program'. Event E() ~ </errors>) End Sub <Fact()> Public Sub EventNotADelegate() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="EventNotADelegate"> <file name="a.vb"> Imports System Imports System.Collections.Generic Module Program Event E as Integer Sub Main(args As String()) End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC31044: Events declared with an 'As' clause must have a delegate type. Event E as Integer ~~~~~~~ </errors>) End Sub <Fact()> Public Sub EventParamsAndAs() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="EventParamsAndAs"> <file name="a.vb"> Imports System Imports System.Collections.Generic Module Program Event E(x as integer) as Integer Sub Main(args As String()) End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC30032: Events cannot have a return type. Event E(x as integer) as Integer ~~ </errors>) End Sub <Fact()> Public Sub EventDelegateReturns() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="EventDelegateReturns"> <file name="a.vb"> Imports System Imports System.Collections.Generic Module Program Event E as Func(of Integer) Sub Main() End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC31084: Events cannot be declared with a delegate type that has a return type. Event E as Func(of Integer) ~~~~~~~~~~~~~~~~ </errors>) End Sub <Fact()> Public Sub EventDelegateClash() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="EventDelegateClash"> <file name="a.vb"> Imports System Imports System.Collections.Generic Module Program Event E() Event E(x as integer) Sub Main() End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC30260: 'E' is already declared as 'Public Event E()' in this module. Event E(x as integer) ~ </errors>) End Sub <Fact()> Public Sub EventNameLength() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="EventNameLength"> <file name="a.vb"> Imports System Imports System.Collections.Generic Module Program Event eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee() Event eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee() Sub Main(args As String()) End Sub End Module </file> </compilation>) CompilationUtils.AssertNoDiagnostics(compilation1) CompilationUtils.AssertTheseEmitDiagnostics(compilation1, <errors> BC37220: Name 'eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeEventHandler' exceeds the maximum length allowed in metadata. Event eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee() ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors>) End Sub <Fact()> Public Sub EventTypeChar() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="EventTypeChar"> <file name="a.vb"> Imports System Imports System.Collections.Generic Module Program Event e$ Sub Main(args As String()) End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC30468: Type declaration characters are not valid in this context. Event e$ ~~ </errors>) End Sub <Fact()> Public Sub EventIllegalImplements() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="EventIllegalImplements"> <file name="a.vb"> Imports System Imports System.Collections.Generic Interface I0 Event e End Interface Interface I1 Event e Implements I0.e End Interface Class Cls1 Implements I0 Shared Event e Implements I0.e End Class Module Program Event e Implements I0.e Sub Main(args As String()) End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC30688: Events in interfaces cannot be declared 'Implements'. Event e Implements I0.e ~~~~~~~~~~ BC30149: Class 'Cls1' must implement 'Event e()' for interface 'I0'. Implements I0 ~~ BC30505: Methods or events that implement interface members cannot be declared 'Shared'. Shared Event e Implements I0.e ~~~~~~ BC31083: Members in a Module cannot implement interface members. Event e Implements I0.e ~~~~~~~~~~ </errors>) End Sub <Fact()> Public Sub CustomEventMissingAccessors() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="CustomEventMissingAccessors"> <file name="a.vb"> Option Strict On Imports System Module Program Delegate Sub del1(x As Integer, x As Integer) Custom Event eeeeeee As del1 End Event Sub Main(args As String()) AddHandler eeeeeee, Nothing RemoveHandler eeeeeee, Nothing RaiseEvent eeeeeee(1,1) End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC31130: 'AddHandler' definition missing for event 'Public Event eeeeeee As Program.del1'. Custom Event eeeeeee As del1 ~~~~~~~ BC31131: 'RemoveHandler' definition missing for event 'Public Event eeeeeee As Program.del1'. Custom Event eeeeeee As del1 ~~~~~~~ BC31132: 'RaiseEvent' definition missing for event 'Public Event eeeeeee As Program.del1'. Custom Event eeeeeee As del1 ~~~~~~~ BC31132: 'RaiseEvent' definition missing for event 'eeeeeee'. RaiseEvent eeeeeee(1,1) ~~~~~~~ </errors>) End Sub <Fact()> Public Sub CustomEventDuplicateAccessors() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="CustomEventDuplicateAccessors"> <file name="a.vb"> Option Strict On Imports System Module Program Delegate Sub del1(x As Integer, x As Integer) Custom Event eeeeeee As del1 AddHandler(value As del1) End AddHandler RemoveHandler(value As del1) End RemoveHandler RaiseEvent(x As Integer, x1 As Integer) End RaiseEvent AddHandler(value As del1) End AddHandler RemoveHandler(value As del1) End RemoveHandler RaiseEvent(x As Integer, x1 As Integer) End RaiseEvent End Event Sub Main(args As String()) AddHandler eeeeeee, Nothing RemoveHandler eeeeeee, Nothing End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC31127: 'AddHandler' is already declared. AddHandler(value As del1) ~~~~~~~~~~~~~~~~~~~~~~~~~ BC31128: 'RemoveHandler' is already declared. RemoveHandler(value As del1) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC31129: 'RaiseEvent' is already declared. RaiseEvent(x As Integer, x1 As Integer) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors>) End Sub <Fact()> Public Sub CustomEventAccessorsWrongParamNum() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="CustomEventDuplicateAccessors"> <file name="a.vb"> Option Strict On Imports System Module Program Delegate Sub del1(x As Integer, x As Integer) Custom Event eeeeeee As del1 AddHandler() End AddHandler RemoveHandler(value As del1, x As Integer) End RemoveHandler RaiseEvent(x As Integer, x1 As Integer) End RaiseEvent End Event Sub Main(args As String()) AddHandler eeeeeee, Nothing RemoveHandler eeeeeee, Nothing End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC31133: 'AddHandler' and 'RemoveHandler' methods must have exactly one parameter. AddHandler() ~~~~~~~~~~~~ BC31133: 'AddHandler' and 'RemoveHandler' methods must have exactly one parameter. RemoveHandler(value As del1, x As Integer) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors>) End Sub <Fact()> Public Sub CustomEventAccessorsWrongParamTypes() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="CustomEventDuplicateAccessors"> <file name="a.vb"> Option Strict Off Imports System Module Program Delegate Sub del1(x As Integer) Custom Event eeeeeee As del1 AddHandler(value As Action(Of Integer)) End AddHandler RemoveHandler(value) End RemoveHandler RaiseEvent(x) ' not an error (strict off) End RaiseEvent End Event Sub Main(args As String()) AddHandler eeeeeee, Nothing RemoveHandler eeeeeee, Nothing End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC31136: 'AddHandler' and 'RemoveHandler' method parameters must have the same delegate type as the containing event. AddHandler(value As Action(Of Integer)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC31136: 'AddHandler' and 'RemoveHandler' method parameters must have the same delegate type as the containing event. RemoveHandler(value) ~~~~~~~~~~~~~~~~~~~~ </errors>) End Sub <Fact()> Public Sub CustomEventAccessorsWrongParamTypes1() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="CustomEventDuplicateAccessors"> <file name="a.vb"> Option Strict Off Imports System Module Program Delegate Sub del1(x As Integer) Custom Event eeeeeee As Object AddHandler(value As Object) End AddHandler RemoveHandler(value) End RemoveHandler RaiseEvent(x) ' not an error (strict off) End RaiseEvent End Event Sub Main(args As String()) AddHandler eeeeeee, Nothing RemoveHandler eeeeeee, Nothing End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC31044: Events declared with an 'As' clause must have a delegate type. Custom Event eeeeeee As Object ~~~~~~ </errors>) End Sub <Fact()> Public Sub CustomEventAccessorsArgModifiers() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="CustomEventAccessorsArgModifiers"> <file name="a.vb"> Option Strict Off Imports System Module Program Delegate Sub del1(ByRef x As Integer) Custom Event eeeeeee As del1 AddHandler(ParamArray value() As del1) End AddHandler RemoveHandler(Optional ByRef value As del1 = Nothing) End RemoveHandler RaiseEvent(Optional ByRef x As Integer = 1) End RaiseEvent End Event Sub Main(args As String()) AddHandler eeeeeee, Nothing RemoveHandler eeeeeee, Nothing End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC31136: 'AddHandler' and 'RemoveHandler' method parameters must have the same delegate type as the containing event. AddHandler(ParamArray value() As del1) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC31138: 'AddHandler', 'RemoveHandler' and 'RaiseEvent' method parameters cannot be declared 'ParamArray'. AddHandler(ParamArray value() As del1) ~~~~~~~~~~ BC31138: 'AddHandler', 'RemoveHandler' and 'RaiseEvent' method parameters cannot be declared 'Optional'. RemoveHandler(Optional ByRef value As del1 = Nothing) ~~~~~~~~ BC31134: 'AddHandler' and 'RemoveHandler' method parameters cannot be declared 'ByRef'. RemoveHandler(Optional ByRef value As del1 = Nothing) ~~~~~ BC31138: 'AddHandler', 'RemoveHandler' and 'RaiseEvent' method parameters cannot be declared 'Optional'. RaiseEvent(Optional ByRef x As Integer = 1) ~~~~~~~~ </errors>) End Sub <Fact()> Public Sub CustomEventRaiseRelaxed1() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="CustomEventRaiseRelaxed1"> <file name="a.vb"> Option Strict On Imports System Module Program Delegate Sub del1(x As Integer) Custom Event eeeeeee1 As del1 AddHandler(value As del1) End AddHandler RemoveHandler(value As del1) End RemoveHandler RaiseEvent(x As Short) ' error End RaiseEvent End Event Custom Event eeeeeee2 As del1 AddHandler(value As del1) End AddHandler RemoveHandler(value As del1) End RemoveHandler RaiseEvent(x As Integer, y As Integer) ' error End RaiseEvent End Event Custom Event eeeeeee3 As del1 AddHandler(value As del1) End AddHandler RemoveHandler(value As del1) End RemoveHandler RaiseEvent(x As Long) 'valid End RaiseEvent End Event Custom Event eeeeeee4 As del1 AddHandler(value As del1) End AddHandler RemoveHandler(value As del1) End RemoveHandler RaiseEvent() ' valid End RaiseEvent End Event Sub Main(args As String()) AddHandler eeeeeee1, Nothing RemoveHandler eeeeeee1, Nothing End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC31137: 'RaiseEvent' method must have the same signature as the containing event's delegate type 'Program.del1'. RaiseEvent(x As Short) ~~~~~~~~~~~~~~~~~~~~~~ BC31137: 'RaiseEvent' method must have the same signature as the containing event's delegate type 'Program.del1'. RaiseEvent(x As Integer, y As Integer) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors>) End Sub <Fact()> Public Sub CustomEventRaiseRelaxed2() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="CustomEventRaiseRelaxed3"> <file name="a.vb"> Option Strict Off Imports System Module Program Delegate Sub del1(x As Integer) Custom Event eeeeeee1 As del1 AddHandler(value As del1) End AddHandler RemoveHandler(value As del1) End RemoveHandler RaiseEvent(x As Short) ' valid End RaiseEvent End Event Custom Event eeeeeee2 As del1 AddHandler(value As del1) End AddHandler RemoveHandler(value As del1) End RemoveHandler RaiseEvent(x As Integer, y As Integer) ' error End RaiseEvent End Event Custom Event eeeeeee3 As del1 AddHandler(value As del1) End AddHandler RemoveHandler(value As del1) End RemoveHandler RaiseEvent(x As Long) 'valid End RaiseEvent End Event Custom Event eeeeeee4 As del1 AddHandler(value As del1) End AddHandler RemoveHandler(value As del1) End RemoveHandler RaiseEvent() ' valid End RaiseEvent End Event Sub Main(args As String()) AddHandler eeeeeee1, Nothing RemoveHandler eeeeeee1, Nothing End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC31137: 'RaiseEvent' method must have the same signature as the containing event's delegate type 'Program.del1'. RaiseEvent(x As Integer, y As Integer) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors>) End Sub <Fact()> Public Sub RaiseEventNotEvent() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="RaiseEventNotEvent"> <file name="a.vb"> Imports System Module Program Delegate Sub del1() Dim o As del1 Sub Main(args As String()) RaiseEvent o() RaiseEvent Blah RaiseEvent RaiseEvent RaiseEvent End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC30676: 'o' is not an event of 'Program'. RaiseEvent o() ~ BC30451: 'Blah' is not declared. It may be inaccessible due to its protection level. RaiseEvent Blah ~~~~ BC30203: Identifier expected. RaiseEvent ~ BC30451: 'RaiseEvent' is not declared. It may be inaccessible due to its protection level. RaiseEvent RaiseEvent ~~~~~~~~~~ </errors>) End Sub <Fact()> Public Sub RaiseEventInBase() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="RaiseEventInBase"> <file name="a.vb"> Imports System Module Program Delegate Sub del1() Dim o As del1 Sub Main(args As String()) End Sub Class cls1 Public Shared Event EFieldLike As Action Public Shared Custom Event ECustom As Action AddHandler(value As Action) End AddHandler RemoveHandler(value As Action) End RemoveHandler RaiseEvent() End RaiseEvent End Event Class cls2 Inherits cls1 Sub Test() ' valid as in Dev10 RaiseEvent EFieldLike() ' error RaiseEvent E1() End Sub End Class End Class End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC30451: 'E1' is not declared. It may be inaccessible due to its protection level. RaiseEvent E1() ~~ </errors>) End Sub <Fact()> Public Sub RaiseEventStrictOn() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="RaiseEventStrictOn"> <file name="a.vb"> Option Strict On Imports System Module Program Delegate Sub del1(ByRef x As Object) Event E As del1 Sub Main() Dim v As String RaiseEvent E(v) End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC32029: Option Strict On disallows narrowing from type 'Object' to type 'String' in copying the value of 'ByRef' parameter 'x' back to the matching argument. RaiseEvent E(v) ~ BC42104: Variable 'v' is used before it has been assigned a value. A null reference exception could result at runtime. RaiseEvent E(v) ~ </errors>) End Sub <Fact()> Public Sub RaiseEventStrictOff() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="RaiseEventStrictOff"> <file name="a.vb"> Option Strict Off Imports System Module Program Delegate Sub del1(ByRef x As Object) Event E As del1 Sub Main() Dim v As String RaiseEvent E(v) End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC42030: Variable 'v' is passed by reference before it has been assigned a value. A null reference exception could result at runtime. RaiseEvent E(v) ~ </errors>) End Sub <Fact()> Public Sub ImplementNotValidDelegate() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ImplementDifferentDelegate"> <file name="a.vb"> Imports System Module Program Interface i1 Delegate Sub del1() Delegate Sub del2(x As Integer) Delegate Sub del3(x() As Integer) Event E1 As del1 Event E2 As del2 Event E3 As del3 End Interface Class cls1 Implements i1 Private Event E1 As Integer Implements i1.E1 Private Event E2 As Func(Of Integer) Implements i1.E2 Private Event E3 As Implements i1.E3 Private Event E4(ParamArray x() As Integer) Implements i1.E3 End Class Sub Main() End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC30149: Class 'cls1' must implement 'Event E2 As Program.i1.del2' for interface 'i1'. Implements i1 ~~ BC31044: Events declared with an 'As' clause must have a delegate type. Private Event E1 As Integer Implements i1.E1 ~~~~~~~ BC31423: Event 'Private Event E1 As Integer' cannot implement event 'Event E1 As Program.i1.del1' on interface 'Program.i1' because their delegate types 'Integer' and 'Program.i1.del1' do not match. Private Event E1 As Integer Implements i1.E1 ~~~~~ BC31084: Events cannot be declared with a delegate type that has a return type. Private Event E2 As Func(Of Integer) Implements i1.E2 ~~~~~~~~~~~~~~~~ BC30401: 'E2' cannot implement 'E2' because there is no matching event on interface 'i1'. Private Event E2 As Func(Of Integer) Implements i1.E2 ~~~~~ BC30180: Keyword does not name a type. Private Event E3 As Implements i1.E3 ~ BC31044: Events declared with an 'As' clause must have a delegate type. Private Event E3 As Implements i1.E3 ~ BC33009: 'Event' parameters cannot be declared 'ParamArray'. Private Event E4(ParamArray x() As Integer) Implements i1.E3 ~~~~~~~~~~ </errors>) End Sub <Fact()> Public Sub ImplementDifferentDelegate() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ImplementDifferentDelegate"> <file name="a.vb"> Imports System Module Program Interface i1 Delegate Sub del1() Delegate Sub del2(x As Integer) Delegate Sub del3(ByRef x As Integer) Event E1 As del1 Event E2 As del2 Event E3 As del3 End Interface Class cls1 Implements i1 Private Event E1 As action Implements i1.E1 Private Event E2 As action Implements i1.E2 Private Event E3 As i1.del2 Implements i1.E3 End Class Sub Main() End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC30149: Class 'cls1' must implement 'Event E2 As Program.i1.del2' for interface 'i1'. Implements i1 ~~ BC30149: Class 'cls1' must implement 'Event E3 As Program.i1.del3' for interface 'i1'. Implements i1 ~~ BC31423: Event 'Private Event E1 As Action' cannot implement event 'Event E1 As Program.i1.del1' on interface 'Program.i1' because their delegate types 'Action' and 'Program.i1.del1' do not match. Private Event E1 As action Implements i1.E1 ~~~~~ BC30401: 'E2' cannot implement 'E2' because there is no matching event on interface 'i1'. Private Event E2 As action Implements i1.E2 ~~~~~ BC30401: 'E3' cannot implement 'E3' because there is no matching event on interface 'i1'. Private Event E3 As i1.del2 Implements i1.E3 ~~~~~ </errors>) End Sub <Fact()> Public Sub ImplementDifferentSignature() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ImplementDifferentDelegate"> <file name="a.vb"> Imports System Module Program Interface i1 Delegate Sub del1() Delegate Sub del2(x As Integer) Delegate Sub del3(ByRef x As Integer) Event E1 As del1 Event E2 As del2 Event E3 As del3 End Interface Class cls1 Implements i1 Private Event E1(x As Integer) Implements i1.E1 Private Event E2() Implements i1.E2 Private Event E3(x As Integer) Implements i1.E3 End Class Sub Main() End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC30149: Class 'cls1' must implement 'Event E1 As Program.i1.del1' for interface 'i1'. Implements i1 ~~ BC30149: Class 'cls1' must implement 'Event E2 As Program.i1.del2' for interface 'i1'. Implements i1 ~~ BC30149: Class 'cls1' must implement 'Event E3 As Program.i1.del3' for interface 'i1'. Implements i1 ~~ BC30401: 'E1' cannot implement 'E1' because there is no matching event on interface 'i1'. Private Event E1(x As Integer) Implements i1.E1 ~~~~~ BC30401: 'E2' cannot implement 'E2' because there is no matching event on interface 'i1'. Private Event E2() Implements i1.E2 ~~~~~ BC30401: 'E3' cannot implement 'E3' because there is no matching event on interface 'i1'. Private Event E3(x As Integer) Implements i1.E3 ~~~~~ </errors>) End Sub <Fact()> Public Sub ImplementConflicting() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ImplementConflicting"> <file name="a.vb"> Imports System Module Program Interface i1 Delegate Sub del1() Delegate Sub del2(x As Integer) Event E1 As del1 Event E2 As del2 Event E1a As del2 Event E2a As Action(Of Integer) End Interface Class cls1 Implements i1 Private Event E1 As i1.del1 Implements i1.E1, i1.E2 Private Event E2(x As Integer) Implements i1.E1a, i1.E2a End Class Sub Main() End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC30149: Class 'cls1' must implement 'Event E2 As Program.i1.del2' for interface 'i1'. Implements i1 ~~ BC30401: 'E1' cannot implement 'E2' because there is no matching event on interface 'i1'. Private Event E1 As i1.del1 Implements i1.E1, i1.E2 ~~~~~ BC31407: Event 'Private Event E2 As Program.i1.del2' cannot implement event 'Program.i1.Event E2a As Action(Of Integer)' because its delegate type does not match the delegate type of another event implemented by 'Private Event E2 As Program.i1.del2'. Private Event E2(x As Integer) Implements i1.E1a, i1.E2a ~~~~~~ </errors>) End Sub <Fact()> Public Sub ImplementTwice() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ImplementTwice"> <file name="a.vb"> Imports System Module Program Interface i1 Delegate Sub del1() Delegate Sub del2(x As Integer) Event E1 As del1 Event E2 As del2 End Interface Class cls1 Implements i1 Private Event E1 As i1.del1 Implements i1.E1, i1.E1 Private Event E2() Implements i1.E1 End Class Sub Main() End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC30149: Class 'cls1' must implement 'Event E2 As Program.i1.del2' for interface 'i1'. Implements i1 ~~ BC30583: 'i1.E1' cannot be implemented more than once. Private Event E1 As i1.del1 Implements i1.E1, i1.E1 ~~~~~ BC30583: 'i1.E1' cannot be implemented more than once. Private Event E2() Implements i1.E1 ~~~~~ </errors>) End Sub <Fact()> Public Sub ImplementIncomplete() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ImplementConflicting"> <file name="a.vb"> Imports System Module Program Interface i1 Delegate Sub del1() Delegate Sub del2(x As Integer) Event E1 As del1 Event E2 As del2 End Interface Class cls1 Implements i1 Private Event E1 As i1.del1 Implements Private Event E2() Implements i1 Private Event E3 Implements i1. Private Event E4 Implements i1.Blah End Class Sub Main() End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC30149: Class 'cls1' must implement 'Event E1 As Program.i1.del1' for interface 'i1'. Implements i1 ~~ BC30149: Class 'cls1' must implement 'Event E2 As Program.i1.del2' for interface 'i1'. Implements i1 ~~ BC30203: Identifier expected. Private Event E1 As i1.del1 Implements ~ BC30287: '.' expected. Private Event E1 As i1.del1 Implements ~ BC30287: '.' expected. Private Event E2() Implements i1 ~~ BC30401: 'E2' cannot implement '' because there is no matching event on interface 'i1'. Private Event E2() Implements i1 ~~ BC30401: 'E3' cannot implement '' because there is no matching event on interface 'i1'. Private Event E3 Implements i1. ~~~ BC30203: Identifier expected. Private Event E3 Implements i1. ~ BC30401: 'E4' cannot implement 'Blah' because there is no matching event on interface 'i1'. Private Event E4 Implements i1.Blah ~~~~~~~ </errors>) End Sub <WorkItem(543095, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543095")> <Fact()> Public Sub SelectCase_CaseStatementError() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="SelectCase_CaseStatementError"> <file name="a.vb"> Imports System Module Program Sub Main(args As String()) Dim x As New myclass1 Select x Ca End Sub End Module Structure myclass1 Implements IDisposable Public Sub dispose() Implements IDisposable.Dispose End Sub End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30095: 'Select Case' must end with a matching 'End Select'. Select x ~~~~~~~~ BC30058: Statements and labels are not valid between 'Select Case' and first 'Case'. Ca ~~ BC30451: 'Ca' is not declared. It may be inaccessible due to its protection level. Ca ~~ </expected>) End Sub <WorkItem(543095, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543095")> <Fact()> Public Sub SelectCase_CaseStatementError_02() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="SelectCase_CaseStatementError"> <file name="a.vb"> Imports System Module Program Sub Main(args As String()) Dim x As New myclass1 Select x Case End Select Select x Case y End Select End Sub End Module Structure myclass1 Implements IDisposable Public Sub dispose() Implements IDisposable.Dispose End Sub End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30201: Expression expected. Case ~ BC30451: 'y' is not declared. It may be inaccessible due to its protection level. Case y ~ </expected>) End Sub <WorkItem(543095, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543095")> <Fact()> Public Sub SelectCase() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="SelectCase"> <file name="a.vb"> Imports System Module Program Sub Main(args As String()) Dim x As New myclass1 Select x ca End Select End Sub End Module Structure myclass1 Implements IDisposable Public Sub dispose() Implements IDisposable.Dispose End Sub End Structure </file> </compilation>) VerifyDiagnostics(compilation, Diagnostic(ERRID.ERR_ExpectedCase, "ca"), Diagnostic(ERRID.ERR_NameNotDeclared1, "ca").WithArguments("ca")) End Sub <WorkItem(543300, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543300")> <Fact()> Public Sub BoundConversion() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="BoundConversion"> <file name="a.vb"> Imports System.Linq Class C1 sharSub MAIN() Dim lists = foo() lists.Where(Function(ByVal item) SyncLock item End SyncLock Return item.ToString() = "" End Function).ToList() End Sub Shared Function foo() As List(Of myattribute1) Return Nothing End Function End Class </file> </compilation>) VerifyDiagnostics(compilation, Diagnostic(ERRID.ERR_ExpectedSpecifier, "MAIN()"), Diagnostic(ERRID.ERR_ExpectedDeclaration, "sharSub"), Diagnostic(ERRID.ERR_ExpectedDeclaration, "lists"), Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "SyncLock item"), Diagnostic(ERRID.ERR_EndSyncLockNoSyncLock, "End SyncLock"), Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Return item.ToString() = """""), Diagnostic(ERRID.ERR_InvalidEndFunction, "End Function"), Diagnostic(ERRID.ERR_ExpectedEOS, ")"), Diagnostic(ERRID.ERR_InvalidEndSub, "End Sub"), Diagnostic(ERRID.WRN_UndefinedOrEmptyNamespaceOrClass1, "System.Linq").WithArguments("System.Linq"), Diagnostic(ERRID.ERR_UndefinedType1, "myattribute1").WithArguments("myattribute1"), Diagnostic(ERRID.ERR_UndefinedType1, "List(Of myattribute1)").WithArguments("List"), Diagnostic(ERRID.HDN_UnusedImportStatement, "Imports System.Linq")) End Sub <WorkItem(543300, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543300")> <Fact()> Public Sub BoundConversion_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="BoundConversion"> <file name="a.vb"> "".Where(Function(item) Return lab1 End Function: Return item.ToString() = "" End Function).ToList() End Sub </file> </compilation>, {Net40.SystemCore}) VerifyDiagnostics(compilation, Diagnostic(ERRID.ERR_Syntax, """"""), Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Return lab1"), Diagnostic(ERRID.ERR_InvalidEndFunction, "End Function"), Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Return item.ToString() = """""), Diagnostic(ERRID.ERR_InvalidEndFunction, "End Function"), Diagnostic(ERRID.ERR_ExpectedEOS, ")"), Diagnostic(ERRID.ERR_InvalidEndSub, "End Sub")) End Sub <WorkItem(543319, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543319")> <Fact()> Public Sub CaseOnlyAppearInSelect() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Module M1 Sub Main() Select "" Case "a" If (True) Case "b" GoTo lab1 End If End Select lab1: End Sub End Module ]]></file> </compilation>) VerifyDiagnostics(compilation, Diagnostic(ERRID.ERR_CaseNoSelect, "Case ""b""")) End Sub <WorkItem(543319, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543319")> <Fact()> Public Sub CaseOnlyAppearInSelect_1() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Class Test Public Shared Sub Main() Select Case "" Case "c" Try Case "a" Catch ex As Exception Case "b" End Try End Select End Sub End Class ]]></file> </compilation>) VerifyDiagnostics(compilation, Diagnostic(ERRID.ERR_CaseNoSelect, "Case ""a"""), Diagnostic(ERRID.ERR_CaseNoSelect, "Case ""b""")) End Sub <WorkItem(543333, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543333")> <Fact()> Public Sub BindReturn() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Class Program Shared Main() Return Nothing End sub End Class ]]></file> </compilation>) VerifyDiagnostics(compilation, Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Return Nothing"), Diagnostic(ERRID.ERR_InvalidEndSub, "End sub")) End Sub <WorkItem(543746, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543746")> <Fact()> Public Sub LocalConstAssignedToSelf() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Module Program Sub Main() Const X = X End Sub End Module ]]></file> </compilation>) VerifyDiagnostics(compilation, Diagnostic(ERRID.ERR_CircularEvaluation1, "X").WithArguments("X"), Diagnostic(ERRID.WRN_DefAsgUseNullRef, "X").WithArguments("X")) End Sub <WorkItem(543746, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543746")> <Fact> Public Sub LocalConstCycle() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Module Program Sub Main() Const Y = Z Const Z = Y Const a = c Const b = a Const c = b End Sub End Module ]]></file> </compilation>) VerifyDiagnostics(compilation, Diagnostic(ERRID.ERR_UseOfLocalBeforeDeclaration1, "Z").WithArguments("Z"), Diagnostic(ERRID.ERR_UseOfLocalBeforeDeclaration1, "c").WithArguments("c")) End Sub <WorkItem(543823, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543823")> <Fact()> Public Sub LocalConstCycle02() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Module Program Sub Main() Const X = 3 + Z Const Y = 2 + X Const Z = 1 + Y End Sub End Module ]]></file> </compilation>) ' Dev10: Diagnostic(ERRID.ERR_NameNotDeclared1, "Z").WithArguments("Z")) VerifyDiagnostics(compilation, Diagnostic(ERRID.ERR_UseOfLocalBeforeDeclaration1, "Z").WithArguments("Z"), Diagnostic(ERRID.ERR_RequiredConstConversion2, "2").WithArguments("Integer", "Object"), Diagnostic(ERRID.ERR_RequiredConstConversion2, "1").WithArguments("Integer", "Object")) End Sub <WorkItem(543821, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543821")> <Fact()> Public Sub LocalConstCycle03() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Module Program Sub Main() Const X = Y Const Y = Y + X Const Z = Y + Z End Sub End Module ]]></file> </compilation>) VerifyDiagnostics(compilation, Diagnostic(ERRID.ERR_UseOfLocalBeforeDeclaration1, "Y").WithArguments("Y"), Diagnostic(ERRID.ERR_CircularEvaluation1, "Y").WithArguments("Y"), Diagnostic(ERRID.ERR_CircularEvaluation1, "Z").WithArguments("Z"), Diagnostic(ERRID.WRN_DefAsgUseNullRef, "Y").WithArguments("Y"), Diagnostic(ERRID.WRN_DefAsgUseNullRef, "Z").WithArguments("Z")) End Sub <WorkItem(543755, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543755")> <Fact()> Public Sub BracketedIdentifierMissingEndBracket() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Module Program Sub Main() Dim [foo as integer = 23 : Dim [goo As Char = "d"c End Sub End Module ]]></file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30203: Identifier expected. Dim [foo as integer = 23 : Dim [goo As Char = "d"c ~ BC30034: Bracketed identifier is missing closing ']'. Dim [foo as integer = 23 : Dim [goo As Char = "d"c ~~~~ BC30203: Identifier expected. Dim [foo as integer = 23 : Dim [goo As Char = "d"c ~ BC30034: Bracketed identifier is missing closing ']'. Dim [foo as integer = 23 : Dim [goo As Char = "d"c ~~~~ </expected>) End Sub <Fact(), WorkItem(536245, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536245"), WorkItem(543652, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543652")> Public Sub BC30192ERR_ParamArrayMustBeLast() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Class C1 Sub foo(byval Paramarray pArr1() as Integer, byval paramarray pArr2 as integer) End Sub End Class ]]> </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30192: End of parameter list expected. Cannot define parameters after a paramarray parameter. Sub foo(byval Paramarray pArr1() as Integer, byval paramarray pArr2 as integer) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30050: ParamArray parameter must be an array. Sub foo(byval Paramarray pArr1() as Integer, byval paramarray pArr2 as integer) ~~~~~ </expected>) End Sub <WorkItem(544501, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544501")> <Fact()> Public Sub TestCombinePrivateAndNotOverridable() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Module Program Sub Main(args As String()) c1.Bar() End Sub End Module Class c1 Partial Private Sub foo(ByRef x() As Integer) End Sub End Class </file> <file name="b.vb"> Imports System Partial Class c1 Private NotOverridable Sub Foo(ByRef x() As Integer) Console.Write("Success") End Sub Shared Sub Bar() Dim x = New c1() x.foo({1}) End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC31408: 'Private' and 'NotOverridable' cannot be combined. Private NotOverridable Sub Foo(ByRef x() As Integer) ~~~~~~~~~~~~~~ </expected>) End Sub <WorkItem(546098, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546098")> <Fact()> Public Sub InstanceMemberOfStructInsideSharedLambda() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Module Test Public Structure S1 Dim a As Integer Public Shared c As Action(Of Integer) = Sub(c) a = 2 End Sub End Structure End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30369: Cannot refer to an instance member of a class from within a shared method or shared member initializer without an explicit instance of the class. a = 2 ~ </expected>) End Sub <WorkItem(546053, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546053")> <Fact()> Public Sub EventHandlerBindingError() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module Test Sub lbHnd() End Sub Dim oc As Object Sub Main() AddHandler oc.evt, AddressOf lbHnd End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30676: 'evt' is not an event of 'Object'. AddHandler oc.evt, AddressOf lbHnd ~~~ </expected>) End Sub <WorkItem(530912, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530912")> <Fact()> Public Sub Bug_17183_LateBinding_Object() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Class classes Public Property P As Object Get Return Nothing End Get Set End Set End Property End Class Module Module1 Sub Main() Dim h As classes = Nothing Dim x = h.P(0) End Sub End Module ]]> </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30574: Option Strict On disallows late binding. Dim x = h.P(0) ~ </expected>) End Sub <WorkItem(530912, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530912")> <Fact()> Public Sub Bug_17183_LateBinding_Array() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports System Class classes Public Property P As Array Get Return Nothing End Get Set End Set End Property End Class Module Module1 Sub Main() Dim h As classes = Nothing Dim x = h.P(0) End Sub End Module ]]> </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30574: Option Strict On disallows late binding. Dim x = h.P(0) ~ </expected>) End Sub <WorkItem(530912, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530912")> <Fact()> Public Sub Bug_17183_LateBinding_COM() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports System.Runtime.InteropServices <TypeLibTypeAttribute(TypeLibTypeFlags.FDispatchable)> Interface inter Default Property sss(x As Integer) As Integer End Interface Class classes Public Property P As inter Get Return Nothing End Get Set End Set End Property End Class Module Module1 Sub Main() Dim h As classes = Nothing Dim x = h.P(0) 'No Late Binding here Dim y = h.P.Member 'Late Binding here - error End Sub End Module ]]> </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30574: Option Strict On disallows late binding. Dim y = h.P.Member 'Late Binding here - error ~~~~~~~~~~ </expected>) End Sub <WorkItem(531400, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531400")> <Fact()> Public Sub Bug18070() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module Program Event E() Sub Main() End Sub Sub Main1() RaiseEvent E() ' 1 Static E As Integer = 1 AddHandler E, AddressOf Main ' 1 RemoveHandler E, AddressOf Main ' 1 End Sub Sub Main2() RaiseEvent E() ' 2 Dim E As Integer = 1 AddHandler E, AddressOf Main ' 2 RemoveHandler E, AddressOf Main ' 2 End Sub Sub Main3(E As Integer) RaiseEvent E() ' 3 AddHandler E, AddressOf Main ' 3 RemoveHandler E, AddressOf Main ' 3 End Sub End Module </file> </compilation>) CompileAndVerify(compilation) End Sub <Fact()> Public Sub Bug547318() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> End Set End Property End Class Font) _FONT = Value Set(ByVal Value As System.Drawing. 'BIND:"Drawing" </file> </compilation>) Dim node As ExpressionSyntax = FindBindingText(Of ExpressionSyntax)(compilation, "a.vb") Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim bindInfo1 As SemanticInfoSummary = semanticModel.GetSemanticInfoSummary(DirectCast(node, ExpressionSyntax)) End Sub <WorkItem(566606, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/566606")> <Fact()> Public Sub BrokenFor() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> </file> </compilation>) Dim text = <![CDATA[ Imports System 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 ]]> compilation = compilation.AddSyntaxTrees(Parse(text)) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30035: Syntax error. For {|stmt1:$$i|} = 1 To 20 ~ BC30035: Syntax error. For {|stmt1:$$i|} = 1 To 20 ~ BC30201: Expression expected. For {|stmt1:$$i|} = 1 To 20 ~ BC30249: '=' expected. For {|stmt1:$$i|} = 1 To 20 ~ BC30370: '}' expected. For {|stmt1:$$i|} = 1 To 20 ~ BC30037: Character is not valid. For {|stmt1:$$i|} = 1 To 20 ~ BC30037: Character is not valid. For {|stmt1:$$i|} = 1 To 20 ~ BC30037: Character is not valid. For {|stmt1:$$i|} = 1 To 20 ~ BC30037: Character is not valid. For {|stmt1:$$i|} = 1 To 20 ~ BC30198: ')' expected. Console.WriteLine({|stmt1:i|}) ~ BC30201: Expression expected. Console.WriteLine({|stmt1:i|}) ~ BC30370: '}' expected. Console.WriteLine({|stmt1:i|}) ~ BC30037: Character is not valid. Console.WriteLine({|stmt1:i|}) ~ BC30451: 'i' is not declared. It may be inaccessible due to its protection level. Console.WriteLine({|stmt1:i|}) ~ BC30037: Character is not valid. Console.WriteLine({|stmt1:i|}) ~ </expected>) End Sub <Fact> Public Sub ConflictsWithTypesInVBCore_EmbeddedTypes() Dim source = <compilation> <file><![CDATA[ Module Module1 Sub Main() End Sub End Module 'Partial Class on Type in Microsoft.VisualBasic Namespace Microsoft.VisualBasic Partial Class HideModuleNameAttribute Inherits Attribute Public Function ABC() As String Return "Success" End Function Public Overrides ReadOnly Property TypeId As Object Get Return "TypeID" End Get End Property End Class End Namespace ]]> </file> </compilation> Dim c = CompilationUtils.CreateEmptyCompilationWithReferences(source, references:={MscorlibRef, SystemRef, SystemCoreRef}, options:=TestOptions.ReleaseDll.WithEmbedVbCoreRuntime(True)).VerifyDiagnostics(Diagnostic(ERRID.ERR_TypeClashesWithVbCoreType4, "HideModuleNameAttribute").WithArguments("class", "HideModuleNameAttribute", "class", "HideModuleNameAttribute"), Diagnostic(ERRID.ERR_UndefinedType1, "Attribute").WithArguments("Attribute"), Diagnostic(ERRID.ERR_OverrideNotNeeded3, "TypeId").WithArguments("property", "TypeId")) End Sub <Fact()> Public Sub ERR_ExtensionMethodCannotBeLateBound_1() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="a.vb"><![CDATA[ Module Module1 Sub Main() Dim x As New Test() Dim y As Object = x x.M(y) End Sub <System.Runtime.CompilerServices.Extension> Sub M(this As Test, x As Double) End Sub End Module Class Test Sub M(x As Integer) End Sub Sub M(x As UInteger) End Sub End Class ]]></file> </compilation>, {Net40.SystemCore}, TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.Custom)) AssertTheseDiagnostics(compilation, <expected> BC36908: Late-bound extension methods are not supported. x.M(y) ~ </expected>) End Sub <Fact()> Public Sub ERR_ExtensionMethodCannotBeLateBound_2() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="a.vb"><![CDATA[ Module Module1 Sub Main() Dim x As New Test() Dim y As Object = x x.M(y) End Sub <System.Runtime.CompilerServices.Extension> Sub M(this As Test, x As Double, y as String) End Sub End Module Class Test Sub M(x As Integer) End Sub Sub M(x As UInteger) End Sub End Class ]]></file> </compilation>, {Net40.SystemCore}, TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.Custom)) AssertTheseDiagnostics(compilation, <expected> BC36908: Late-bound extension methods are not supported. x.M(y) ~ </expected>) End Sub <Fact()> Public Sub ERR_ExtensionMethodCannotBeLateBound_3() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="a.vb"><![CDATA[ Module Module1 Sub Main() Dim x As New Test() Dim y As Object = x x.M(y) End Sub <System.Runtime.CompilerServices.Extension> Sub M(this As Test, x As Double) End Sub End Module Class Test Sub M(x As UInteger) End Sub End Class ]]></file> </compilation>, {Net40.SystemCore}, TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.Custom)) AssertTheseDiagnostics(compilation, <expected> BC42016: Implicit conversion from 'Object' to 'UInteger'. x.M(y) ~ </expected>) CompileAndVerify(compilation) End Sub <Fact()> Public Sub ERR_ExtensionMethodCannotBeLateBound_4() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Linq.Expressions Imports System.Runtime.CompilerServices Imports System.Collections.Generic Module Module1 Sub Main() Dim c1 As New C1() Dim x As Object = New List(Of Integer) Try c1.fun(x) Catch e As Exception Console.WriteLine(e) End Try End Sub <Extension> Sub fun(Of X)(this As C1, ByVal a As Queue(Of X)) End Sub End Module Class C1 Sub fun(Of X)(ByVal a As List(Of X)) End Sub Sub fun(Of X)(ByVal a As Stack(Of X)) End Sub End Class ]]></file> </compilation>, {Net40.SystemCore}, TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.Custom)) AssertTheseDiagnostics(compilation, <expected> BC36908: Late-bound extension methods are not supported. c1.fun(x) ~~~ </expected>) End Sub <Fact()> Public Sub ERR_ExtensionMethodCannotBeLateBound_5() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Linq.Expressions Imports System.Runtime.CompilerServices Imports System.Collections.Generic Module Module1 Sub Main() Dim c1 As New C1() Dim x As Object = New List(Of Integer) Try c1.fun(x) Catch e As Exception Console.WriteLine(e) End Try End Sub <Extension> Sub fun(Of X)(this As C1, ByVal a As Queue(Of X)) End Sub End Module Class C1 Sub fun(Of X)(ByVal a As List(Of X)) End Sub End Class ]]></file> </compilation>, {Net40.SystemCore}, TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.Custom)) AssertTheseDiagnostics(compilation, <expected> BC36908: Late-bound extension methods are not supported. c1.fun(x) ~~~ </expected>) End Sub <WorkItem(573728, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/573728")> <Fact()> Public Sub Bug573728() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Delegate Sub D(i As Integer) Module M Sub M(o As D) o() o(1, 2) End Sub End Module ]]></file> </compilation>, TestOptions.ReleaseDll) AssertTheseDiagnostics(compilation, <expected> BC30455: Argument not specified for parameter 'i' of 'D'. o() ~ BC30057: Too many arguments to 'D'. o(1, 2) ~ </expected>) End Sub <Fact(), WorkItem(792754, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/792754")> Public Sub NameClashAcrossFiles() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Module M Sub Main() End Sub Private Test2 As Settings End Module ]]></file> <file name="b.vb"><![CDATA[ Module M ' b.vb Private ReadOnly TOOL_OUTPUT_FILE_NAME As String = Settings.OutputFileName Function Test() As Settings return Nothing End Function End Module ]]></file> </compilation>, TestOptions.ReleaseExe) Dim allDiagnostics = comp.GetDiagnostics() AssertTheseDiagnostics(allDiagnostics, <expected><![CDATA[ BC30002: Type 'Settings' is not defined. Private Test2 As Settings ~~~~~~~~ BC30179: module 'M' and module 'M' conflict in namespace '<Default>'. Module M ' b.vb ~ BC30451: 'Settings' is not declared. It may be inaccessible due to its protection level. Private ReadOnly TOOL_OUTPUT_FILE_NAME As String = Settings.OutputFileName ~~~~~~~~ BC30002: Type 'Settings' is not defined. Function Test() As Settings ~~~~~~~~ ]]></expected>) Dim tree = comp.SyntaxTrees.Where(Function(t) t.FilePath.EndsWith("a.vb", StringComparison.Ordinal)).Single Dim model = comp.GetSemanticModel(tree) AssertTheseDiagnostics(model.GetDiagnostics(), <expected><![CDATA[ BC30002: Type 'Settings' is not defined. Private Test2 As Settings ~~~~~~~~ ]]></expected>) tree = comp.SyntaxTrees.Where(Function(t) t.FilePath.EndsWith("b.vb", StringComparison.Ordinal)).Single model = comp.GetSemanticModel(tree) AssertTheseDiagnostics(model.GetDiagnostics(), <expected><![CDATA[ BC30179: module 'M' and module 'M' conflict in namespace '<Default>'. Module M ' b.vb ~ BC30451: 'Settings' is not declared. It may be inaccessible due to its protection level. Private ReadOnly TOOL_OUTPUT_FILE_NAME As String = Settings.OutputFileName ~~~~~~~~ BC30002: Type 'Settings' is not defined. Function Test() As Settings ~~~~~~~~ ]]></expected>) End Sub <Fact> Public Sub BC42004WRN_RecursiveOperatorCall() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Friend Module RecAcc001mod Class cls Sub New() End Sub Shared Operator +(ByVal y As cls) As Object Return +y End Operator Shared Operator -(ByVal x As cls, ByVal y As Object) As Object Return x - y End Operator Public Shared Operator >>(ByVal x As cls, ByVal y As Integer) As Object Return x >> y End Operator Public Shared Widening Operator CType(ByVal y As cls) As Integer Return CType(y, Integer) End Operator End Class End Module ]]></file> </compilation>) Dim allDiagnostics = comp.GetDiagnostics() AssertTheseDiagnostics(allDiagnostics, <expected><![CDATA[ BC42004: Expression recursively calls the containing Operator 'Public Shared Operator +(y As RecAcc001mod.cls) As Object'. Return +y ~~ BC42004: Expression recursively calls the containing Operator 'Public Shared Operator -(x As RecAcc001mod.cls, y As Object) As Object'. Return x - y ~~~~~ BC42004: Expression recursively calls the containing Operator 'Public Shared Operator >>(x As RecAcc001mod.cls, y As Integer) As Object'. Return x >> y ~~~~~~ BC42004: Expression recursively calls the containing Operator 'Public Shared Widening Operator CType(y As RecAcc001mod.cls) As Integer'. Return CType(y, Integer) ~ ]]></expected>) End Sub <Fact(), WorkItem(5072, "https://github.com/dotnet/roslyn/issues/5072")> Public Sub LangVersion_ReadonlyAutoProperties() Dim source = <compilation> <file name="a.vb"> Class TestClass Public Sub New() 'Check assignment of readonly auto property Test = "Test" End Sub 'Check readonly auto-properties Public ReadOnly Property Test As String End Class Interface I1 ReadOnly Property Test1 As String WriteOnly Property Test2 As String Property Test3 As String End Interface MustInherit Class C1 MustOverride ReadOnly Property Test1 As String MustOverride WriteOnly Property Test2 As String MustOverride Property Test3 As String End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(source, parseOptions:=VisualBasicParseOptions.Default.WithLanguageVersion(LanguageVersion.VisualBasic12)) CompilationUtils.AssertTheseParseDiagnostics(compilation, <expected> BC36716: Visual Basic 12.0 does not support readonly auto-implemented properties. Public ReadOnly Property Test As String ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) compilation = CompilationUtils.CreateCompilationWithMscorlib40(source, parseOptions:=VisualBasicParseOptions.Default.WithLanguageVersion(LanguageVersion.VisualBasic9)) CompilationUtils.AssertTheseParseDiagnostics(compilation, <expected> BC36716: Visual Basic 9.0 does not support auto-implemented properties. Public ReadOnly Property Test As String ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact(), WorkItem(5072, "https://github.com/dotnet/roslyn/issues/5072")> Public Sub LangVersion_RegionEveryWhere01() Dim source = <compilation> <file name="a.vb"> Class TestClass Sub New() #Region "Region in .ctor" #End Region ' "Region in .ctor" End Sub Shared Sub New() #Region "Region in .cctor" #End Region ' "Region in .cctor" End Sub Public Sub ASub() #Region "Region in a Sub" #End Region ' "Region in a Sub" End Sub Public Function AFunc() #Region "Region in a Func" #End Region ' "Region in a Func" End Function Shared Operator +(x As TestClass, y As TestClass) As TestClass #Region "Region in an operator" #End Region ' "Region in an operator" End Operator Property P As Integer Get #Region "Region in a get" #End Region ' "Region in a get" End Get Set(value As Integer) #Region "Region in a set" #End Region ' "Region in a set" End Set End Property Custom Event E As System.Action AddHandler(value As Action) #Region "Region in an add" #End Region ' "Region in an add" End AddHandler RemoveHandler(value As Action) #Region "Region in a remove" #End Region ' "Region in a remove" End RemoveHandler RaiseEvent() #Region "Region in a raise" #End Region ' "Region in a raise" End RaiseEvent End Event End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(source, parseOptions:=VisualBasicParseOptions.Default.WithLanguageVersion(LanguageVersion.VisualBasic12)) CompilationUtils.AssertTheseParseDiagnostics(compilation, <expected> BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #Region "Region in .ctor" ~~~~~~~~~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #End Region ' "Region in .ctor" ~~~~~~~~~~~ BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #Region "Region in .cctor" ~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #End Region ' "Region in .cctor" ~~~~~~~~~~~ BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #Region "Region in a Sub" ~~~~~~~~~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #End Region ' "Region in a Sub" ~~~~~~~~~~~ BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #Region "Region in a Func" ~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #End Region ' "Region in a Func" ~~~~~~~~~~~ BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #Region "Region in an operator" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #End Region ' "Region in an operator" ~~~~~~~~~~~ BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #Region "Region in a get" ~~~~~~~~~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #End Region ' "Region in a get" ~~~~~~~~~~~ BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #Region "Region in a set" ~~~~~~~~~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #End Region ' "Region in a set" ~~~~~~~~~~~ BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #Region "Region in an add" ~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #End Region ' "Region in an add" ~~~~~~~~~~~ BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #Region "Region in a remove" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #End Region ' "Region in a remove" ~~~~~~~~~~~ BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #Region "Region in a raise" ~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #End Region ' "Region in a raise" ~~~~~~~~~~~ </expected>) End Sub <Fact(), WorkItem(5072, "https://github.com/dotnet/roslyn/issues/5072")> Public Sub LangVersion_RegionEveryWhere02() Dim source = <compilation> <file name="a.vb"> Class TestClass #Region "Region" #End Region Sub New() End Sub #Region "Region" #End Region Shared Sub New() End Sub #Region "Region" #End Region Public Sub ASub() End Sub #Region "Region" #End Region Public Function AFunc() End Function #Region "Region" #End Region Shared Operator +(x As TestClass, y As TestClass) As TestClass End Operator #Region "Region" #End Region Property P As Integer #Region "Region" #End Region Get End Get #Region "Region" #End Region Set(value As Integer) End Set #Region "Region" #End Region End Property #Region "Region" #End Region Custom Event E As System.Action #Region "Region" #End Region AddHandler(value As Action) End AddHandler #Region "Region" #End Region RemoveHandler(value As Action) End RemoveHandler #Region "Region" #End Region RaiseEvent() End RaiseEvent #Region "Region" #End Region End Event #Region "Region" #End Region End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(source, parseOptions:=VisualBasicParseOptions.Default.WithLanguageVersion(LanguageVersion.VisualBasic12)) CompilationUtils.AssertTheseParseDiagnostics(compilation, <expected> </expected>) End Sub <Fact(), WorkItem(5072, "https://github.com/dotnet/roslyn/issues/5072")> Public Sub LangVersion_RegionEveryWhere03() Dim source = <compilation> <file name="a.vb"> Class TestClass #Region "Region" Private f1 as Integer #End Region Sub New() End Sub #Region "Region" Private f1 as Integer #End Region Shared Sub New() End Sub #Region "Region" Private f1 as Integer #End Region Public Sub ASub() End Sub #Region "Region" Private f1 as Integer #End Region Public Function AFunc() End Function #Region "Region" Private f1 as Integer #End Region Shared Operator +(x As TestClass, y As TestClass) As TestClass End Operator #Region "Region" Private f1 as Integer #End Region Property P As Integer #Region "Region" #End Region Get End Get #Region "Region" #End Region Set(value As Integer) End Set #Region "Region" #End Region End Property #Region "Region" Private f1 as Integer #End Region Custom Event E As System.Action #Region "Region" #End Region AddHandler(value As Action) End AddHandler #Region "Region" #End Region RemoveHandler(value As Action) End RemoveHandler #Region "Region" #End Region RaiseEvent() End RaiseEvent #Region "Region" #End Region End Event #Region "Region" Private f1 as Integer #End Region End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(source, parseOptions:=VisualBasicParseOptions.Default.WithLanguageVersion(LanguageVersion.VisualBasic12)) CompilationUtils.AssertTheseParseDiagnostics(compilation, <expected> </expected>) End Sub <Fact(), WorkItem(5072, "https://github.com/dotnet/roslyn/issues/5072")> Public Sub LangVersion_RegionEveryWhere04() Dim source = <compilation> <file name="a.vb"> Class TestClass #Region "Region" Sub New() End Sub #End Region #Region "Region" Shared Sub New() End Sub #End Region #Region "Region" Public Sub ASub() End Sub #End Region #Region "Region" Public Function AFunc() End Function #End Region #Region "Region" Shared Operator +(x As TestClass, y As TestClass) As TestClass End Operator #End Region #Region "Region" Property P As Integer #Region "Region" Get End Get #End Region #Region "Region" Set(value As Integer) End Set #End Region End Property #End Region #Region "Region" Custom Event E As System.Action #Region "Region" AddHandler(value As Action) End AddHandler #End Region #Region "Region" RemoveHandler(value As Action) End RemoveHandler #End Region #Region "Region" RaiseEvent() End RaiseEvent #End Region End Event #End Region End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(source, parseOptions:=VisualBasicParseOptions.Default.WithLanguageVersion(LanguageVersion.VisualBasic12)) CompilationUtils.AssertTheseParseDiagnostics(compilation, <expected> </expected>) End Sub <Fact(), WorkItem(5072, "https://github.com/dotnet/roslyn/issues/5072")> Public Sub LangVersion_RegionEveryWhere05() Dim source = <compilation> <file name="a.vb"> Class TestClass Property P As Integer Get #Region "Region" #End Region </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(source, parseOptions:=VisualBasicParseOptions.Default.WithLanguageVersion(LanguageVersion.VisualBasic12)) CompilationUtils.AssertTheseParseDiagnostics(compilation, <expected> BC30481: 'Class' statement must end with a matching 'End Class'. Class TestClass ~~~~~~~~~~~~~~~ BC30025: Property missing 'End Property'. Property P As Integer ~~~~~~~~~~~~~~~~~~~~~ BC30631: 'Get' statement must end with a matching 'End Get'. Get ~~~ </expected>) End Sub <Fact(), WorkItem(5072, "https://github.com/dotnet/roslyn/issues/5072")> Public Sub LangVersion_RegionEveryWhere06() Dim source = <compilation> <file name="a.vb"> Class TestClass Property P As Integer Get End Get #Region "Region" #End Region</file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(source, parseOptions:=VisualBasicParseOptions.Default.WithLanguageVersion(LanguageVersion.VisualBasic12)) CompilationUtils.AssertTheseParseDiagnostics(compilation, <expected> BC30481: 'Class' statement must end with a matching 'End Class'. Class TestClass ~~~~~~~~~~~~~~~ BC30025: Property missing 'End Property'. Property P As Integer ~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact(), WorkItem(5072, "https://github.com/dotnet/roslyn/issues/5072")> Public Sub LangVersion_RegionEveryWhere07() Dim source = <compilation> <file name="a.vb"> Class TestClass Property P As Integer Get #Region "Region" #End Region End Property End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(source, parseOptions:=VisualBasicParseOptions.Default.WithLanguageVersion(LanguageVersion.VisualBasic12)) CompilationUtils.AssertTheseParseDiagnostics(compilation, <expected> BC30631: 'Get' statement must end with a matching 'End Get'. Get ~~~ </expected>) End Sub <Fact(), WorkItem(5072, "https://github.com/dotnet/roslyn/issues/5072")> Public Sub LangVersion_RegionEveryWhere08() Dim source = <compilation> <file name="a.vb"> Class TestClass Sub Test() #if False #Region "Region" #End Region #End if End Sub End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(source, parseOptions:=VisualBasicParseOptions.Default.WithLanguageVersion(LanguageVersion.VisualBasic12)) CompilationUtils.AssertTheseParseDiagnostics(compilation, <expected> </expected>) End Sub <Fact(), WorkItem(5072, "https://github.com/dotnet/roslyn/issues/5072")> Public Sub LangVersion_RegionEveryWhere09() Dim source = <compilation> <file name="a.vb"> #Region "Region 1" #End Region ' 1 </file> <file name="b.vb"> #Region "Region 2" </file> <file name="c.vb"> #End Region ' 3 </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(source, parseOptions:=VisualBasicParseOptions.Default.WithLanguageVersion(LanguageVersion.VisualBasic12)) CompilationUtils.AssertTheseParseDiagnostics(compilation, <expected> BC30681: '#Region' statement must end with a matching '#End Region'. #Region "Region 2" ~~~~~~~~~~~~~~~~~~ BC30680: '#End Region' must be preceded by a matching '#Region'. #End Region ' 3 ~~~~~~~~~~~ </expected>) End Sub <Fact(), WorkItem(5072, "https://github.com/dotnet/roslyn/issues/5072")> Public Sub LangVersion_RegionEveryWhere10() Dim source = <compilation> <file name="a.vb"> Namespace NS1 #Region "Region1" #End Region ' 1 End Namespace #Region "Region2" Namespace NS2 #End Region ' 2 End Namespace Namespace NS3 #Region "Region3" End Namespace #End Region ' 3 Namespace NS4 #Region "Region4" End Namespace Namespace NS5 #End Region ' 4 End Namespace #Region "Region5" Namespace NS6 End Namespace #End Region ' 5 </file> <file name="b.vb"> Namespace NS7 #Region "Region6" End Namespace </file> <file name="c.vb"> Namespace NS8 #End Region ' 7 End Namespace </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(source, parseOptions:=VisualBasicParseOptions.Default.WithLanguageVersion(LanguageVersion.VisualBasic12)) CompilationUtils.AssertTheseParseDiagnostics(compilation, <expected> BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #End Region ' 2 ~~~~~~~~~~~ BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #End Region ' 3 ~~~~~~~~~~~ BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #End Region ' 4 ~~~~~~~~~~~ BC30681: '#Region' statement must end with a matching '#End Region'. #Region "Region6" ~~~~~~~~~~~~~~~~~ BC30680: '#End Region' must be preceded by a matching '#Region'. #End Region ' 7 ~~~~~~~~~~~ </expected>) End Sub <Fact(), WorkItem(5072, "https://github.com/dotnet/roslyn/issues/5072")> Public Sub LangVersion_RegionEveryWhere11() Dim source = <compilation> <file name="a.vb"> Module NS1 #Region "Region1" #End Region ' 1 End Module #Region "Region2" Module NS2 #End Region ' 2 End Module Module NS3 #Region "Region3" End Module #End Region ' 3 Module NS4 #Region "Region4" End Module Module NS5 #End Region ' 4 End Module #Region "Region5" Module NS6 End Module #End Region ' 5 </file> <file name="b.vb"> Module NS7 #Region "Region6" End Module </file> <file name="c.vb"> Module NS8 #End Region ' 7 End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(source, parseOptions:=VisualBasicParseOptions.Default.WithLanguageVersion(LanguageVersion.VisualBasic12)) CompilationUtils.AssertTheseParseDiagnostics(compilation, <expected> BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #End Region ' 2 ~~~~~~~~~~~ BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #End Region ' 3 ~~~~~~~~~~~ BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #End Region ' 4 ~~~~~~~~~~~ BC30681: '#Region' statement must end with a matching '#End Region'. #Region "Region6" ~~~~~~~~~~~~~~~~~ BC30680: '#End Region' must be preceded by a matching '#Region'. #End Region ' 7 ~~~~~~~~~~~ </expected>) End Sub <Fact(), WorkItem(5072, "https://github.com/dotnet/roslyn/issues/5072")> Public Sub LangVersion_RegionEveryWhere12() Dim source = <compilation> <file name="a.vb"> Class NS1 #Region "Region1" #End Region ' 1 End Class #Region "Region2" Class NS2 #End Region ' 2 End Class Class NS3 #Region "Region3" End Class #End Region ' 3 Class NS4 #Region "Region4" End Class Class NS5 #End Region ' 4 End Class #Region "Region5" Class NS6 End Class #End Region ' 5 </file> <file name="b.vb"> Class NS7 #Region "Region6" End Class </file> <file name="c.vb"> Class NS8 #End Region ' 7 End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(source, parseOptions:=VisualBasicParseOptions.Default.WithLanguageVersion(LanguageVersion.VisualBasic12)) CompilationUtils.AssertTheseParseDiagnostics(compilation, <expected> BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #End Region ' 2 ~~~~~~~~~~~ BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #End Region ' 3 ~~~~~~~~~~~ BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #End Region ' 4 ~~~~~~~~~~~ BC30681: '#Region' statement must end with a matching '#End Region'. #Region "Region6" ~~~~~~~~~~~~~~~~~ BC30680: '#End Region' must be preceded by a matching '#Region'. #End Region ' 7 ~~~~~~~~~~~ </expected>) End Sub <Fact(), WorkItem(5072, "https://github.com/dotnet/roslyn/issues/5072")> Public Sub LangVersion_RegionEveryWhere13() Dim source = <compilation> <file name="a.vb"> Structure NS1 #Region "Region1" #End Region ' 1 End Structure #Region "Region2" Structure NS2 #End Region ' 2 End Structure Structure NS3 #Region "Region3" End Structure #End Region ' 3 Structure NS4 #Region "Region4" End Structure Structure NS5 #End Region ' 4 End Structure #Region "Region5" Structure NS6 End Structure #End Region ' 5 </file> <file name="b.vb"> Structure NS7 #Region "Region6" End Structure </file> <file name="c.vb"> Structure NS8 #End Region ' 7 End Structure </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(source, parseOptions:=VisualBasicParseOptions.Default.WithLanguageVersion(LanguageVersion.VisualBasic12)) CompilationUtils.AssertTheseParseDiagnostics(compilation, <expected> BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #End Region ' 2 ~~~~~~~~~~~ BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #End Region ' 3 ~~~~~~~~~~~ BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #End Region ' 4 ~~~~~~~~~~~ BC30681: '#Region' statement must end with a matching '#End Region'. #Region "Region6" ~~~~~~~~~~~~~~~~~ BC30680: '#End Region' must be preceded by a matching '#Region'. #End Region ' 7 ~~~~~~~~~~~ </expected>) End Sub <Fact(), WorkItem(5072, "https://github.com/dotnet/roslyn/issues/5072")> Public Sub LangVersion_RegionEveryWhere14() Dim source = <compilation> <file name="a.vb"> Interface NS1 #Region "Region1" #End Region ' 1 End Interface #Region "Region2" Interface NS2 #End Region ' 2 End Interface Interface NS3 #Region "Region3" End Interface #End Region ' 3 Interface NS4 #Region "Region4" End Interface Interface NS5 #End Region ' 4 End Interface #Region "Region5" Interface NS6 End Interface #End Region ' 5 </file> <file name="b.vb"> Interface NS7 #Region "Region6" End Interface </file> <file name="c.vb"> Interface NS8 #End Region ' 7 End Interface </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(source, parseOptions:=VisualBasicParseOptions.Default.WithLanguageVersion(LanguageVersion.VisualBasic12)) CompilationUtils.AssertTheseParseDiagnostics(compilation, <expected> BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #End Region ' 2 ~~~~~~~~~~~ BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #End Region ' 3 ~~~~~~~~~~~ BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #End Region ' 4 ~~~~~~~~~~~ BC30681: '#Region' statement must end with a matching '#End Region'. #Region "Region6" ~~~~~~~~~~~~~~~~~ BC30680: '#End Region' must be preceded by a matching '#Region'. #End Region ' 7 ~~~~~~~~~~~ </expected>) End Sub <Fact(), WorkItem(5072, "https://github.com/dotnet/roslyn/issues/5072")> Public Sub LangVersion_RegionEveryWhere15() Dim source = <compilation> <file name="a.vb"> Enum NS1 #Region "Region1" #End Region ' 1 End Enum #Region "Region2" Enum NS2 #End Region ' 2 End Enum Enum NS3 #Region "Region3" End Enum #End Region ' 3 Enum NS4 #Region "Region4" End Enum Enum NS5 #End Region ' 4 End Enum #Region "Region5" Enum NS6 End Enum #End Region ' 5 </file> <file name="b.vb"> Enum NS7 #Region "Region6" End Enum </file> <file name="c.vb"> Enum NS8 #End Region ' 7 End Enum </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(source, parseOptions:=VisualBasicParseOptions.Default.WithLanguageVersion(LanguageVersion.VisualBasic12)) CompilationUtils.AssertTheseParseDiagnostics(compilation, <expected> BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #End Region ' 2 ~~~~~~~~~~~ BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #End Region ' 3 ~~~~~~~~~~~ BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #End Region ' 4 ~~~~~~~~~~~ BC30681: '#Region' statement must end with a matching '#End Region'. #Region "Region6" ~~~~~~~~~~~~~~~~~ BC30680: '#End Region' must be preceded by a matching '#Region'. #End Region ' 7 ~~~~~~~~~~~ </expected>) End Sub <Fact(), WorkItem(5072, "https://github.com/dotnet/roslyn/issues/5072")> Public Sub LangVersion_RegionEveryWhere16() Dim source = <compilation> <file name="a.vb"> Class NS1 Property P1 As Integer #Region "Region1" #End Region ' 1 Get End Get Set End Set End Property End Class Class NS2 #Region "Region2" Property P1 As Integer #End Region ' 2 Get End Get Set End Set End Property End Class Class NS3 Property P1 As Integer #Region "Region3" Get End Get Set End Set End Property #End Region ' 3 End Class Class NS4 Property P1 As Integer #Region "Region4" Get End Get Set End Set End Property Property P2 As Integer #End Region ' 4 Get End Get Set End Set End Property End Class Class NS6 #Region "Region5" Property P1 As Integer Get End Get Set End Set End Property #End Region ' 5 End Class </file> <file name="b.vb"> Class NS7 Property P1 As Integer #Region "Region6" Get End Get Set End Set End Property End Class </file> <file name="c.vb"> Class NS8 Property P1 As Integer #End Region ' 7 Get End Get Set End Set End Property End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(source, parseOptions:=VisualBasicParseOptions.Default.WithLanguageVersion(LanguageVersion.VisualBasic12)) CompilationUtils.AssertTheseParseDiagnostics(compilation, <expected> BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #End Region ' 2 ~~~~~~~~~~~ BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #End Region ' 3 ~~~~~~~~~~~ BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #End Region ' 4 ~~~~~~~~~~~ BC30681: '#Region' statement must end with a matching '#End Region'. #Region "Region6" ~~~~~~~~~~~~~~~~~ BC30680: '#End Region' must be preceded by a matching '#Region'. #End Region ' 7 ~~~~~~~~~~~ </expected>) End Sub <Fact(), WorkItem(5072, "https://github.com/dotnet/roslyn/issues/5072")> Public Sub LangVersion_RegionEveryWhere17() Dim source = <compilation> <file name="a.vb"> Class NS1 Custom Event E1 As System.Action #Region "Region1" #End Region ' 1 AddHandler(value As Action) End AddHandler RemoveHandler(value As Action) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class Class NS2 #Region "Region2" Custom Event E1 As System.Action #End Region ' 2 AddHandler(value As Action) End AddHandler RemoveHandler(value As Action) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class Class NS3 Custom Event E1 As System.Action #Region "Region3" AddHandler(value As Action) End AddHandler RemoveHandler(value As Action) End RemoveHandler RaiseEvent() End RaiseEvent End Event #End Region ' 3 End Class Class NS4 Custom Event E1 As System.Action #Region "Region4" AddHandler(value As Action) End AddHandler RemoveHandler(value As Action) End RemoveHandler RaiseEvent() End RaiseEvent End Event Custom Event E2 As System.Action #End Region ' 4 AddHandler(value As Action) End AddHandler RemoveHandler(value As Action) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class Class NS6 #Region "Region5" Custom Event E1 As System.Action AddHandler(value As Action) End AddHandler RemoveHandler(value As Action) End RemoveHandler RaiseEvent() End RaiseEvent End Event #End Region ' 5 End Class </file> <file name="b.vb"> Class NS7 Custom Event E1 As System.Action #Region "Region6" AddHandler(value As Action) End AddHandler RemoveHandler(value As Action) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class </file> <file name="c.vb"> Class NS8 Custom Event E1 As System.Action #End Region ' 7 AddHandler(value As Action) End AddHandler RemoveHandler(value As Action) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(source, parseOptions:=VisualBasicParseOptions.Default.WithLanguageVersion(LanguageVersion.VisualBasic12)) CompilationUtils.AssertTheseParseDiagnostics(compilation, <expected> BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #End Region ' 2 ~~~~~~~~~~~ BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #End Region ' 3 ~~~~~~~~~~~ BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #End Region ' 4 ~~~~~~~~~~~ BC30681: '#Region' statement must end with a matching '#End Region'. #Region "Region6" ~~~~~~~~~~~~~~~~~ BC30680: '#End Region' must be preceded by a matching '#Region'. #End Region ' 7 ~~~~~~~~~~~ </expected>) End Sub <Fact(), WorkItem(5072, "https://github.com/dotnet/roslyn/issues/5072")> Public Sub LangVersion_RegionEveryWhere18() Dim source = <compilation> <file name="a.vb"> #Region "Region1" Class NS1 #Region "Region2" Sub Test1() #End Region ' 2 End Sub End Class #End Region ' 1 </file> <file name="b.vb"> #Region "Region3" Class NS2 Sub Test1() #Region "Region4" End Sub #End Region ' 4 End Class #End Region ' 3 </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(source, parseOptions:=VisualBasicParseOptions.Default.WithLanguageVersion(LanguageVersion.VisualBasic12)) CompilationUtils.AssertTheseParseDiagnostics(compilation, <expected> BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #End Region ' 2 ~~~~~~~~~~~ BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #Region "Region4" ~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact(), WorkItem(5072, "https://github.com/dotnet/roslyn/issues/5072")> Public Sub LangVersion_CObjInAttributes() Dim source = <compilation> <file name="a.vb"><![CDATA[ Class TestClass1 <System.ComponentModel.DefaultValue(CObj("Test"))> Public Property Test2 As String '<System.ComponentModel.DefaultValue(CType("Test", Object))> 'Public Property Test3 As String '<System.ComponentModel.DefaultValue(DirectCast("Test", Object))> 'Public Property Test4 As String '<System.ComponentModel.DefaultValue(TryCast("Test", Object))> 'Public Property Test5 As String End Class ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndReferences(source, {SystemRef}, parseOptions:=VisualBasicParseOptions.Default.WithLanguageVersion(LanguageVersion.VisualBasic12)) CompilationUtils.AssertTheseDiagnostics(compilation, <expected><![CDATA[ BC36716: Visual Basic 12.0 does not support CObj in attribute arguments. <System.ComponentModel.DefaultValue(CObj("Test"))> ~~~~ ]]></expected>) End Sub <Fact(), WorkItem(5072, "https://github.com/dotnet/roslyn/issues/5072")> Public Sub LangVersion_MultilineStrings() Dim source = <compilation> <file name="a.vb"><![CDATA[ Class TestClass Dim test4 = " This is a muiltiline string" End Class ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(source, parseOptions:=VisualBasicParseOptions.Default.WithLanguageVersion(LanguageVersion.VisualBasic12)) CompilationUtils.AssertTheseParseDiagnostics(compilation, <expected> BC36716: Visual Basic 12.0 does not support multiline string literals. Dim test4 = " ~~ </expected>) End Sub <Fact(), WorkItem(5072, "https://github.com/dotnet/roslyn/issues/5072")> Public Sub LangVersion_LineContinuationComments() Dim source = <compilation> <file name="a.vb"><![CDATA[ Class TestClass Dim test5 As String = "" Dim chars = From c In test5 'This is a test of comments in a linq statement Let asc = Asc(c) 'VS2015 can handle this Select asc Sub Test() Dim chars2 = From c In test5 'This is a test of comments in a linq statement Let asc = Asc(c) 'VS2015 can handle this Select asc End Sub End Class ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(source, parseOptions:=VisualBasicParseOptions.Default.WithLanguageVersion(LanguageVersion.VisualBasic12)) CompilationUtils.AssertTheseParseDiagnostics(compilation, <expected> BC36716: Visual Basic 12.0 does not support line continuation comments. Dim chars = From c In test5 'This is a test of comments in a linq statement ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 12.0 does not support line continuation comments. Dim chars2 = From c In test5 'This is a test of comments in a linq statement ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) compilation = CompilationUtils.CreateCompilationWithMscorlib40(source, parseOptions:=VisualBasicParseOptions.Default.WithLanguageVersion(LanguageVersion.VisualBasic9)) CompilationUtils.AssertTheseParseDiagnostics(compilation, <expected> BC36716: Visual Basic 9.0 does not support implicit line continuation. Dim chars = From c In test5 'This is a test of comments in a linq statement ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 9.0 does not support implicit line continuation. Dim chars2 = From c In test5 'This is a test of comments in a linq statement ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact(), WorkItem(5072, "https://github.com/dotnet/roslyn/issues/5072")> Public Sub LangVersion_TypeOfIsNot() Dim source = <compilation> <file name="a.vb"><![CDATA[ Class TestClass Sub Test() Dim test6 As String = "" If TypeOf test6 IsNot System.String Then Console.WriteLine("That string isn't a string") End Sub End Class ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(source, parseOptions:=VisualBasicParseOptions.Default.WithLanguageVersion(LanguageVersion.VisualBasic12)) CompilationUtils.AssertTheseParseDiagnostics(compilation, <expected> BC36716: Visual Basic 12.0 does not support TypeOf IsNot expression. If TypeOf test6 IsNot System.String Then Console.WriteLine("That string isn't a string") ~~~~~ </expected>) End Sub <Fact(), WorkItem(5072, "https://github.com/dotnet/roslyn/issues/5072")> Public Sub LangVersion_YearFirstDateLiterals() Dim source = <compilation> <file name="a.vb"><![CDATA[ Class TestClass Sub Test() Dim d = #2015-08-23# End Sub End Class ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(source, parseOptions:=VisualBasicParseOptions.Default.WithLanguageVersion(LanguageVersion.VisualBasic12)) CompilationUtils.AssertTheseParseDiagnostics(compilation, <expected> BC36716: Visual Basic 12.0 does not support year-first date literals. Dim d = #2015-08-23# ~~~~~~~~~~~~ </expected>) End Sub <Fact(), WorkItem(5072, "https://github.com/dotnet/roslyn/issues/5072")> Public Sub LangVersion_Pragma() Dim source = <compilation> <file name="a.vb"><![CDATA[ Class TestClass Sub Test() #Disable Warning BC42024 Dim test7 As String 'Should have no "unused variable" warning #Enable Warning BC42024 End Sub End Class ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(source, parseOptions:=VisualBasicParseOptions.Default.WithLanguageVersion(LanguageVersion.VisualBasic12)) CompilationUtils.AssertTheseParseDiagnostics(compilation, <expected> BC36716: Visual Basic 12.0 does not support warning directives. #Disable Warning BC42024 ~~~~~~~~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 12.0 does not support warning directives. #Enable Warning BC42024 ~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact(), WorkItem(5072, "https://github.com/dotnet/roslyn/issues/5072")> Public Sub LangVersion_PartialModulesAndInterfaces() Dim source = <compilation> <file name="a.vb"><![CDATA[ Partial Module Module1 End Module Partial Interface IFace End Interface ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(source, parseOptions:=VisualBasicParseOptions.Default.WithLanguageVersion(LanguageVersion.VisualBasic12)) CompilationUtils.AssertTheseParseDiagnostics(compilation, <expected> BC36716: Visual Basic 12.0 does not support partial modules. Partial Module Module1 ~~~~~~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 12.0 does not support partial interfaces. Partial Interface IFace ~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact(), WorkItem(5072, "https://github.com/dotnet/roslyn/issues/5072")> Public Sub LangVersion_ImplementReadonlyWithReadwrite() Dim source = <compilation> <file name="a.vb"><![CDATA[ Interface IReadOnly ReadOnly Property Test1 As String WriteOnly Property Test2 As String End Interface Class ReadWrite Implements IReadOnly Public Property Test1 As String Implements IReadOnly.Test1 Public Property Test2 As String Implements IReadOnly.Test2 End Class ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndReferences(source, {SystemRef}, parseOptions:=VisualBasicParseOptions.Default.WithLanguageVersion(LanguageVersion.VisualBasic12)) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36716: Visual Basic 12.0 does not support implementing read-only or write-only property with read-write property. Public Property Test1 As String Implements IReadOnly.Test1 ~~~~~~~~~~~~~~~ BC36716: Visual Basic 12.0 does not support implementing read-only or write-only property with read-write property. Public Property Test2 As String Implements IReadOnly.Test2 ~~~~~~~~~~~~~~~ </expected>) End Sub <Fact(), WorkItem(13617, "https://github.com/dotnet/roslyn/issues/13617")> Public Sub MissingTypeArgumentInGenericExtensionMethod() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.CompilerServices Module FooExtensions <Extension()> Public Function ExtensionMethod0(ByVal obj As Object) Return GetType(Object) End Function <Extension()> Public Function ExtensionMethod1(Of T)(ByVal obj As Object) Return GetType(T) End Function <Extension()> Public Function ExtensionMethod2(Of T1, T2)(ByVal obj As Object) Return GetType(T1) End Function End Module Module Module1 Sub Main() Dim omittedArg0 As Type = "string literal".ExtensionMethod0(Of )() Dim omittedArg1 As Type = "string literal".ExtensionMethod1(Of )() Dim omittedArg2 As Type = "string literal".ExtensionMethod2(Of )() Dim omittedArgFunc0 As Func(Of Object) = "string literal".ExtensionMethod0(Of ) Dim omittedArgFunc1 As Func(Of Object) = "string literal".ExtensionMethod1(Of ) Dim omittedArgFunc2 As Func(Of Object) = "string literal".ExtensionMethod2(Of ) Dim moreArgs0 As Type = "string literal".ExtensionMethod0(Of Integer)() Dim moreArgs1 As Type = "string literal".ExtensionMethod1(Of Integer, Boolean)() Dim moreArgs2 As Type = "string literal".ExtensionMethod2(Of Integer, Boolean, String)() Dim lessArgs1 As Type = "string literal".ExtensionMethod1() Dim lessArgs2 As Type = "string literal".ExtensionMethod2(Of Integer)() Dim nonExistingMethod0 As Type = "string literal".ExtensionMethodNotFound0() Dim nonExistingMethod1 As Type = "string literal".ExtensionMethodNotFound1(Of Integer)() Dim nonExistingMethod2 As Type = "string literal".ExtensionMethodNotFound2(Of Integer, String)() Dim exactArgs0 As Type = "string literal".ExtensionMethod0() Dim exactArgs1 As Type = "string literal".ExtensionMethod1(Of Integer)() Dim exactArgs2 As Type = "string literal".ExtensionMethod2(Of Integer, Boolean)() End Sub End Module ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, {Net40.SystemCore}) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36907: Extension method 'Public Function ExtensionMethod0() As Object' defined in 'FooExtensions' is not generic (or has no free type parameters) and so cannot have type arguments. Dim omittedArg0 As Type = "string literal".ExtensionMethod0(Of )() ~~~~~ BC30182: Type expected. Dim omittedArg0 As Type = "string literal".ExtensionMethod0(Of )() ~ BC30182: Type expected. Dim omittedArg1 As Type = "string literal".ExtensionMethod1(Of )() ~ BC36590: Too few type arguments to extension method 'Public Function ExtensionMethod2(Of T1, T2)() As Object' defined in 'FooExtensions'. Dim omittedArg2 As Type = "string literal".ExtensionMethod2(Of )() ~~~~~ BC30182: Type expected. Dim omittedArg2 As Type = "string literal".ExtensionMethod2(Of )() ~ BC36907: Extension method 'Public Function ExtensionMethod0() As Object' defined in 'FooExtensions' is not generic (or has no free type parameters) and so cannot have type arguments. Dim omittedArgFunc0 As Func(Of Object) = "string literal".ExtensionMethod0(Of ) ~~~~~ BC30182: Type expected. Dim omittedArgFunc0 As Func(Of Object) = "string literal".ExtensionMethod0(Of ) ~ BC30182: Type expected. Dim omittedArgFunc1 As Func(Of Object) = "string literal".ExtensionMethod1(Of ) ~ BC36590: Too few type arguments to extension method 'Public Function ExtensionMethod2(Of T1, T2)() As Object' defined in 'FooExtensions'. Dim omittedArgFunc2 As Func(Of Object) = "string literal".ExtensionMethod2(Of ) ~~~~~ BC30182: Type expected. Dim omittedArgFunc2 As Func(Of Object) = "string literal".ExtensionMethod2(Of ) ~ BC36907: Extension method 'Public Function ExtensionMethod0() As Object' defined in 'FooExtensions' is not generic (or has no free type parameters) and so cannot have type arguments. Dim moreArgs0 As Type = "string literal".ExtensionMethod0(Of Integer)() ~~~~~~~~~~~~ BC36591: Too many type arguments to extension method 'Public Function ExtensionMethod1(Of T)() As Object' defined in 'FooExtensions'. Dim moreArgs1 As Type = "string literal".ExtensionMethod1(Of Integer, Boolean)() ~~~~~~~~~~~~~~~~~~~~~ BC36591: Too many type arguments to extension method 'Public Function ExtensionMethod2(Of T1, T2)() As Object' defined in 'FooExtensions'. Dim moreArgs2 As Type = "string literal".ExtensionMethod2(Of Integer, Boolean, String)() ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36589: Type parameter 'T' for extension method 'Public Function ExtensionMethod1(Of T)() As Object' defined in 'FooExtensions' cannot be inferred. Dim lessArgs1 As Type = "string literal".ExtensionMethod1() ~~~~~~~~~~~~~~~~ BC36590: Too few type arguments to extension method 'Public Function ExtensionMethod2(Of T1, T2)() As Object' defined in 'FooExtensions'. Dim lessArgs2 As Type = "string literal".ExtensionMethod2(Of Integer)() ~~~~~~~~~~~~ BC30456: 'ExtensionMethodNotFound0' is not a member of 'String'. Dim nonExistingMethod0 As Type = "string literal".ExtensionMethodNotFound0() ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30456: 'ExtensionMethodNotFound1' is not a member of 'String'. Dim nonExistingMethod1 As Type = "string literal".ExtensionMethodNotFound1(Of Integer)() ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30456: 'ExtensionMethodNotFound2' is not a member of 'String'. Dim nonExistingMethod2 As Type = "string literal".ExtensionMethodNotFound2(Of Integer, String)() ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub End Class End Namespace
' 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.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Imports Roslyn.Test.Utilities.TestMetadata Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests ' this place is dedicated to binding related error tests Public Class BindingErrorTests Inherits BasicTestBase #Region "Targeted Error Tests - please arrange tests in the order of error code" <Fact()> Public Sub BC0ERR_None_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="None"> <file name="a.vb"> Imports System Class TimerState Public Delegate Sub MyEventHandler(ByVal sender As Object, ByVal e As System.EventArgs) Private m_MyEvent As MyEventHandler Public Custom Event MyEvent As MyEventHandler RaiseEvent(ByVal sender As Object, ByVal e As System.EventArgs) m_MyEvent.Invoke(sender, e) End RaiseEvent AddHandler(ByVal value As MyEventHandler) m_MyEvent = DirectCast ( _ [Delegate].Combine(m_MyEvent, value), _ MyEventHandler) : End addHandler RemoveHandler(ByVal value As MyEventHandler) m_MyEvent = DirectCast ( _ [Delegate].RemoveAll(m_MyEvent, value), _ MyEventHandler) End RemoveHandler End Event End Class </file> </compilation>) CompilationUtils.AssertNoErrors(compilation) End Sub <Fact()> Public Sub BC0ERR_None_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="None"> <file name="a.vb"> Class AAA Private _name As String Public ReadOnly Property Name() As String Get Return _name : End Get End Property Private _age As String Public ReadOnly Property Age() As String Get Return _age : End Get End Property End Class </file> </compilation>) CompilationUtils.AssertNoErrors(compilation) End Sub <Fact()> Public Sub BC0ERR_None_3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="None"> <file name="a.vb"> Module M1 Function B As string Dim x = 1: End Function Function C As string Dim x = 2 :End Function End Module </file> </compilation>) CompilationUtils.AssertNoErrors(compilation) End Sub <Fact()> Public Sub BC0ERR_None_4() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="None"> <file name="a.vb"> Public Class S1 Public Sub New() Dim cond = True GoTo l1 If False Then l1: End If End Sub End Class </file> </compilation>) CompilationUtils.AssertNoErrors(compilation) End Sub <Fact()> Public Sub BC0ERR_None_5() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="None"> <file name="a.vb"> Public Structure S1 Function FOO As String Return "h" End Function Sub Main() FOO FOO() End Sub End Structure </file> </compilation>) CompilationUtils.AssertNoErrors(compilation) End Sub <Fact()> Public Sub BC0ERR_None_6() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="None"> <file name="a.vb"> Public Structure S1 Sub Main() dim a?()(,) as integer dim b(2) as integer dim c as integer(,) End Sub End Structure </file> </compilation>) CompilationUtils.AssertNoErrors(compilation) End Sub <Fact()> Public Sub BC0ERR_None_7() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="None"> <file name="a.vb"> Public Class D Public Class Foo Public x As Integer End Class Public Class FooD Inherits Foo Public Sub Baz() End Sub End Class End Class </file> </compilation>) CompilationUtils.AssertNoErrors(compilation) End Sub <Fact()> Public Sub BC0ERR_None_8() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="None"> <file name="a.vb"> Public Class D Public Shared Sub Main() Dim x As Integer = 1 Dim b As Boolean = x = 1 System.Console.Write(b ) Dim l As Long = 5 System.Console.Write(l &gt; 6 ) Dim f As Single = 25 System.Console.Write(f &gt;= 25 ) Dim d As Double = 3 System.Console.Write(d &lt;= f ) End Sub End Class </file> </compilation>) CompilationUtils.AssertNoErrors(compilation) End Sub <Fact()> Public Sub BC0ERR_None_9() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="None"> <file name="a.vb"> Public Class C Public Shared Sub Main() System.Console.Write("{0}{1}{2}{3}{4}{5}", "a", "b", "c", "d", "e", "f" ) End Sub End Class </file> </compilation>) CompilationUtils.AssertNoErrors(compilation) End Sub <Fact()> Public Sub BC0ERR_None_10() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="None"> <file name="a.vb"> Public Class D Public Class Moo(Of T) Public Sub Boo(x As T) Dim local As T = x End Sub End Class End Class </file> </compilation>) CompilationUtils.AssertNoErrors(compilation) End Sub <Fact()> Public Sub BC0ERR_None_11() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="None"> <file name="a.vb"> Public Class C public class Moo public shared S as integer end class Public Shared Sub Main() System.Console.Write(Moo.S ) Moo.S = 42 System.Console.Write(Moo.S ) End Sub End Class </file> </compilation>) CompilationUtils.AssertNoErrors(compilation) End Sub <Fact()> Public Sub BC0ERR_None_12() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="None"> <file name="a.vb"> Public Class C Private Shared Function M(ByVal x As Integer, ByVal y As Integer, ByVal z As Integer) As Integer Return y End Function Public Shared Sub Main() System.Console.Write(M(0, 42, 1)) End Sub End Class </file> </compilation>) CompilationUtils.AssertNoErrors(compilation) End Sub <Fact()> Public Sub BC0ERR_None_13() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="None"> <file name="a.vb"> Public Class C Private Shared Function M() As System.AppDomain dim y as object = System.AppDomain.CreateDomain("qq") dim z as System.AppDomain = ctype(y,System.AppDomain) return z End Function End Class </file> </compilation>) CompilationUtils.AssertNoErrors(compilation) End Sub <Fact()> Public Sub BC0ERR_None_14() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="None"> <file name="a.vb"> Imports System Class Program Public Class C Public Function Foo(ByVal p1 As Short, ByVal p2 As UShort) As UInteger Return CUShort (p1 + p2) End Function Public Function Foo(ByVal p1 As Short, ByVal p2 As String) As UInteger Return CUInt (p1) End Function Public Function Foo(ByVal p1 As Short, ByVal ParamArray p2 As UShort()) As UInteger Return CByte (p2(0) + p2(1)) End Function End Class End Class </file> </compilation>) CompilationUtils.AssertNoErrors(compilation) End Sub <Fact()> Public Sub BC0ERR_None_15() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="None"> <file name="a.vb"> Class C Private Property P As Integer End Class </file> </compilation>) CompilationUtils.AssertNoErrors(compilation) End Sub <Fact()> Public Sub BC0ERR_None_16() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BC0ERR_None_16"> <file name="a.vb"> Class Tests Public Sub New() End Sub Public Sub New(i As Integer) Me.New() End Sub Public Sub New(s As String) : Call Me.New(1) End Sub Public Sub New(s As Double) ' comment Call Me.New(1) End Sub End Class </file> </compilation>) CompilationUtils.AssertNoErrors(compilation) End Sub <Fact()> Public Sub BC0ERR_None_17() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BC0ERR_None_17"> <file name="a.vb"> Class Tests Public Sub New() End Sub Public Sub New(i As Integer) #Const a = 1 Me.New() End Sub End Class </file> </compilation>) CompilationUtils.AssertNoErrors(compilation) End Sub <Fact()> Public Sub BC0ERR_None_18() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BC0ERR_None_18"> <file name="a.vb"> Class Tests Public Sub New() End Sub Public Sub New(i As Integer) #Const a = 1 #If a = 0 Then Me.New() #End If Me.New() End Sub End Class </file> </compilation>) CompilationUtils.AssertNoErrors(compilation) End Sub <Fact()> Public Sub BC0ERR_None_19() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BC0ERR_None_19"> <file name="a.vb"> Class b Public Sub New(ParamArray t() As Integer) End Sub End Class Class d Inherits b Public Sub New() End Sub End Class </file> </compilation>) CompilationUtils.AssertNoErrors(compilation) End Sub <WorkItem(540629, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540629")> <Fact()> Public Sub BC30002ERR_UndefinedType1() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="InvalidModuleAttribute1"> <file name="a.vb"><![CDATA[ Imports System Class Outer <AttributeUsage(AttributeTargets.All)> Class MyAttribute Inherits Attribute End Class End Class <MyAttribute()> Class Test End Class ]]></file> </compilation>). VerifyDiagnostics(Diagnostic(ERRID.ERR_UndefinedType1, "MyAttribute").WithArguments("MyAttribute")) End Sub <Fact()> Public Sub BC30020ERR_IsOperatorRequiresReferenceTypes1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Public Structure zzz Shared Sub Main() Dim a As New yyy Dim b As New yyy System.Console.WriteLine(a Is b) b = a System.Console.WriteLine(a Is b) End Sub End Structure Public Structure yyy Public i As Integer Public Sub abc() System.Console.WriteLine(i) End Sub End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30020: 'Is' operator does not accept operands of type 'yyy'. Operands must be reference or nullable types. System.Console.WriteLine(a Is b) ~ BC30020: 'Is' operator does not accept operands of type 'yyy'. Operands must be reference or nullable types. System.Console.WriteLine(a Is b) ~ BC30020: 'Is' operator does not accept operands of type 'yyy'. Operands must be reference or nullable types. System.Console.WriteLine(a Is b) ~ BC30020: 'Is' operator does not accept operands of type 'yyy'. Operands must be reference or nullable types. System.Console.WriteLine(a Is b) ~ </expected>) End Sub <Fact()> Public Sub BC30020ERR_IsOperatorRequiresReferenceTypes1_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Interface I End Interface Class A End Class Class B(Of T As Structure) End Class Class C Shared Sub M1(Of T1)(_1 As T1) If _1 Is Nothing Then End If If Nothing Is _1 Then End If End Sub Shared Sub M2(Of T2 As Class)(_2 As T2) If _2 Is Nothing Then End If If Nothing Is _2 Then End If End Sub Shared Sub M3(Of T3 As Structure)(_3 As T3) If _3 Is Nothing Then End If If Nothing Is _3 Then End If End Sub Shared Sub M4(Of T4 As New)(_4 As T4) If _4 Is Nothing Then End If If Nothing Is _4 Then End If End Sub Shared Sub M5(Of T5 As I)(_5 As T5) If _5 Is Nothing Then End If If Nothing Is _5 Then End If End Sub Shared Sub M6(Of T6 As A)(_6 As T6) If _6 Is Nothing Then End If If Nothing Is _6 Then End If End Sub Shared Sub M7(Of T7 As U, U)(_7 As T7) If _7 Is Nothing Then End If If Nothing Is _7 Then End If End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30020: 'Is' operator does not accept operands of type 'T3'. Operands must be reference or nullable types. If _3 Is Nothing Then ~~ BC30020: 'Is' operator does not accept operands of type 'T3'. Operands must be reference or nullable types. If Nothing Is _3 Then ~~ </expected>) End Sub <Fact()> Public Sub BC30029ERR_CantRaiseBaseEvent() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="CantRaiseBaseEvent"> <file name="a.vb"> Option Explicit On Class class1 Public Event MyEvent() End Class Class class2 Inherits class1 Sub RaiseEvt() 'COMPILEERROR: BC30029,"MyEvent" RaiseEvent MyEvent() End Sub End Class </file> </compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_CantRaiseBaseEvent, "MyEvent")) End Sub <Fact()> Public Sub BC30030ERR_TryWithoutCatchOrFinally() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="TryWithoutCatchOrFinally"> <file name="a.vb"> Module M1 Sub Scen1() 'COMPILEERROR: BC30030, "Try" Try End Try End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30030: Try must have at least one 'Catch' or a 'Finally'. Try ~~~ </expected>) End Sub <Fact()> Public Sub BC30038ERR_StrictDisallowsObjectOperand1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="StrictDisallowsObjectOperand1"> <file name="a.vb"> Imports System Structure myStruct1 shared result = New Guid() And New Guid() End structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30452: Operator 'And' is not defined for types 'Guid' and 'Guid'. shared result = New Guid() And New Guid() ~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30038ERR_StrictDisallowsObjectOperand1_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="StrictDisallowsObjectOperand1"> <file name="a.vb"> Option Infer Off option Strict on Structure myStruct1 sub foo() Dim x1$ = "hi" Dim [dim] = "hi" &amp; "hello" Dim x31 As integer = x1 &amp; [dim] end sub End structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30209: Option Strict On requires all variable declarations to have an 'As' clause. Dim [dim] = "hi" &amp; "hello" ~~~~~ BC30038: Option Strict On prohibits operands of type Object for operator '&amp;'. Dim x31 As integer = x1 &amp; [dim] ~~~~~ </expected>) End Sub <Fact()> Public Sub BC30038ERR_StrictDisallowsObjectOperand1_1a() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="StrictDisallowsObjectOperand1"> <file name="a.vb"> <![CDATA[ option Strict on Structure myStruct1 sub foo() Dim x1$ = 33 & 2.34 'No inference here end sub End structure ]]> </file> </compilation>) AssertTheseEmitDiagnostics(compilation, <expected><![CDATA[ BC35000: Requested operation is not available because the runtime library function 'Microsoft.VisualBasic.CompilerServices.Conversions.ToString' is not defined. Dim x1$ = 33 & 2.34 'No inference here ~~ BC35000: Requested operation is not available because the runtime library function 'Microsoft.VisualBasic.CompilerServices.Conversions.ToString' is not defined. Dim x1$ = 33 & 2.34 'No inference here ~~~~ ]]></expected>) End Sub <Fact()> Public Sub BC30039ERR_LoopControlMustNotBeProperty() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Module M Sub M() For <x/>.@a = "" To "" Next End Sub End Module ]]></file> </compilation>, references:=XmlReferences) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC30039: Loop control variable cannot be a property or a late-bound indexed array. For <x/>.@a = "" To "" ~~~~~~~ BC30337: 'For' loop control variable cannot be of type 'String' because the type does not support the required operators. For <x/>.@a = "" To "" ~~~~~~~ ]]></errors>) End Sub <Fact()> Public Sub BC30039ERR_LoopControlMustNotBeProperty_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System Class C Property P() As Integer Dim F As Integer Sub Method1(A As Integer, ByRef B As Integer) ' error For Each P In {1} Next ' warning For Each F In {2} Next For Each Me.F In {3} Next For Each A In {4} Next For Each B In {5} Next End Sub Shared Sub Main() End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30039: Loop control variable cannot be a property or a late-bound indexed array. For Each P In {1} ~ </expected>) End Sub <Fact()> Public Sub BC30039ERR_LoopControlMustNotBeProperty_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Option Strict Off Option Infer On Public Class MyClass1 Public Property z As Integer Public Shared Sub Main() End Sub Public Sub Foo() For z = 1 To 10 Next For x = 1 To z Step z Next End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30039: Loop control variable cannot be a property or a late-bound indexed array. For z = 1 To 10 ~ </expected>) End Sub <Fact(), WorkItem(545641, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545641")> Public Sub MissingLatebindingHelpers() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class Program Shared Sub Main() Dim Result As Object For Result = 1 To 2 Next End Sub End Class </file> </compilation>) AssertTheseEmitDiagnostics(compilation, <expected> BC35000: Requested operation is not available because the runtime library function 'Microsoft.VisualBasic.CompilerServices.ObjectFlowControl+ForLoopControl.ForLoopInitObj' is not defined. For Result = 1 To 2 ~~~~~~~~~~~~~~~~~~~~ BC35000: Requested operation is not available because the runtime library function 'Microsoft.VisualBasic.CompilerServices.ObjectFlowControl+ForLoopControl.ForNextCheckObj' is not defined. For Result = 1 To 2 ~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub MissingLatebindingHelpersObjectFor() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Option Strict Off Imports System Class Program Shared Sub Main() Dim obj As Object = New cls1 obj.P1 = 42 ' assignment (Set) obj.P1() ' side-effect (Call) Console.WriteLine(obj.P1) ' value (Get) End Sub Class cls1 Private _p1 As Integer Public Property p1 As Integer Get Console.Write("Get") Return _p1 End Get Set(value As Integer) Console.Write("Set") _p1 = value End Set End Property End Class End Class </file> </compilation>) AssertTheseEmitDiagnostics(compilation, <expected> BC35000: Requested operation is not available because the runtime library function 'Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateSet' is not defined. obj.P1 = 42 ' assignment (Set) ~~~~~~~~~~~ BC35000: Requested operation is not available because the runtime library function 'Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateCall' is not defined. obj.P1() ' side-effect (Call) ~~~~~~ BC35000: Requested operation is not available because the runtime library function 'Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateGet' is not defined. Console.WriteLine(obj.P1) ' value (Get) ~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30043ERR_UseOfKeywordNotInInstanceMethod1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="UseOfKeywordNotInInstanceMethod1"> <file name="a.vb"> Class [ident1] Public k As Short Public Shared Function foo2() As String 'COMPILEERROR: BC30043, "Me" Me.k = 333 Return Nothing End Function End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30043: 'Me' is valid only within an instance method. Me.k = 333 ~~ </expected>) End Sub <Fact()> Public Sub BC30043ERR_UseOfKeywordNotInInstanceMethod1_WithinFieldInitializers() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="FieldsUsingMe"> <file name="a.vb"> Option strict on imports system Class C1 private f1 as integer = 21 private shared f2 as integer = Me.f1 + 1 End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30043: 'Me' is valid only within an instance method. private shared f2 as integer = Me.f1 + 1 ~~ </expected>) End Sub <Fact()> Public Sub BC30043ERR_UseOfKeywordNotInInstanceMethod1_MeInAttribute() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BC30043ERR_UseOfKeywordNotInInstanceMethod1_MeInAttribute"> <file name="a.vb"> Option Strict On Imports System Imports System.Reflection Imports System.Runtime.InteropServices &lt;Assembly: AssemblyCulture(Me.AAA)&gt; &lt;StructLayout(Me.AAA)&gt; Structure S1 End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30043: 'Me' is valid only within an instance method. &lt;Assembly: AssemblyCulture(Me.AAA)&gt; ~~ BC30043: 'Me' is valid only within an instance method. &lt;StructLayout(Me.AAA)&gt; ~~ </expected>) End Sub <Fact()> Public Sub BC30043ERR_UseOfKeywordNotInInstanceMethod1_MyBaseInAttribute() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BC30043ERR_UseOfKeywordNotInInstanceMethod1_MyBaseInAttribute"> <file name="a.vb"> Option Strict On Imports System Imports System.Reflection Imports System.Runtime.InteropServices &lt;Assembly: AssemblyCulture(MyBase.AAA)&gt; &lt;StructLayout(MyBase.AAA)&gt; Structure S1 End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30043: 'MyBase' is valid only within an instance method. &lt;Assembly: AssemblyCulture(MyBase.AAA)&gt; ~~~~~~ BC30043: 'MyBase' is valid only within an instance method. &lt;StructLayout(MyBase.AAA)&gt; ~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30043ERR_UseOfKeywordNotInInstanceMethod1_MyClassInAttribute() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BC30043ERR_UseOfKeywordNotInInstanceMethod1_MyClassInAttribute"> <file name="a.vb"> Option Strict On Imports System Imports System.Reflection Imports System.Runtime.InteropServices &lt;Assembly: AssemblyCulture(MyClass.AAA)&gt; &lt;StructLayout(MyClass.AAA)&gt; Structure S1 End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30043: 'MyClass' is valid only within an instance method. &lt;Assembly: AssemblyCulture(MyClass.AAA)&gt; ~~~~~~~ BC30043: 'MyClass' is valid only within an instance method. &lt;StructLayout(MyClass.AAA)&gt; ~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30043ERR_UseOfKeywordNotInInstanceMethod1_WithinFieldInitializers_MyBase() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BC30043ERR_UseOfKeywordNotInInstanceMethod1_WithinFieldInitializers_MyBase"> <file name="a.vb"> Option strict on imports system Class Base Shared Function GetBar(i As Integer) As Integer Return Nothing End Function End Class Class C2 Inherits Base Public Shared f As Func(Of Func(Of Integer, Integer)) = Function() New Func(Of Integer, Integer)(AddressOf MyBase.GetBar) Public Shared Property P As Integer = MyBase.GetBar(1) End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30043: 'MyBase' is valid only within an instance method. Function() New Func(Of Integer, Integer)(AddressOf MyBase.GetBar) ~~~~~~ BC30043: 'MyBase' is valid only within an instance method. Public Shared Property P As Integer = MyBase.GetBar(1) ~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30043ERR_UseOfKeywordNotInInstanceMethod1_WithinFieldInitializers_MyClass() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BC30043ERR_UseOfKeywordNotInInstanceMethod1_WithinFieldInitializers_MyClass"> <file name="a.vb"> Option strict on imports system Class C2 Shared Function GetBar(i As Integer) As Integer Return Nothing End Function Public Shared f As Func(Of Func(Of Integer, Integer)) = Function() New Func(Of Integer, Integer)(AddressOf MyClass.GetBar) Public Shared Property P As Integer = MyClass.GetBar(1) End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30043: 'MyClass' is valid only within an instance method. Function() New Func(Of Integer, Integer)(AddressOf MyClass.GetBar) ~~~~~~~ BC30043: 'MyClass' is valid only within an instance method. Public Shared Property P As Integer = MyClass.GetBar(1) ~~~~~~~ </expected>) End Sub <WorkItem(542958, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542958")> <Fact()> Public Sub BC30043ERR_UseOfKeywordNotInInstanceMethod1_MyClassInAttribute_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BC30043ERR_UseOfKeywordNotInInstanceMethod1_MyClassInAttribute"> <file name="a.vb"> Option Strict On Imports System Imports System.Runtime.InteropServices Public Class S1 Const str As String = "" &lt;MyAttribute(MyClass.color.blue)&gt; Sub foo() End Sub Shared Sub main() End Sub Enum color blue End Enum End Class Class MyAttribute Inherits Attribute Sub New(str As S1.color) End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30043: 'MyClass' is valid only within an instance method. &lt;MyAttribute(MyClass.color.blue)&gt; ~~~~~~~ </expected>) End Sub <WorkItem(542958, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542958")> <Fact()> Public Sub BC30043ERR_UseOfKeywordNotInInstanceMethod1_MeInAttribute_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BC30043ERR_UseOfKeywordNotInInstanceMethod1_MeInAttribute"> <file name="a.vb"> Option Strict On Imports System Imports System.Runtime.InteropServices Public Class S1 Const str As String = "" &lt;MyAttribute(Me.color.blue)&gt; Sub foo() End Sub Shared Sub main() End Sub Enum color blue End Enum End Class Class MyAttribute Inherits Attribute Sub New(str As S1.color) End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30043: 'Me' is valid only within an instance method. &lt;MyAttribute(Me.color.blue)&gt; ~~ </expected>) End Sub <WorkItem(542958, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542958")> <Fact()> Public Sub BC30043ERR_UseOfKeywordNotInInstanceMethod1_MyBaseInAttribute_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BC30043ERR_UseOfKeywordNotInInstanceMethod1_MyBaseInAttribute"> <file name="a.vb"> Option Strict On Imports System Imports System.Runtime.InteropServices Public Class BaseClass Enum color blue End Enum End Class Public Class S1 Inherits BaseClass &lt;MyAttribute(MyBase.color.blue)&gt; Sub foo() End Sub Shared Sub main() End Sub End Class Class MyAttribute Inherits Attribute Sub New(x As S1.color) End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30043: 'MyBase' is valid only within an instance method. &lt;MyAttribute(MyBase.color.blue)&gt; ~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30044ERR_UseOfKeywordFromStructure1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="UseOfKeywordFromStructure1"> <file name="a.vb"> Module M1 Structure S Public Overrides Function ToString() As String Return MyBase.ToString() End Function End Structure End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30044: 'MyBase' is not valid within a structure. Return MyBase.ToString() ~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30045ERR_BadAttributeConstructor1() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="BadAttributeConstructor1"> <file name="a.vb"><![CDATA[ Imports System Module M1 Class myattr1 Inherits Attribute Sub New(ByVal o() As c1) Me.o = o End Sub Public o() As c1 End Class Public Class c1 End Class <myattr1(Nothing)> Class Scen18 End Class Class myattr2 Inherits Attribute Sub New(ByVal o() As delegate1) Me.o = o End Sub Public o() As delegate1 End Class Delegate Sub delegate1() <myattr2(Nothing)> Class Scen20 End Class End Module ]]></file> </compilation>). VerifyDiagnostics(Diagnostic(ERRID.ERR_BadAttributeConstructor1, "myattr1").WithArguments("M1.c1()"), Diagnostic(ERRID.ERR_BadAttributeConstructor1, "myattr2").WithArguments("M1.delegate1()")) Dim scen18 = compilation.GlobalNamespace.GetTypeMember("M1").GetTypeMember("Scen18") Dim attribute = scen18.GetAttributes().Single() Assert.Equal("M1.myattr1(Nothing)", attribute.ToString()) Dim argument = attribute.CommonConstructorArguments(0) Assert.Null(argument.Type) End Sub <Fact, WorkItem(3380, "DevDiv_Projects/Roslyn")> Public Sub BC30046ERR_ParamArrayWithOptArgs() CreateCompilationWithMscorlib40(<compilation name="ERR_ParamArrayWithOptArgs"> <file name="a.vb"><![CDATA[ Class C1 Shared Sub Main() End Sub sub abc( optional k as string = "hi", paramarray s() as integer ) End Sub End Class ]]></file> </compilation>).VerifyDiagnostics( Diagnostic(ERRID.ERR_ParamArrayWithOptArgs, "s")) End Sub <Fact()> Public Sub BC30049ERR_ExpectedArray1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ExpectedArray1"> <file name="a.vb"> Module M1 Sub Main() Dim boolVar_12 As Boolean 'COMPILEERROR: BC30049, "boolVar_12" ReDim boolVar_12(120) 'COMPILEERROR: BC30049, "boolVar_12", BC30811, "as" ReDim boolVar_12(120, 130) End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30049: 'Redim' statement requires an array. ReDim boolVar_12(120) ~~~~~~~~~~ BC30049: 'Redim' statement requires an array. ReDim boolVar_12(120, 130) ~~~~~~~~~~ </expected>) End Sub <WorkItem(542209, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542209")> <Fact()> Public Sub BC30052ERR_ArrayRankLimit() CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="ArrayRankLimit"> <file name="a.vb"> Public Class C1 Dim S1(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32) As Byte Dim S2(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33) As Byte End Class </file> </compilation>).VerifyDiagnostics( Diagnostic(ERRID.ERR_ArrayRankLimit, "(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33)")) End Sub <Fact, WorkItem(2424, "https://github.com/dotnet/roslyn/issues/2424")> Public Sub BC30053ERR_AsNewArray_01() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="AsNewArray"> <file name="a.vb"> Module M1 Sub Foo() Dim c() As New System.Exception Dim d(), e() As New System.Exception Dim f(), g As New System.Exception Dim h, i() As New System.Exception End Sub Dim x() As New System.Exception Dim y(), z() As New System.Exception Dim u(), v As New System.Exception Dim w, q() As New System.Exception End Module </file> </compilation>) Dim expectedErrors1 = <errors> BC30053: Arrays cannot be declared with 'New'. Dim c() As New System.Exception ~~~ BC30053: Arrays cannot be declared with 'New'. Dim d(), e() As New System.Exception ~~~ BC30053: Arrays cannot be declared with 'New'. Dim d(), e() As New System.Exception ~~~ BC30053: Arrays cannot be declared with 'New'. Dim f(), g As New System.Exception ~~~ BC30053: Arrays cannot be declared with 'New'. Dim h, i() As New System.Exception ~~~ BC30053: Arrays cannot be declared with 'New'. Dim x() As New System.Exception ~~~ BC30053: Arrays cannot be declared with 'New'. Dim y(), z() As New System.Exception ~~~ BC30053: Arrays cannot be declared with 'New'. Dim y(), z() As New System.Exception ~~~ BC30053: Arrays cannot be declared with 'New'. Dim u(), v As New System.Exception ~~~ BC30053: Arrays cannot be declared with 'New'. Dim w, q() As New System.Exception ~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact, WorkItem(2424, "https://github.com/dotnet/roslyn/issues/2424")> Public Sub BC30053ERR_AsNewArray_02() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="AsNewArray"> <file name="a.vb"> Module M1 Sub Foo() Dim c(1) As New System.Exception Dim d(1), e(1) As New System.Exception Dim f(1), g As New System.Exception Dim h, i(1) As New System.Exception End Sub Dim x(1) As New System.Exception Dim y(1), z(1) As New System.Exception Dim u(1), v As New System.Exception Dim w, q(1) As New System.Exception End Module </file> </compilation>) Dim expectedErrors1 = <errors> BC30053: Arrays cannot be declared with 'New'. Dim c(1) As New System.Exception ~~~ BC30053: Arrays cannot be declared with 'New'. Dim d(1), e(1) As New System.Exception ~~~ BC30053: Arrays cannot be declared with 'New'. Dim d(1), e(1) As New System.Exception ~~~ BC30053: Arrays cannot be declared with 'New'. Dim f(1), g As New System.Exception ~~~ BC30053: Arrays cannot be declared with 'New'. Dim h, i(1) As New System.Exception ~~~ BC30053: Arrays cannot be declared with 'New'. Dim x(1) As New System.Exception ~~~~ BC30053: Arrays cannot be declared with 'New'. Dim y(1), z(1) As New System.Exception ~~~~ BC30053: Arrays cannot be declared with 'New'. Dim y(1), z(1) As New System.Exception ~~~~ BC30053: Arrays cannot be declared with 'New'. Dim u(1), v As New System.Exception ~~~~ BC30053: Arrays cannot be declared with 'New'. Dim w, q(1) As New System.Exception ~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC30057ERR_TooManyArgs1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="TooManyArgs1"> <file name="a.vb"> Module M1 Sub Main() test("CC", 15, 45) End Sub Sub test(ByVal name As String, ByVal age As Integer) End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30057: Too many arguments to 'Public Sub test(name As String, age As Integer)'. test("CC", 15, 45) ~~ </expected>) End Sub ' 30057 is better here <WorkItem(528720, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528720")> <Fact()> Public Sub BC30057ERR_TooManyArgs1_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ConstructorNotFound1"> <file name="a.vb"> Module M1 Sub FOO() Dim DynamicArray_2() As Byte Dim DynamicArray_3() As Long 'COMPILEERROR: BC30251, "New Byte(1, 2, 3, 4)" DynamicArray_2 = New Byte(1, 2, 3, 4) 'COMPILEERROR: BC30251, "New Byte(1)" DynamicArray_3 = New Long(1) Exit Sub End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30057: Too many arguments to 'Public Sub New()'. DynamicArray_2 = New Byte(1, 2, 3, 4) ~ BC30057: Too many arguments to 'Public Sub New()'. DynamicArray_3 = New Long(1) ~ </expected>) End Sub <Fact()> Public Sub BC30057ERR_TooManyArgs1_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ConstructorNotFound1"> <file name="a.vb"> Option Infer On Imports System Module Module1 Sub Main() Dim arr16 As New Integer(2, 3) { {1, 2}, {2, 1} }' Invalid End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30057: Too many arguments to 'Public Sub New()'. Dim arr16 As New Integer(2, 3) { {1, 2}, {2, 1} }' Invalid ~ BC30205: End of statement expected. Dim arr16 As New Integer(2, 3) { {1, 2}, {2, 1} }' Invalid ~ </expected>) End Sub <Fact()> Public Sub BC30057ERR_TooManyArgs1_3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ConstructorNotFound1"> <file name="a.vb"> Option Strict On Imports System Module Module1 Sub Main() Dim myArray8 As Integer(,) = New Integer(,) 1,2,3,4,5 End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30057: Too many arguments to 'Public Sub New()'. Dim myArray8 As Integer(,) = New Integer(,) 1,2,3,4,5 ~ BC30205: End of statement expected. Dim myArray8 As Integer(,) = New Integer(,) 1,2,3,4,5 ~ </expected>) End Sub <Fact()> Public Sub BC30059ERR_RequiredConstExpr_fields() Dim source = <compilation> <file name="a.vb"> Option Strict On option Infer On imports system Imports microsoft.visualbasic.strings Class A Public Const X As Integer = 1 End Class Class B Sub New(x As Action) End Sub Sub New(x As Integer) End Sub Public Const X As Integer = 2 End Class Class C Sub New(x As Integer) End Sub Public Const X As Integer = 3 End Class Class D Sub New(x As Func(Of Integer)) End Sub Public Const X As Integer = 4 End Class Class C1 Public Delegate Sub SubDel(p as integer) Public Shared Sub foo(p as Integer) Console.WriteLine("DelegateField works :) " + p.ToString()) End Sub public shared function f() as integer return 23 end function ' should work because of const propagation public const f1 as integer = 1 + 1 '' should not work Public const f2 as SubDel = AddressOf C1.foo public const f3 as integer = C1.f() public const f4,f5 as integer = C1.f() '' should also give a BC30059 for inferred types public const f6 as object = new C1() public const f7 = new C1() public const f8 as integer = Asc(chrW(255)) ' > 127 are not const public const f9() as integer = new integer() {1, 2} public const f10 = new integer() {1, 2} public const f11 = GetType(Integer) public const f12 as system.type = GetType(Integer) public const f13 as integer = cint(cint(cbyte("1"))) public const f14 as integer = cint(cint(cbyte(1))) ' works public const f15 as long = clng(cint(cbyte("1"))) public const f16 as long = clng(cint(cbyte(1))) ' works public const ValueWorks1 as Integer = new C(23).X public const ValueWorks2 as Integer = new A().X public const ValueWorks3 as Integer = 23 + new A().X public const ValueWorks4 as Integer = if(nothing, 23) public const ValueWorks5 as Integer = if(23 = 42, 23, 42) public const ValueWorks6 as Integer = if(new A().X = 0, 23, 42) public const ValueWorks7 as Integer = if(new A(), nothing).X public const ValueWorks8 as Integer = if(23 = 42, 23, new A().X) public const ValueWorks9 as Integer = if(23 = 42, new A().X, 42) public const ValueWorks10 as Integer = CType("12", Integer).MaxValue ' needs option strict off ... public const ValueWorks11 as Integer = New B(Sub() Exit Sub).X public const ValueWorks12 = New D(Function() 23).X public const ValueDoesntWork1 as Integer = f() public const ValueDoesntWork2 as Integer = 1 + f() public const ValueDoesntWork3 as Integer = f() + 1 Public shared Sub Main(args() as string) End sub End Class </file> </compilation> Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) CompilationUtils.AssertTheseDiagnostics(c1, <expected> BC30424: Constants must be of an intrinsic or enumerated type, not a class, structure, type parameter, or array type. Public const f2 as SubDel = AddressOf C1.foo ~~~~~~ BC30059: Constant expression is required. public const f3 as integer = C1.f() ~~~~~~ BC30671: Explicit initialization is not permitted with multiple variables declared with a single type specifier. public const f4,f5 as integer = C1.f() ~~~~~~~~~~~~~~~~~~~~~~~~~ BC30059: Constant expression is required. public const f4,f5 as integer = C1.f() ~~~~~~ BC30059: Constant expression is required. public const f6 as object = new C1() ~~~~~~~~ BC30059: Constant expression is required. public const f7 = new C1() ~~~~~~~~ BC30059: Constant expression is required. public const f8 as integer = Asc(chrW(255)) ' > 127 are not const ~~~~~~~~~~~~~~ BC30424: Constants must be of an intrinsic or enumerated type, not a class, structure, type parameter, or array type. public const f9() as integer = new integer() {1, 2} ~~ BC30059: Constant expression is required. public const f10 = new integer() {1, 2} ~~~~~~~~~~~~~~~~~~~~ BC30059: Constant expression is required. public const f11 = GetType(Integer) ~~~~~~~~~~~~~~~~ BC30424: Constants must be of an intrinsic or enumerated type, not a class, structure, type parameter, or array type. public const f12 as system.type = GetType(Integer) ~~~~~~~~~~~ BC30060: Conversion from 'String' to 'Byte' cannot occur in a constant expression. public const f13 as integer = cint(cint(cbyte("1"))) ~~~ BC30060: Conversion from 'String' to 'Byte' cannot occur in a constant expression. public const f15 as long = clng(cint(cbyte("1"))) ~~~ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. public const ValueWorks1 as Integer = new C(23).X ~~~~~~~~~~~ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. public const ValueWorks2 as Integer = new A().X ~~~~~~~~~ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. public const ValueWorks3 as Integer = 23 + new A().X ~~~~~~~~~ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. public const ValueWorks6 as Integer = if(new A().X = 0, 23, 42) ~~~~~~~~~ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. public const ValueWorks7 as Integer = if(new A(), nothing).X ~~~~~~~~~~~~~~~~~~~~~~ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. public const ValueWorks8 as Integer = if(23 = 42, 23, new A().X) ~~~~~~~~~ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. public const ValueWorks9 as Integer = if(23 = 42, new A().X, 42) ~~~~~~~~~ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. public const ValueWorks10 as Integer = CType("12", Integer).MaxValue ' needs option strict off ... ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. public const ValueWorks11 as Integer = New B(Sub() Exit Sub).X ~~~~~~~~~~~~~~~~~~~~~~~ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. public const ValueWorks12 = New D(Function() 23).X ~~~~~~~~~~~~~~~~~~~~~~ BC30059: Constant expression is required. public const ValueDoesntWork1 as Integer = f() ~~~ BC30059: Constant expression is required. public const ValueDoesntWork2 as Integer = 1 + f() ~~~ BC30059: Constant expression is required. public const ValueDoesntWork3 as Integer = f() + 1 ~~~ </expected>) End Sub ' The non-constant initializer should result in ' a single error, even if declaring multiple fields. <Fact()> Public Sub BC30059ERR_RequiredConstExpr_2() Dim source = <compilation> <file name="a.vb"> Option Strict On Module M Const A, B As Integer = F() Function F() As Integer Return 0 End Function End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) compilation.AssertTheseDiagnostics( <expected> BC30671: Explicit initialization is not permitted with multiple variables declared with a single type specifier. Const A, B As Integer = F() ~~~~~~~~~~~~~~~~~~~~~ BC30059: Constant expression is required. Const A, B As Integer = F() ~~~ </expected>) End Sub <Fact()> Public Sub BC30059ERR_RequiredConstExpr_locals() Dim source = <compilation> <file name="a.vb"> Option strict off imports system Imports microsoft.visualbasic.strings Class A Public Const X As Integer = 1 End Class Class B Sub New(x As Action) End Sub Sub New(x As Integer) End Sub Public Const X As Integer = 2 End Class Class C Sub New(x As Integer) End Sub Public Const X As Integer = 3 End Class Class D Sub New(x As Func(Of Integer)) End Sub Public Const X As Integer = 4 End Class Class C1 Public Delegate Sub SubDel(p as integer) Public Shared Sub foo(p as Integer) Console.WriteLine("DelegateField works :) " + p.ToString()) End Sub public shared function f() as integer return 23 end function Public Sub Main() ' should work because of const propagation const f1 as integer = 1 + 1 ' should not work const f2 as SubDel = AddressOf C1.foo const f3 as integer = C1.f() const f4,f5 as integer = C1.f() ' should also give a BC30059 for inferred types const f6 as object = new C1() const f7 = new C1() const f8 as integer = Asc(chrW(255)) ' > 127 are not const const f9() as integer = new integer() {1, 2} const f10 = new integer() {1, 2} const f11 = GetType(Integer) const f12 as system.type = GetType(Integer) const f13 as integer = cint(cint(cbyte("1"))) const f14 as integer = cint(cint(cbyte(1))) ' works const f15 as long = clng(cint(cbyte("1"))) const f16 as long = clng(cint(cbyte(1))) ' works const ValueWorks1 as Integer = new C(23).X const ValueWorks2 as Integer = new A().X const ValueWorks3 as Integer = 23 + new A().X const ValueWorks4 as Integer = if(nothing, 23) const ValueWorks5 as Integer = if(23 = 42, 23, 42) const ValueWorks6 as Integer = if(new A().X = 0, 23, 42) const ValueWorks7 as Integer = if(new A(), nothing).X const ValueWorks8 as Integer = if(23 = 42, 23, new A().X) const ValueWorks9 as Integer = if(23 = 42, new A().X, 42) const ValueWorks10 as Integer = CType("12", Integer).MaxValue ' needs option strict off ... const ValueWorks11 as Integer = New B(Sub() Exit Sub).X const ValueWorks12 as Integer = New D(Function() 23).X const ValueDoesntWork1 as Integer = f() Dim makeThemUsed as long = f1 + f3 + f4 + f5 + f8 + f13 + f14 + f15 + f16 + ValueWorks1 + ValueWorks2 + ValueWorks3 + ValueWorks4 + ValueWorks5 + ValueWorks6 + ValueWorks7 + ValueWorks8 + ValueWorks9 + ValueWorks10 + ValueWorks11 + ValueWorks12 End Sub End Class </file> </compilation> Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) CompilationUtils.AssertTheseDiagnostics(c1, <expected> BC30424: Constants must be of an intrinsic or enumerated type, not a class, structure, type parameter, or array type. const f2 as SubDel = AddressOf C1.foo ~~~~~~ BC30059: Constant expression is required. const f3 as integer = C1.f() ~~~~~~ BC30438: Constants must have a value. const f4,f5 as integer = C1.f() ~~ BC30671: Explicit initialization is not permitted with multiple variables declared with a single type specifier. const f4,f5 as integer = C1.f() ~~~~~~~~~~~~~~~~~~~~~~~~~ BC30059: Constant expression is required. const f4,f5 as integer = C1.f() ~~~~~~ BC30059: Constant expression is required. const f6 as object = new C1() ~~~~~~~~ BC30059: Constant expression is required. const f7 = new C1() ~~~~~~~~ BC30059: Constant expression is required. const f8 as integer = Asc(chrW(255)) ' > 127 are not const ~~~~~~~~~~~~~~ BC30424: Constants must be of an intrinsic or enumerated type, not a class, structure, type parameter, or array type. const f9() as integer = new integer() {1, 2} ~~~~ BC30059: Constant expression is required. const f10 = new integer() {1, 2} ~~~~~~~~~~~~~~~~~~~~ BC30059: Constant expression is required. const f11 = GetType(Integer) ~~~~~~~~~~~~~~~~ BC30424: Constants must be of an intrinsic or enumerated type, not a class, structure, type parameter, or array type. const f12 as system.type = GetType(Integer) ~~~~~~~~~~~ BC30060: Conversion from 'String' to 'Byte' cannot occur in a constant expression. const f13 as integer = cint(cint(cbyte("1"))) ~~~ BC30060: Conversion from 'String' to 'Byte' cannot occur in a constant expression. const f15 as long = clng(cint(cbyte("1"))) ~~~ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. const ValueWorks1 as Integer = new C(23).X ~~~~~~~~~~~ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. const ValueWorks2 as Integer = new A().X ~~~~~~~~~ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. const ValueWorks3 as Integer = 23 + new A().X ~~~~~~~~~ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. const ValueWorks6 as Integer = if(new A().X = 0, 23, 42) ~~~~~~~~~ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. const ValueWorks7 as Integer = if(new A(), nothing).X ~~~~~~~~~~~~~~~~~~~~~~ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. const ValueWorks8 as Integer = if(23 = 42, 23, new A().X) ~~~~~~~~~ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. const ValueWorks9 as Integer = if(23 = 42, new A().X, 42) ~~~~~~~~~ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. const ValueWorks10 as Integer = CType("12", Integer).MaxValue ' needs option strict off ... ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. const ValueWorks11 as Integer = New B(Sub() Exit Sub).X ~~~~~~~~~~~~~~~~~~~~~~~ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. const ValueWorks12 as Integer = New D(Function() 23).X ~~~~~~~~~~~~~~~~~~~~~~ BC30059: Constant expression is required. const ValueDoesntWork1 as Integer = f() ~~~ </expected>) End Sub <Fact()> Public Sub BC30059ERR_RequiredConstExpr_3() Dim source = <compilation> <file name="a.vb"> Option strict on Option Infer On imports system Class C1 Public Delegate Sub SubDel(p as integer) Public Shared Sub foo(p as Integer) Console.WriteLine("DelegateField works :) " + p.ToString()) End Sub public shared function f() as integer return 23 end function public shared function g(p as integer) as integer return 23 end function ' should not work Public const f2 = AddressOf C1.foo Public const f3 as object = AddressOf C1.foo public const f4 as integer = 1 + 2 + 3 + f() public const f5 as boolean = not (f() = 23) public const f6 as integer = f() + f() + f() public const f7 as integer = g(1 + 2 + f()) Public shared Sub Main(args() as string) End sub End Class </file> </compilation> Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) CompilationUtils.AssertTheseDiagnostics(c1, <expected> BC30059: Constant expression is required. Public const f2 = AddressOf C1.foo ~~~~~~~~~~~~~~~~ BC30059: Constant expression is required. Public const f3 as object = AddressOf C1.foo ~~~~~~~~~~~~~~~~ BC30059: Constant expression is required. public const f4 as integer = 1 + 2 + 3 + f() ~~~ BC30059: Constant expression is required. public const f5 as boolean = not (f() = 23) ~~~ BC30059: Constant expression is required. public const f6 as integer = f() + f() + f() ~~~ BC30059: Constant expression is required. public const f6 as integer = f() + f() + f() ~~~ BC30059: Constant expression is required. public const f6 as integer = f() + f() + f() ~~~ BC30059: Constant expression is required. public const f7 as integer = g(1 + 2 + f()) ~~~~~~~~~~~~~~ </expected>) End Sub <Fact> Public Sub TestArrayLocalConst() Dim source = <compilation> <file name="a.vb"> Imports System Module C Sub Main() Const A As Integer() = Nothing Console.Write(A) End Sub End Module </file> </compilation> Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) CompilationUtils.AssertTheseDiagnostics(c1, <expected> BC30424: Constants must be of an intrinsic or enumerated type, not a class, structure, type parameter, or array type. Const A As Integer() = Nothing ~ </expected>) End Sub <Fact()> Public Sub BC30059ERR_RequiredConstExpr_Attr() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="ERR_RequiredConstExpr_Attr"> <file name="at30059.vb"><![CDATA[ Imports System <AttributeUsage(AttributeTargets.All)> Public Class MyAttribute Inherits Attribute Public Sub New(p As ULong) End Sub End Class <My(Foo.FG)> Public Class Foo Public Shared FG As ULong = 12345 Public Function F() As Byte Dim x As Byte = 1 Return x End Function End Class ]]></file> </compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_RequiredConstExpr, "Foo.FG")) End Sub <WorkItem(542967, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542967")> <Fact()> Public Sub BC30059ERR_RequiredConstExpr_QueryInAttr() CompilationUtils.CreateCompilationWithMscorlib40AndReferences( <compilation name="ERR_RequiredConstExpr_Attr"> <file name="at30059.vb"><![CDATA[ Imports System Imports System.Linq Class Program Const q As String = "" Sub Main(args As String()) End Sub <My((From x In q Select x).Count())> Shared Sub sum() End Sub End Class Class MyAttribute Inherits Attribute Sub New(s As Integer) End Sub End Class ]]></file> </compilation>, references:={Net40.SystemCore}).VerifyDiagnostics(Diagnostic(ERRID.ERR_RequiredConstExpr, "(From x In q Select x).Count()")) End Sub <WorkItem(542967, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542967")> <Fact()> Public Sub BC30059ERR_RequiredConstExpr_QueryInAttr_2() CompilationUtils.CreateCompilationWithMscorlib40AndReferences( <compilation name="ERR_RequiredConstExpr_Attr"> <file name="at30059.vb"><![CDATA[ Imports System Imports System.Linq Class Program Const q As String = "" Sub Main(args As String()) End Sub Public F1 As Object <My((From x In q Select F1).Count())> Shared Sub sum() End Sub End Class Class MyAttribute Inherits Attribute Sub New(s As Integer) End Sub End Class ]]></file> </compilation>, references:={Net40.SystemCore}).VerifyDiagnostics(Diagnostic(ERRID.ERR_BadInstanceMemberAccess, "F1")) End Sub <WorkItem(542967, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542967")> <Fact()> Public Sub BC30059ERR_RequiredConstExpr_QueryInAttr_3() CompilationUtils.CreateCompilationWithMscorlib40AndReferences( <compilation name="ERR_RequiredConstExpr_Attr"> <file name="at30059.vb"><![CDATA[ Imports System Imports System.Linq <My((From x In "s" Select x).Count())> Class Program Public F1 As Integer End Class <My((From x In "s" Select Program.F1).Count())> Class Program2 End Class Class MyAttribute Inherits Attribute Sub New(s As Integer) End Sub End Class ]]></file> </compilation>, references:={Net40.SystemCore}).VerifyDiagnostics({Diagnostic(ERRID.ERR_RequiredConstExpr, "(From x In ""s"" Select x).Count()"), Diagnostic(ERRID.ERR_ObjectReferenceNotSupplied, "Program.F1")}) End Sub <Fact()> Public Sub BC30059ERR_RequiredConstExpr_XmlEmbeddedExpression() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Module M Private Const F1 = Nothing Private Const F2 As String = "v2" Private Const F3 = <%= Nothing %> Private Const F4 = <%= "v4" %> Private Const F5 As String = <%= "v5" %> Private F6 As Object = <x a0=<%= "v0" %> a1=<%= F1 %> a2=<%= F2 %> a3=<%= F3 %> a4=<%= F4 %> a5=<%= F5 %>/> End Module ]]></file> </compilation>, references:=XmlReferences) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC30059: Constant expression is required. Private Const F3 = <%= Nothing %> ~~~~~~~~~~~~~~ BC31172: An embedded expression cannot be used here. Private Const F3 = <%= Nothing %> ~~~~~~~~~~~~~~ BC30059: Constant expression is required. Private Const F4 = <%= "v4" %> ~~~~~~~~~~~ BC31172: An embedded expression cannot be used here. Private Const F4 = <%= "v4" %> ~~~~~~~~~~~ BC30059: Constant expression is required. Private Const F5 As String = <%= "v5" %> ~~~~~~~~~~~ BC31172: An embedded expression cannot be used here. Private Const F5 As String = <%= "v5" %> ~~~~~~~~~~~ ]]></errors>) End Sub <Fact()> Public Sub BC30060ERR_RequiredConstConversion2() Dim source = <compilation> <file name="a.vb"> Option strict on imports system Class C1 ' should show issues public const f1 as integer = CInt("23") public const f2 as integer = CType("23", integer) public const f3 as byte = CType(300, byte) public const f4 as byte = CType(300, BORG) public const f5 as byte = 300 public const f6 as string = 23 public const f10 as date = CDate("November 04, 2008") public const f13 as decimal = Ctype("20100607",decimal) ' should not show issues public const f7 as integer = CInt(23) public const f8 as integer = CType(23, integer) public const f9 as byte = CType(254, byte) public const f11 as date = Ctype(#06/07/2010#,date) public const f12 as decimal = Ctype(20100607,decimal) Public shared Sub Main(args() as string) End sub End Class </file> </compilation> Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) CompilationUtils.AssertTheseDiagnostics(c1, <expected> BC30060: Conversion from 'String' to 'Integer' cannot occur in a constant expression. public const f1 as integer = CInt("23") ~~~~ BC30060: Conversion from 'String' to 'Integer' cannot occur in a constant expression. public const f2 as integer = CType("23", integer) ~~~~ BC30439: Constant expression not representable in type 'Byte'. public const f3 as byte = CType(300, byte) ~~~ BC30002: Type 'BORG' is not defined. public const f4 as byte = CType(300, BORG) ~~~~ BC30439: Constant expression not representable in type 'Byte'. public const f5 as byte = 300 ~~~ BC30512: Option Strict On disallows implicit conversions from 'Integer' to 'String'. public const f6 as string = 23 ~~ BC30060: Conversion from 'String' to 'Date' cannot occur in a constant expression. public const f10 as date = CDate("November 04, 2008") ~~~~~~~~~~~~~~~~~~~ BC30060: Conversion from 'String' to 'Decimal' cannot occur in a constant expression. public const f13 as decimal = Ctype("20100607",decimal) ~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30060ERR_RequiredConstConversion2_StrictOff() Dim source = <compilation> <file name="a.vb"> Option strict off imports system Class C1 public const f6 as string = 23 public const f7 as string = CType(23,string) Public shared Sub Main(args() as string) End sub End Class </file> </compilation> Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) CompilationUtils.AssertTheseDiagnostics(c1, <expected> BC30060: Conversion from 'Integer' to 'String' cannot occur in a constant expression. public const f6 as string = 23 ~~ BC30060: Conversion from 'Integer' to 'String' cannot occur in a constant expression. public const f7 as string = CType(23,string) ~~ </expected>) End Sub <Fact()> Public Sub BC30064ERR_ReadOnlyAssignment() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ReadOnlyAssignment"> <file name="a.vb"> Imports System Module M1 Class ReferenceType Implements IDisposable Dim dummy As Integer Public Sub Dispose() Implements System.IDisposable.Dispose End Sub End Class Class TestClass ReadOnly Name As String = "Cici" Sub test() Name = "string" ' variables declared in a using statement are considered read only as well Using a As New ReferenceType(), b As New ReferenceType() a = New ReferenceType() b = New ReferenceType() End Using End Sub End Class End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30064: 'ReadOnly' variable cannot be the target of an assignment. Name = "string" ~~~~ BC30064: 'ReadOnly' variable cannot be the target of an assignment. a = New ReferenceType() ~ BC30064: 'ReadOnly' variable cannot be the target of an assignment. b = New ReferenceType() ~ </expected>) End Sub <Fact()> Public Sub BC30065ERR_ExitSubOfFunc_1() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="ExitSubOfFunc"> <file name="a.vb"> Public Class C1 Function FOO() If (True) Exit Sub End If Return Nothing End Function End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC30065: 'Exit Sub' is not valid in a Function or Property. Exit Sub ~~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC30067ERR_ExitFuncOfSub_1() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="ExitFuncOfSub"> <file name="a.vb"> Public Class C1 Sub FOO() If (True) lb1: Exit Function End If End Sub End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC30067: 'Exit Function' is not valid in a Sub or Property. lb1: Exit Function ~~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC30068ERR_LValueRequired() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="LValueRequired"> <file name="a.vb"> Module M1 Class TestClass ReadOnly Name As String = "Cici" Sub test() Dim obj As Cls1 obj.Test = 1 obj.Test() = 1 End Sub End Class Class Cls1 Public Overridable Sub Test() End Sub End Class End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42104: Variable 'obj' is used before it has been assigned a value. A null reference exception could result at runtime. obj.Test = 1 ~~~ BC30068: Expression is a value and therefore cannot be the target of an assignment. obj.Test = 1 ~~~~~~~~ BC30068: Expression is a value and therefore cannot be the target of an assignment. obj.Test() = 1 ~~~~~~~~~~ </expected>) End Sub <WorkItem(575055, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/575055")> <Fact> Public Sub BC30068ERR_IdentifierWithSameNameDifferentScope() Dim source = <compilation> <file name="DuplicateID.vb"><![CDATA[ Module Module1 Dim list2 As Integer() = {1} Dim ddd = From i In list2 Where i > Foo(Function(m1) If(True, Sub(m2) Call Function(m3) Return Sub() If True Then For Each i In list2 : m1 = i : Exit Sub : Exit For : Next End Function(m2), Sub(m2) Call Function(m3) Return Sub() If True Then For Each i In list2 : m1 = i : Exit Sub : Exit For : Next End Function(m2))) Sub Main() End Sub Function Foo(ByVal x) Return x.Invoke(1) End Function End Module ]]></file></compilation> CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_ExpectedQueryableSource, "list2").WithArguments("Integer()"), Diagnostic(ERRID.ERR_LValueRequired, "i"), Diagnostic(ERRID.ERR_LValueRequired, "i")) End Sub ' change error 30098 to 30068 <WorkItem(538107, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538107")> <Fact()> Public Sub BC30068ERR_LValueRequired_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ReadOnlyProperty1"> <file name="a.vb"> Module SB008mod Public ReadOnly Name As String Public ReadOnly Name1 As Struct1 Public ReadOnly Name2 As Class1 Sub SB008() Name = "15" Name1.Field = "15" Name2.Field = "15" System.TypeCode.Boolean=0 A().Field="15" End Sub Function A() As Struct1 Return Nothing End Function End Module Structure Struct1 Public Field As String End Structure Class Class1 Public Field As String End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30064: 'ReadOnly' variable cannot be the target of an assignment. Name = "15" ~~~~ BC30064: 'ReadOnly' variable cannot be the target of an assignment. Name1.Field = "15" ~~~~~~~~~~~ BC30074: Constant cannot be the target of an assignment. System.TypeCode.Boolean=0 ~~~~~~~~~~~~~~~~~~~~~~~ BC30068: Expression is a value and therefore cannot be the target of an assignment. A().Field="15" ~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30068ERR_LValueRequired_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="LValueRequired"> <file name="a.vb"> Class A Property P Shared Property Q End Class Structure B Property P Shared Property Q End Structure Class C Property P As A Property Q As B Sub M() P.P = Nothing ' no error Q.P = Nothing ' BC30068 A.Q = Nothing ' no error B.Q = Nothing ' no error End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30068: Expression is a value and therefore cannot be the target of an assignment. Q.P = Nothing ' BC30068 ~~~ </expected>) End Sub <Fact()> Public Sub BC30069ERR_ForIndexInUse1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ForIndexInUse1"> <file name="a.vb"> Module A Sub TEST() Dim n(3) As Integer Dim u As Integer For u = n(0) To n(3) Step n(0) ' BC30069: For loop control variable 'u' already in use by an enclosing For loop. For u = 1 To 9 Next Next End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30069: For loop control variable 'u' already in use by an enclosing For loop. For u = 1 To 9 ~ </expected>) End Sub <Fact()> Public Sub BC30070ERR_NextForMismatch1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="NextForMismatch1"> <file name="a.vb"> Module A Sub TEST() Dim n(3) As Integer Dim u As Integer Dim k As Integer For u = n(0) To n(3) Step n(0) For k = 1 To 9 Next u Next k End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30070: Next control variable does not match For loop control variable 'k'. Next u ~ BC30070: Next control variable does not match For loop control variable 'u'. Next k ~ </expected>) End Sub <Fact()> Public Sub BC30070ERR_NextForMismatch1_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="NextForMismatch1"> <file name="a.vb"> Class C Public Shared Sub Main() Dim S As String = "ABC" Dim T As String = "XYZ" For Each x As Char In S For Each y As Char In T Next y, x For Each x As Char In S For Each y As Char In T Next x, y End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30070: Next control variable does not match For loop control variable 'y'. Next x, y ~ BC30451: 'y' is not declared. It may be inaccessible due to its protection level. Next x, y ~ </expected>) End Sub <Fact()> Public Sub BC30074ERR_CantAssignToConst() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="CantAssignToConst"> <file name="a.vb"> Class c1_0 Public foo As Byte End Class Class c2_1 Inherits c1_0 Public Shadows Const foo As Short = 15 Sub test() 'COMPILEERROR: BC30074, "foo" foo = 1 End Sub End Class Class c3_1 Inherits c1_0 Public Shadows Const foo As Short = 15 End Class Class c2_2 Sub test() Dim obj As c3_1 obj.foo = 10 End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30074: Constant cannot be the target of an assignment. foo = 1 ~~~ BC30074: Constant cannot be the target of an assignment. obj.foo = 10 ~~~~~~~ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. obj.foo = 10 ~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30075ERR_NamedSubscript() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="NamedSubscript"> <file name="a.vb"> Class c1 Sub test() Dim Array As Integer() = new integer(){1} Array(Index:=10) = 1 End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30075: Named arguments are not valid as array subscripts. Array(Index:=10) = 1 ~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30089ERR_ExitDoNotWithinDo() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ERR_ExitDoNotWithinDo"> <file name="a.vb"> Structure myStruct1 Public Sub m(ByVal s As String) Select Case s Case "userID" Exit do End Select End Sub End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30089: 'Exit Do' can only appear inside a 'Do' statement. Exit do ~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30089ERR_ExitDoNotWithinDo_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ERR_ExitDoNotWithinDo"> <file name="a.vb"> Structure myStruct1 Public Sub m(ByVal s As String) If s Then Exit Do Else End If End Sub End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30089: 'Exit Do' can only appear inside a 'Do' statement. Exit Do ~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30094ERR_MultiplyDefined1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="MultiplyDefined1"> <file name="a.vb"> Module M1 Sub Main() SB008() End Sub Sub SB008() [cc]: 'COMPILEERROR: BC30094, "cc" cc: Exit Sub End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30094: Label 'cc' is already defined in the current method. cc: ~~ </expected>) End Sub <Fact()> Public Sub Bug585223_notMultiplyDefined() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="MultiplyDefined1"> <file name="a.vb"> <![CDATA[ Module Program Sub Main() &H100000000: &H000000000: End Sub End Module ]]> </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> </expected>) End Sub <Fact()> Public Sub Bug585223_notMultiplyDefined_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="MultiplyDefined1"> <file name="a.vb"> <![CDATA[ Module Program Sub Main() &HF: &HFF: &HFFF: &HFFFF: &HFFFFF: &HFFFFFF: &HFFFFFFF: &HFFFFFFFF: &HFFFFFFFFF: &HFFFFFFFFFF: &HFFFFFFFFFFF: &HFFFFFFFFFFFF: &HFFFFFFFFFFFFF: &HFFFFFFFFFFFFFF: &HFFFFFFFFFFFFFFF: &HFFFFFFFFFFFFFFFF: End Sub End Module ]]> </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> </expected>) End Sub <Fact()> Public Sub BC30096ERR_ExitForNotWithinFor() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ExitForNotWithinFor"> <file name="a.vb"> Structure myStruct1 Public Sub m(ByVal s As String) Select Case s Case "userID" Exit For End Select End Sub End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30096: 'Exit For' can only appear inside a 'For' statement. Exit For ~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30096ERR_ExitForNotWithinFor_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ExitForNotWithinFor"> <file name="a.vb"> Structure myStruct1 Public Sub m(ByVal s As String) If s Then Exit For Else End If End Sub End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30096: 'Exit For' can only appear inside a 'For' statement. Exit For ~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30097ERR_ExitWhileNotWithinWhile() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ExitWhileNotWithinWhile"> <file name="a.vb"> Structure myStruct1 Public Sub m(ByVal s As String) Select Case s Case "userID" Exit While End Select End Sub End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30097: 'Exit While' can only appear inside a 'While' statement. Exit While ~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30097ERR_ExitWhileNotWithinWhile_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ExitWhileNotWithinWhile"> <file name="a.vb"> Structure myStruct1 Public Sub m(ByVal s As String) If s Then Exit While Else End If End Sub End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30097: 'Exit While' can only appear inside a 'While' statement. Exit While ~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30099ERR_ExitSelectNotWithinSelect() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ExitSelectNotWithinSelect"> <file name="a.vb"> Structure myStruct1 Public Sub m(ByVal s As String) If s Then Exit Select Else End If End Sub End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30099: 'Exit Select' can only appear inside a 'Select' statement. Exit Select ~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30101ERR_BranchOutOfFinally() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="BranchOutOfFinally"> <file name="a.vb"> Imports System Module M1 Sub Foo() Try Try Label1: Catch Finally GoTo Label1 End Try Catch Finally End Try Exit Sub End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30101: Branching out of a 'Finally' is not valid. GoTo Label1 ~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30101ERR_BranchOutOfFinally2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="BC30101ERR_BranchOutOfFinally2"> <file name="a.vb"> Imports System Module M1 Sub Foo() Try Try Catch Finally Label2: GoTo Label2 End Try Catch Finally End Try Exit Sub End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) End Sub <Fact()> Public Sub BC30101ERR_BranchOutOfFinally3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="BC30101ERR_BranchOutOfFinally3"> <file name="a.vb"> Imports System Module M1 Sub Foo() Try Catch Finally Label2: GoTo Label2 End Try End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) End Sub <Fact()> Public Sub BC30101ERR_BranchOutOfFinally4() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="BC30101ERR_BranchOutOfFinally4"> <file name="a.vb"> Imports System Module M1 Sub Foo() Try Catch Finally GoTo L2 L2: GoTo L2 End Try End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) End Sub <Fact()> Public Sub BC30103ERR_QualNotObjectRecord1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System Enum E A End Enum Class C Shared Sub M(Of T)() Dim [object] As Object = Nothing M([object]!P) Dim [enum] As E = E.A M([enum]!P) Dim [boolean] As Boolean = False M([boolean]!P) Dim [char] As Char = Nothing M([char]!P) Dim [sbyte] As SByte = Nothing M([sbyte]!P) Dim [byte] As Byte = Nothing M([byte]!P) Dim [int16] As Int16 = Nothing M([int16]!P) Dim [uint16] As UInt16 = Nothing M([uint16]!P) Dim [int32] As Int32 = Nothing M([int32]!P) Dim [uint32] As UInt32 = Nothing M([uint32]!P) Dim [int64] As Int64 = Nothing M([int64]!P) Dim [uint64] As UInt64 = Nothing M([uint64]!P) Dim [decimal] As Decimal = Nothing M([decimal]!P) Dim [single] As Single = Nothing M([single]!P) Dim [double] As Double = Nothing M([double]!P) Dim [type] As Type = Nothing M([type]!P) Dim [array] As Integer() = Nothing M([array]!P) Dim [nullable] As Nullable(Of Integer) = Nothing M([nullable]!P) Dim [datetime] As DateTime = Nothing M([datetime]!P) Dim [action] As Action = Nothing M([action]!P) Dim tp As T = Nothing M(tp!P) End Sub Shared Sub M(o) End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30103: '!' requires its left operand to have a type parameter, class or interface type, but this operand has the type 'E'. M([enum]!P) ~~~~~~ BC30103: '!' requires its left operand to have a type parameter, class or interface type, but this operand has the type 'Boolean'. M([boolean]!P) ~~~~~~~~~ BC30103: '!' requires its left operand to have a type parameter, class or interface type, but this operand has the type 'Char'. M([char]!P) ~~~~~~ BC30103: '!' requires its left operand to have a type parameter, class or interface type, but this operand has the type 'SByte'. M([sbyte]!P) ~~~~~~~ BC30103: '!' requires its left operand to have a type parameter, class or interface type, but this operand has the type 'Byte'. M([byte]!P) ~~~~~~ BC30103: '!' requires its left operand to have a type parameter, class or interface type, but this operand has the type 'Short'. M([int16]!P) ~~~~~~~ BC30103: '!' requires its left operand to have a type parameter, class or interface type, but this operand has the type 'UShort'. M([uint16]!P) ~~~~~~~~ BC30103: '!' requires its left operand to have a type parameter, class or interface type, but this operand has the type 'Integer'. M([int32]!P) ~~~~~~~ BC30103: '!' requires its left operand to have a type parameter, class or interface type, but this operand has the type 'UInteger'. M([uint32]!P) ~~~~~~~~ BC30103: '!' requires its left operand to have a type parameter, class or interface type, but this operand has the type 'Long'. M([int64]!P) ~~~~~~~ BC30103: '!' requires its left operand to have a type parameter, class or interface type, but this operand has the type 'ULong'. M([uint64]!P) ~~~~~~~~ BC30103: '!' requires its left operand to have a type parameter, class or interface type, but this operand has the type 'Decimal'. M([decimal]!P) ~~~~~~~~~ BC30103: '!' requires its left operand to have a type parameter, class or interface type, but this operand has the type 'Single'. M([single]!P) ~~~~~~~~ BC30103: '!' requires its left operand to have a type parameter, class or interface type, but this operand has the type 'Double'. M([double]!P) ~~~~~~~~ BC30367: Class 'Type' cannot be indexed because it has no default property. M([type]!P) ~~~~~~ BC30103: '!' requires its left operand to have a type parameter, class or interface type, but this operand has the type 'Integer()'. M([array]!P) ~~~~~~~ BC30690: Structure 'Integer?' cannot be indexed because it has no default property. M([nullable]!P) ~~~~~~~~~~ BC30103: '!' requires its left operand to have a type parameter, class or interface type, but this operand has the type 'Date'. M([datetime]!P) ~~~~~~~~~~ BC30555: Default member of 'Action' is not a property. M([action]!P) ~~~~~~~~ BC30547: 'T' cannot be indexed because it has no default property. M(tp!P) ~~ </expected>) End Sub <Fact()> Public Sub BC30103ERR_QualNotObjectRecord1a() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Enum E A End Enum Class C Shared Sub M(Of T)() Dim [string] As String = Nothing M([string]!P) End Sub Shared Sub M(o) End Sub End Class </file> </compilation>) compilation.VerifyEmitDiagnostics( Diagnostic(ERRID.ERR_MissingRuntimeHelper, "P").WithArguments("Microsoft.VisualBasic.CompilerServices.Conversions.ToInteger")) End Sub <Fact()> Public Sub BC30103ERR_QualNotObjectRecord2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="QualNotObjectRecord1"> <file name="a.vb"> Imports System Module BitOp001mod Sub BitOp001() Dim b As Byte = 2 Dim c As Byte = 3 Dim s As Short = 2 Dim t As Short = 3 Dim i As Integer = 2 Dim j As Integer = 3 Dim l As Long = 2 Dim m As Long = 3 b = b!c s = s!t i = i!j l = l!m End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30103: '!' requires its left operand to have a type parameter, class or interface type, but this operand has the type 'Byte'. b = b!c ~ BC30103: '!' requires its left operand to have a type parameter, class or interface type, but this operand has the type 'Short'. s = s!t ~ BC30103: '!' requires its left operand to have a type parameter, class or interface type, but this operand has the type 'Integer'. i = i!j ~ BC30103: '!' requires its left operand to have a type parameter, class or interface type, but this operand has the type 'Long'. l = l!m ~ </expected>) End Sub <Fact()> Public Sub BC30105ERR_TooFewIndices() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="TooFewIndices"> <file name="a.vb"> Imports System Module M1 Sub AryChg001() Dim a() As Integer = New Integer() {9, 10} ReDim a(10) Dim a8() As Integer = New Integer() {1, 2} Dim b8() As Integer = New Integer() {3, 4} Dim c8 As Integer a8() = b8 b8 = a() a8() = c8 c8 = a8() End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30105: Number of indices is less than the number of dimensions of the indexed array. a8() = b8 ~~ BC30105: Number of indices is less than the number of dimensions of the indexed array. b8 = a() ~~ BC30105: Number of indices is less than the number of dimensions of the indexed array. a8() = c8 ~~ BC30105: Number of indices is less than the number of dimensions of the indexed array. c8 = a8() ~~ </expected>) End Sub <Fact()> Public Sub BC30106ERR_TooManyIndices() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="TooManyIndices"> <file name="a.vb"> Imports System Module M1 Sub AryChg001() Dim a() As Integer = New Integer() {9, 10} ReDim a(10) Dim a8() As Integer = New Integer() {1, 2} Dim b8() As Integer = New Integer() {3, 4} Dim c8 As Integer a8(1, 2) = b8(1) b8 = a(0, 4) a8(4, 5, 6) = c8 c8 = a8(1, 2) End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30106: Number of indices exceeds the number of dimensions of the indexed array. a8(1, 2) = b8(1) ~~~~~~ BC30106: Number of indices exceeds the number of dimensions of the indexed array. b8 = a(0, 4) ~~~~~~ BC30106: Number of indices exceeds the number of dimensions of the indexed array. a8(4, 5, 6) = c8 ~~~~~~~~~ BC30106: Number of indices exceeds the number of dimensions of the indexed array. c8 = a8(1, 2) ~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30107ERR_EnumNotExpression1() CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="EnumNotExpression1"> <file name="a.vb"> Option Strict On Module BitOp001mod1 Sub BitOp001() Dim b As Byte = 2 Dim c As Byte = 3 Dim s As Short = 2 Dim t As Short = 3 Dim i As Integer = 2 Dim j As Integer = 3 Dim l As Long = 2 Dim m As Long = 3 b = b &amp; c b = b ^ c s = s &amp; t s = s ^ t i = i &amp; j i = i ^ j l = l &amp; m l = l ^ m Exit Sub End Sub End Module </file> </compilation>).VerifyDiagnostics( Diagnostic(ERRID.ERR_NarrowingConversionDisallowed2, "b & c").WithArguments("String", "Byte"), Diagnostic(ERRID.ERR_NarrowingConversionDisallowed2, "b ^ c").WithArguments("Double", "Byte"), Diagnostic(ERRID.ERR_NarrowingConversionDisallowed2, "s & t").WithArguments("String", "Short"), Diagnostic(ERRID.ERR_NarrowingConversionDisallowed2, "s ^ t").WithArguments("Double", "Short"), Diagnostic(ERRID.ERR_NarrowingConversionDisallowed2, "i & j").WithArguments("String", "Integer"), Diagnostic(ERRID.ERR_NarrowingConversionDisallowed2, "i ^ j").WithArguments("Double", "Integer"), Diagnostic(ERRID.ERR_NarrowingConversionDisallowed2, "l & m").WithArguments("String", "Long"), Diagnostic(ERRID.ERR_NarrowingConversionDisallowed2, "l ^ m").WithArguments("Double", "Long")) End Sub <Fact()> Public Sub BC30108ERR_TypeNotExpression1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="TypeNotExpression1"> <file name="a.vb"> Module Module1 Sub Main() Module1 End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30108: 'Module1' is a type and cannot be used as an expression. Module1 ~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30108ERR_TypeNotExpression1_1() CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="TypeNotExpression1"> <file name="a.vb"> Imports System.Collections.Generic Module Program Sub Main() Dim lst As New List(Of String) From {Program, "abc", "def", "ghi"} End Sub End Module </file> </compilation>).VerifyDiagnostics( Diagnostic(ERRID.ERR_TypeNotExpression1, "Program").WithArguments("Program")) End Sub <WorkItem(545166, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545166")> <Fact()> Public Sub BC30109ERR_ClassNotExpression1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ClassNotExpression1"> <file name="a.vb"> Imports System Module M1 Sub FOO() Dim c As Object c = String(3, "Hai123") c = String End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30109: 'String' is a class type and cannot be used as an expression. c = String(3, "Hai123") ~~~~~~ BC30109: 'String' is a class type and cannot be used as an expression. c = String ~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30110ERR_StructureNotExpression1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="StructureNotExpression1"> <file name="a.vb"> Imports System Structure S1 End Structure Module M1 Sub FOO() Dim c As Object c = S1(3, "Hai123") c = S1 End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30110: 'S1' is a structure type and cannot be used as an expression. c = S1(3, "Hai123") ~~ BC30110: 'S1' is a structure type and cannot be used as an expression. c = S1 ~~ </expected>) End Sub <Fact()> Public Sub BC30111ERR_InterfaceNotExpression1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="StructureNotExpression1"> <file name="a.vb"> Imports System Interface S1 End Interface Module M1 Sub FOO() Dim c As Object c = S1(3, "Hai123") c = S1 End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30111: 'S1' is an interface type and cannot be used as an expression. c = S1(3, "Hai123") ~~ BC30111: 'S1' is an interface type and cannot be used as an expression. c = S1 ~~ </expected>) End Sub <Fact()> Public Sub BC30112ERR_NamespaceNotExpression1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="NamespaceNotExpression1"> <file name="a.vb"> Imports System Module M1 Sub Foo() 'COMPILEERROR: BC30112, "Text$" Text$ End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30112: 'System.Text' is a namespace and cannot be used as an expression. Text$ ~~~~~ </expected>) End Sub <Fact()> Public Sub BC30112ERR_NamespaceNotExpression2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="NamespaceNotExpression1"> <file name="a.vb"> Option Infer On Namespace X Class Program Sub Main() 'COMPILEERROR: BC30112, "x" For Each x In "" Next End Sub End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30112: 'X' is a namespace and cannot be used as an expression. For Each x In "" ~ </expected>) End Sub <Fact()> Public Sub BC30114ERR_XmlPrefixNotExpression() Dim options = TestOptions.ReleaseDll.WithGlobalImports(GlobalImport.Parse({"<xmlns:p1=""..."">"})) Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports System Imports <xmlns:p2="..."> Imports <xmlns:p4="..."> Module M Private F1 As Object = p1 Private F2 As Object = P1 Private F3 As Object = xml Private F4 As Object = XML Private F5 As Object = xmlns Private F6 As Object = XMLNS Private F7 As Object = <x xmlns:p3="..."> <%= p2 %> <%= p3 %> <%= xmlns %> </x> Private Function F8(p1 As Object) As Object Return p1 End Function Private Function F9(xmlns As Object) As Object Return p2 End Function Private F10 As Object = p4 End Module ]]></file> <file name="b.vb"><![CDATA[ Class p4 End Class ]]></file> </compilation>, references:=XmlReferences, options:=options) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC30114: 'p1' is an XML prefix and cannot be used as an expression. Use the GetXmlNamespace operator to create a namespace object. Private F1 As Object = p1 ~~ BC30451: 'P1' is not declared. It may be inaccessible due to its protection level. Private F2 As Object = P1 ~~ BC30112: 'System.Xml' is a namespace and cannot be used as an expression. Private F3 As Object = xml ~~~ BC30112: 'System.Xml' is a namespace and cannot be used as an expression. Private F4 As Object = XML ~~~ BC30114: 'xmlns' is an XML prefix and cannot be used as an expression. Use the GetXmlNamespace operator to create a namespace object. Private F5 As Object = xmlns ~~~~~ BC30451: 'XMLNS' is not declared. It may be inaccessible due to its protection level. Private F6 As Object = XMLNS ~~~~~ BC30114: 'p2' is an XML prefix and cannot be used as an expression. Use the GetXmlNamespace operator to create a namespace object. <%= p2 %> ~~ BC30451: 'p3' is not declared. It may be inaccessible due to its protection level. <%= p3 %> ~~ BC30114: 'xmlns' is an XML prefix and cannot be used as an expression. Use the GetXmlNamespace operator to create a namespace object. <%= xmlns %> ~~~~~ BC30114: 'p2' is an XML prefix and cannot be used as an expression. Use the GetXmlNamespace operator to create a namespace object. Return p2 ~~ BC30109: 'p4' is a class type and cannot be used as an expression. Private F10 As Object = p4 ~~ ]]></errors>) End Sub <Fact()> Public Sub BC30131ERR_ModuleSecurityAttributeNotAllowed1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="BC30131ERR_ModuleSecurityAttributeNotAllowed1"> <file name="a.vb"> <![CDATA[ Imports System Imports System.Security.Permissions Imports System.Security.Principal <Module: MySecurity(Security.Permissions.SecurityAction.Assert)> <AttributeUsage(AttributeTargets.Module)> Class MySecurityAttribute Inherits SecurityAttribute Public Sub New(action As SecurityAction) MyBase.New(action) End Sub Public Overrides Function CreatePermission() As Security.IPermission Return Nothing End Function End Class Module Foo Public Sub main() End Sub End Module ]]> </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected><![CDATA[ BC36979: Security attribute 'MySecurityAttribute' is not valid on this declaration type. Security attributes are only valid on assembly, type and method declarations. <Module: MySecurity(Security.Permissions.SecurityAction.Assert)> ~~~~~~~~~~ ]]> </expected>) End Sub <Fact()> Public Sub BC30132ERR_LabelNotDefined1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="LabelNotDefined1"> <file name="a.vb"> Module Implicitmod Sub Implicit() 'COMPILEERROR: BC30132, "ns1" GoTo ns1 End Sub Sub Test() ns1: End Sub End Module Namespace NS2 Module Implicitmod Sub Implicit() ns1: End Sub End Module End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30132: Label 'ns1' is not defined. GoTo ns1 ~~~ </expected>) End Sub <Fact()> Public Sub BC30148ERR_RequiredNewCall2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="RequiredNewCall2"> <file name="a.vb"> Imports System Module Test Class clsTest0 Sub New(ByVal strTest As String) End Sub End Class Class clsTest1 Inherits clsTest0 Private strTest As String = "Hello" Sub New(ByVal ArgX As String) 'COMPILEERROR: BC30148, "Console.WriteLine(ArgX)" Console.WriteLine(ArgX) End Sub End Class End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30148: First statement of this 'Sub New' must be a call to 'MyBase.New' or 'MyClass.New' because base class 'Test.clsTest0' of 'Test.clsTest1' does not have an accessible 'Sub New' that can be called with no arguments. Sub New(ByVal ArgX As String) ~~~ </expected>) End Sub <Fact()> Public Sub BC30157ERR_BadWithRef() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Module M1 Sub Main() .xxx = 3 End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30157: Leading '.' or '!' can only appear inside a 'With' statement. .xxx = 3 ~~~~ </expected>) End Sub <Fact()> Public Sub BC30157ERR_BadWithRef_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C Default Property P(x As String) Get Return Nothing End Get Set(value) End Set End Property Sub M() !A = Me!B Me!A = !B End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30157: Leading '.' or '!' can only appear inside a 'With' statement. !A = Me!B ~~ BC30157: Leading '.' or '!' can only appear inside a 'With' statement. Me!A = !B ~~ </expected>) End Sub <Fact()> Public Sub BC30157ERR_BadWithRef_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Module M Sub M() Dim o As Object o = .<x> o = ...<x> .@a = .@<a> End Sub End Module ]]></file> </compilation>, references:=XmlReferences) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC30157: Leading '.' or '!' can only appear inside a 'With' statement. o = .<x> ~~~~ BC30157: Leading '.' or '!' can only appear inside a 'With' statement. o = ...<x> ~~~~~~ BC30157: Leading '.' or '!' can only appear inside a 'With' statement. .@a = .@<a> ~~~ BC30157: Leading '.' or '!' can only appear inside a 'With' statement. .@a = .@<a> ~~~~~ ]]></errors>) End Sub <Fact()> Public Sub BC30182_ERR_UnrecognizedType_2() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="UnrecognizedType"> <file name="a.vb"> Namespace NS Class C1 Sub FOO() Dim v = 1 Dim s = CType(v, NS) End Sub End Class End Namespace </file> </compilation>) Dim expectedErrors1 = <errors> BC30182: Type expected. Dim s = CType(v, NS) ~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC30203ERR_ExpectedIdentifier() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BC30203ERR_ExpectedIdentifier"> <file name="a.vb"> Option Strict On Class C1 Public Property Public Property _ as Integer Shared Public End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC30203: Identifier expected. Public Property ~ BC30301: 'Public Property As Object' and 'Public Property As Integer' cannot overload each other because they differ only by return types. Public Property ~ BC30203: Identifier expected. Public Property _ as Integer ~ BC30203: Identifier expected. Shared Public ~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC30209ERR_StrictDisallowImplicitObject() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="StrictDisallowImplicitObject"> <file name="a.vb"> Option Strict On Structure myStruct Dim s End Structure </file> </compilation>) Dim expectedErrors1 = <errors> BC30209: Option Strict On requires all variable declarations to have an 'As' clause. Dim s ~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC30209ERR_StrictDisallowImplicitObject_1() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="StrictDisallowImplicitObject"> <file name="a.vb"> Option Strict On Structure myStruct Sub Scen1() 'COMPILEERROR: BC30209, "i" Dim i End Sub End Structure </file> </compilation>) Dim expectedErrors1 = <errors> BC30209: Option Strict On requires all variable declarations to have an 'As' clause. Dim i ~ BC42024: Unused local variable: 'i'. Dim i ~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact(), WorkItem(528749, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528749")> Public Sub BC30209ERR_StrictDisallowImplicitObject_3() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="StrictDisallowImplicitObject"> <file name="a.vb"> Option strict on option infer off imports system Class C1 Public Const f1 = "foo" Public Const f2 As Object = "foo" Public Const f3 = 23 Public Const f4 As Object = 42 Public Shared Sub Main(args() As String) console.writeline(f1) console.writeline(f2) console.writeline(f3) console.writeline(f4) End Sub End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC30209: Option Strict On requires all variable declarations to have an 'As' clause. Public Const f1 = "foo" ~~ BC30209: Option Strict On requires all variable declarations to have an 'As' clause. Public Const f3 = 23 ~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC30239ERR_ExpectedRelational_SelectCase() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="StrictDisallowImplicitObject"> <file name="a.vb"> <file name="a.vb"><![CDATA[ Imports System Module M1 Sub Main() Select Case 0 Case Is << 1 End Select End Sub End Module ]]></file> </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected><![CDATA[ BC30239: Relational operator expected. Case Is << 1 ~ ]]></expected>) End Sub <Fact()> Public Sub BC30272ERR_NamedParamNotFound2() CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="NamedParamNotFound2"> <file name="a.vb"> Module Module1 Class C0(Of T) Public whichOne As String Sub Foo(ByVal t1 As T) whichOne = "T" End Sub End Class Class C1(Of T, Y) Inherits C0(Of T) Overloads Sub Foo(ByVal y1 As Y) whichOne = "Y" End Sub End Class Sub GenUnif0060() Dim tc1 As New C1(Of Integer, Integer) ' BC30272: 't1' is not a parameter of 'Public Overloads Sub Foo(y1 As Y)'. Call tc1.Foo(t1:=1000) End Sub End Module </file> </compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_NamedParamNotFound2, "t1").WithArguments("t1", "Public Overloads Sub Foo(y1 As Integer)"), Diagnostic(ERRID.ERR_OmittedArgument2, "Foo").WithArguments("y1", "Public Overloads Sub Foo(y1 As Integer)")) End Sub <Fact()> Public Sub BC30274ERR_NamedArgUsedTwice2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="NamedArgUsedTwice2"> <file name="a.vb"> Module Module1 Class C0 Public whichOne As String Sub Foo(ByVal t1 As String) whichOne = "T" End Sub End Class Class C1 Inherits C0 Overloads Sub Foo(ByVal y1 As String) whichOne = "Y" End Sub End Class Sub test() Dim [ident1] As C0 = New C0() Dim clsNarg2get As C1 = New C1() Dim str1 As String = "Visual Basic" 'COMPILEERROR: BC30274, "y" [ident1].Foo(1, t1:=2) = str1 'COMPILEERROR: BC30274, "x" [ident1].Foo(t1:=1, t1:=1) = str1 End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30274: Parameter 't1' of 'Public Sub Foo(t1 As String)' already has a matching argument. [ident1].Foo(1, t1:=2) = str1 ~~ BC30274: Parameter 't1' of 'Public Sub Foo(t1 As String)' already has a matching argument. [ident1].Foo(t1:=1, t1:=1) = str1 ~~ </expected>) End Sub <Fact()> Public Sub BC30277ERR_TypecharNoMatch2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="TypecharNoMatch2"> <file name="a.vb"> Imports Microsoft.VisualBasic.Information Namespace NS30277 Public Class genClass1(Of CT) Public Function genFun7(Of T)(ByVal x As T) As T() Dim t1(2) As T Return t1 End Function End Class Module MD30277 Sub GenMethod9102() Const uiConst As UInteger = 1000 Dim o As New genClass1(Of Object) Dim objTmp As Object = CShort(10) ' BC30277: type character does not match declared data type. o.genFun7%(1&amp;) ' BC30277: type character does not match declared data type. o.genFun7%(True) ' BC30277: type character does not match declared data type. o.genFun7%((True And False)) ' BC30277: type character does not match declared data type. o.genFun7%(CDbl(1)) ' BC30277: type character does not match declared data type. o.genFun7%(Fun1) ' BC30277: type character does not match declared data type. o.genFun7%(TypeName(o)) ' BC30277: type character does not match declared data type. o.genFun7%(uiConst) ' BC30277: type character does not match declared data type. o.genFun7%(objTmp) End Sub Function Fun1() As Byte Return 1 End Function End Module End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30277: Type character '%' does not match declared data type 'Long'. o.genFun7%(1&amp;) ~~~~~~~~~~~~~~ BC30277: Type character '%' does not match declared data type 'Boolean'. o.genFun7%(True) ~~~~~~~~~~~~~~~~ BC30277: Type character '%' does not match declared data type 'Boolean'. o.genFun7%((True And False)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30277: Type character '%' does not match declared data type 'Double'. o.genFun7%(CDbl(1)) ~~~~~~~~~~~~~~~~~~~ BC30277: Type character '%' does not match declared data type 'Byte'. o.genFun7%(Fun1) ~~~~~~~~~~~~~~~~ BC30277: Type character '%' does not match declared data type 'String'. o.genFun7%(TypeName(o)) ~~~~~~~~~~~~~~~~~~~~~~~ BC30277: Type character '%' does not match declared data type 'UInteger'. o.genFun7%(uiConst) ~~~~~~~~~~~~~~~~~~~ BC30277: Type character '%' does not match declared data type 'Object'. o.genFun7%(objTmp) ~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30277ERR_TypecharNoMatch2_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="TypecharNoMatch2"> <file name="a.vb"> Class C Public Shared Sub Main() 'declare with explicit type, use in next with a type char") For Each x As Integer In New Integer() {1, 1, 1} 'COMPILEERROR: BC30277, "x#" Next x# For Each [me] As Integer In New Integer() {1, 1, 1} Next me% End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30277: Type character '#' does not match declared data type 'Integer'. Next x# ~~ </expected>) End Sub <WorkItem(528681, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528681")> <Fact()> Public Sub BC30277ERR_TypecharNoMatch2_3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="TypecharNoMatch2"> <file name="a.vb"> Public Class MyClass1 Public Shared Sub Main() For ivar% As Long = 1 To 10 Next For dvar# As Single = 1 To 10 Next For cvar@ As Decimal = 1 To 10 Next End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30302: Type character '%' cannot be used in a declaration with an explicit type. For ivar% As Long = 1 To 10 ~~~~~ BC30302: Type character '#' cannot be used in a declaration with an explicit type. For dvar# As Single = 1 To 10 ~~~~~ BC30302: Type character '@' cannot be used in a declaration with an explicit type. For cvar@ As Decimal = 1 To 10 ~~~~~ </expected>) End Sub <Fact()> Public Sub BC30282ERR_InvalidConstructorCall1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="InvalidConstructorCall1"> <file name="a.vb"> Module Error30282 Class Class1 Sub New() End Sub End Class Class Class2 Inherits Class1 Sub New() 'COMPILEERROR: BC30282, "Class1.New" Class1.New() End Sub End Class End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30282: Constructor call is valid only as the first statement in an instance constructor. Class1.New() ~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30282ERR_InvalidConstructorCall2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="InvalidConstructorCall2"> <file name="a.vb"> Imports System Class C Sub New(x As Integer) Me.New(Of Integer) End Sub Sub New End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30282: Constructor call is valid only as the first statement in an instance constructor. Me.New(Of Integer) ~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30282ERR_InvalidConstructorCall3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="InvalidConstructorCall3"> <file name="a.vb"> Imports System Class C Sub New(x As Integer) Me.New Me.New(Of Integer) End Sub Sub New End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30282: Constructor call is valid only as the first statement in an instance constructor. Me.New(Of Integer) ~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30282ERR_InvalidConstructorCall4() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="InvalidConstructorCall4"> <file name="a.vb"> Imports System Class C Sub New(x As Integer) Me.New(Of Integer)(1.ToString(123, 2, 3, 4)) End Sub Sub New End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30282: Constructor call is valid only as the first statement in an instance constructor. Me.New(Of Integer)(1.ToString(123, 2, 3, 4)) ~~~~~~~~~~~~~~~~~~ BC30516: Overload resolution failed because no accessible 'ToString' accepts this number of arguments. Me.New(Of Integer)(1.ToString(123, 2, 3, 4)) ~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30282ERR_InvalidConstructorCall5() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="InvalidConstructorCall5"> <file name="a.vb"> Imports System Class C Sub New(x As Integer) Dim a = 1 + Me.New(Of Integer) End Sub Sub New End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30282: Constructor call is valid only as the first statement in an instance constructor. Dim a = 1 + Me.New(Of Integer) ~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30282ERR_ConstructorCallIsValidOnlyAsTheFirstStatementInAnInstanceConstructor_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BC30282ERR_ConstructorCallIsValidOnlyAsTheFirstStatementInAnInstanceConstructor_1"> <file name="a.vb"> Class Tests Public Sub New() End Sub Public Sub New(i As Integer) Me.New() End Sub Public Sub New(t As Tests) t.New(1) End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> BC30282: Constructor call is valid only as the first statement in an instance constructor. t.New(1) ~~~~~ </errors>) End Sub <Fact()> Public Sub BC30282ERR_ConstructorCallIsValidOnlyAsTheFirstStatementInAnInstanceConstructor_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BC30282ERR_ConstructorCallIsValidOnlyAsTheFirstStatementInAnInstanceConstructor_2"> <file name="a.vb"> Class Tests Public Sub New() End Sub Public Sub New(i As Integer) Me.New() Me.New() End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> BC30282: Constructor call is valid only as the first statement in an instance constructor. Me.New() ~~~~~~ </errors>) End Sub <Fact()> Public Sub BC30282ERR_ConstructorCallIsValidOnlyAsTheFirstStatementInAnInstanceConstructor_3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BC30282ERR_ConstructorCallIsValidOnlyAsTheFirstStatementInAnInstanceConstructor_3"> <file name="a.vb"> Class Tests Public Sub New() End Sub Public Sub New(i As Integer) l1: Me.New() End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> BC30282: Constructor call is valid only as the first statement in an instance constructor. Me.New() ~~~~~~ </errors>) End Sub <Fact()> Public Sub BC30282ERR_ConstructorCallIsValidOnlyAsTheFirstStatementInAnInstanceConstructor_4() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BC30282ERR_ConstructorCallIsValidOnlyAsTheFirstStatementInAnInstanceConstructor_4"> <file name="a.vb"> Class Tests Public Sub New() End Sub Public Sub New2() Me.New() End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> BC30282: Constructor call is valid only as the first statement in an instance constructor. Me.New() ~~~~~~ </errors>) End Sub <Fact()> Public Sub BC30282ERR_ConstructorCallIsValidOnlyAsTheFirstStatementInAnInstanceConstructor_5() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BC30282ERR_ConstructorCallIsValidOnlyAsTheFirstStatementInAnInstanceConstructor_5"> <file name="a.vb"> Class Tests Public Sub New() End Sub Public Sub New(i As Integer) #Const a = 1 #If a = 1 Then Me.New() #End If Me.New() End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> BC30282: Constructor call is valid only as the first statement in an instance constructor. Me.New() ~~~~~~ </errors>) End Sub <Fact()> Public Sub BC30282ERR_ConstructorCallIsValidOnlyAsTheFirstStatementInAnInstanceConstructor_6() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BC30282ERR_ConstructorCallIsValidOnlyAsTheFirstStatementInAnInstanceConstructor_6"> <file name="a.vb"> Class Tests Public Sub New() End Sub Public Sub New(i As Integer) Dim a As Integer = 1 + Me.New() + Me.New End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> BC30282: Constructor call is valid only as the first statement in an instance constructor. Dim a As Integer = 1 + Me.New() + Me.New ~~~~~~ BC30282: Constructor call is valid only as the first statement in an instance constructor. Dim a As Integer = 1 + Me.New() + Me.New ~~~~~~ </errors>) End Sub <Fact()> Public Sub BC30282ERR_ConstructorCallIsValidOnlyAsTheFirstStatementInAnInstanceConstructor_7() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BC30282ERR_ConstructorCallIsValidOnlyAsTheFirstStatementInAnInstanceConstructor_7"> <file name="a.vb"> Class Tests Public Sub New(i As String) End Sub Public Sub New(i As Integer) Dim a As Integer = 1 + Me.New(1, 2) + Me.New End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> BC30282: Constructor call is valid only as the first statement in an instance constructor. Dim a As Integer = 1 + Me.New(1, 2) + Me.New ~~~~~~ BC30282: Constructor call is valid only as the first statement in an instance constructor. Dim a As Integer = 1 + Me.New(1, 2) + Me.New ~~~~~~ </errors>) End Sub <Fact()> Public Sub BC30282ERR_ConstructorCallIsValidOnlyAsTheFirstStatementInAnInstanceConstructor_8() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BC30282ERR_ConstructorCallIsValidOnlyAsTheFirstStatementInAnInstanceConstructor_8"> <file name="a.vb"> Class Tests Public Sub New(i As String) End Sub Public Sub New(i As Integer) Tests.New(1, 2) End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> BC30282: Constructor call is valid only as the first statement in an instance constructor. Tests.New(1, 2) ~~~~~~~~~ </errors>) End Sub <WorkItem(541012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541012")> <Fact()> Public Sub BC30283ERR_CantOverrideConstructor() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="CantOverrideConstructor"> <file name="a.vb"> Module Error30283 Class Class1 mustoverride Sub New() End Sub End Class End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30364: 'Sub New' cannot be declared 'mustoverride'. mustoverride Sub New() ~~~~~~~~~~~~ BC30429: 'End Sub' must be preceded by a matching 'Sub'. End Sub ~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30288ERR_DuplicateLocals1() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="DuplicateLocals1"> <file name="a.vb"> Public Class Class1 Public Sub foo(ByVal val As Short) Dim i As Integer Dim i As String End Sub End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC42024: Unused local variable: 'i'. Dim i As Integer ~ BC30288: Local variable 'i' is already declared in the current block. Dim i As String ~ BC42024: Unused local variable: 'i'. Dim i As String ~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact(), WorkItem(531346, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531346")> Public Sub UnicodeCaseInsensitiveLocals() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="UnicodeCaseInsensitiveLocals"> <file name="a.vb"> Public Class Class1 Public Sub foo() Dim X&#x130; 'COMPILEERROR:BC30288, "xi" Dim xi Dim &#x130; 'COMPILEERROR:BC30288, "i" Dim i End Sub End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC42024: Unused local variable: 'X&#x130;'. Dim X&#x130; ~~ BC30288: Local variable 'xi' is already declared in the current block. Dim xi ~~ BC42024: Unused local variable: 'xi'. Dim xi ~~ BC42024: Unused local variable: '&#x130;'. Dim &#x130; ~ BC30288: Local variable 'i' is already declared in the current block. Dim i ~ BC42024: Unused local variable: 'i'. Dim i ~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC30290ERR_LocalSameAsFunc() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="LocalSameAsFunc"> <file name="a.vb"> Module Error30290 Class Class1 Function Foo(ByVal Name As String) 'COMPILEERROR : BC30290, "Foo" Dim Foo As Date Return Name End Function End Class End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30290: Local variable cannot have the same name as the function containing it. Dim Foo As Date ~~~ BC42024: Unused local variable: 'Foo'. Dim Foo As Date ~~~ </expected>) End Sub <Fact()> Public Sub BC30290ERR_LocalSameAsFunc_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="LocalSameAsFunc"> <file name="a.vb"> Class C Shared Sub Main() End Sub Function foo() as Object 'COMPILEERROR: BC30290, For Each foo As Integer In New Integer() {1, 2, 3} Next return nothing End Function Sub foo1() For Each foo1 As Integer In New Integer() {1, 2, 3} Next End SUB End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30290: Local variable cannot have the same name as the function containing it. For Each foo As Integer In New Integer() {1, 2, 3} ~~~ </expected>) End Sub <Fact()> Public Sub BC30297ERR_ConstructorCannotCallItself_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BC30297ERR_ConstructorCannotCallItself_1"> <file name="a.vb"> Imports System Class Tests Public Sub New(i As Integer) Me.New("") End Sub Public Sub New(i As String) Me.New(1) End Sub Public Sub New(i As DateTime) Me.New(1) End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> BC30298: Constructor 'Public Sub New(i As Integer)' cannot call itself: 'Public Sub New(i As Integer)' calls 'Public Sub New(i As String)'. 'Public Sub New(i As String)' calls 'Public Sub New(i As Integer)'. Public Sub New(i As Integer) ~~~ BC30298: Constructor 'Public Sub New(i As String)' cannot call itself: 'Public Sub New(i As String)' calls 'Public Sub New(i As Integer)'. 'Public Sub New(i As Integer)' calls 'Public Sub New(i As String)'. Public Sub New(i As String) ~~~ </errors>) End Sub <Fact()> Public Sub BC30297ERR_ConstructorCannotCallItself_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BC30297ERR_ConstructorCannotCallItself_2"> <file name="a.vb"> Imports System Class Tests Public Sub New(i As Byte) Me.New(CType(i, Int16)) End Sub Public Sub New(i As Int16) Me.New(DateTime.Now) End Sub Public Sub New(i As DateTime) Me.New(DateTime.Now) End Sub Public Sub New(i As Int64) Me.New("") End Sub Public Sub New(i As Int32) Me.New(ctype(1, UInt32)) End Sub Public Sub New(i As UInt32) Me.New("") End Sub Public Sub New(i As String) Me.New(cint(1)) End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> BC30298: Constructor 'Public Sub New(i As Date)' cannot call itself: 'Public Sub New(i As Date)' calls 'Public Sub New(i As Date)'. Public Sub New(i As DateTime) ~~~ BC30298: Constructor 'Public Sub New(i As Integer)' cannot call itself: 'Public Sub New(i As Integer)' calls 'Public Sub New(i As UInteger)'. 'Public Sub New(i As UInteger)' calls 'Public Sub New(i As String)'. 'Public Sub New(i As String)' calls 'Public Sub New(i As Integer)'. Public Sub New(i As Int32) ~~~ BC30298: Constructor 'Public Sub New(i As UInteger)' cannot call itself: 'Public Sub New(i As UInteger)' calls 'Public Sub New(i As String)'. 'Public Sub New(i As String)' calls 'Public Sub New(i As Integer)'. 'Public Sub New(i As Integer)' calls 'Public Sub New(i As UInteger)'. Public Sub New(i As UInt32) ~~~ BC30298: Constructor 'Public Sub New(i As String)' cannot call itself: 'Public Sub New(i As String)' calls 'Public Sub New(i As Integer)'. 'Public Sub New(i As Integer)' calls 'Public Sub New(i As UInteger)'. 'Public Sub New(i As UInteger)' calls 'Public Sub New(i As String)'. Public Sub New(i As String) ~~~ </errors>) End Sub <Fact()> Public Sub BC30297ERR_ConstructorCannotCallItself_3() ' NOTE: Test case ensures that the error in calling the ' constructor suppresses the cycle detection Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BC30297ERR_ConstructorCannotCallItself_3"> <file name="a.vb"> Imports System Class Tests Public Sub New(i As Integer) Me.New("") End Sub Public Sub New(i As String) Me.New(qqq) End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> BC30451: 'qqq' is not declared. It may be inaccessible due to its protection level. Me.New(qqq) ~~~ </errors>) End Sub <Fact()> Public Sub BC30306ERR_MissingSubscript() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="MissingSubscript"> <file name="a.vb"> Module Mod30306 Sub ArExtFrErr002() Dim scen1(,) As Integer ReDim scen1(2, 2) Dim scen4() As Integer 'COMPILEERROR: BC30306, "(", BC30306, "," ReDim scen4(, ) Dim scen8a(,,) As Integer 'COMPILEERROR: BC30306, "(", BC30306, ",", BC30306, "," ReDim scen8a(, , ) Dim Scen8b(,,) As Integer 'COMPILEERROR: BC30306, ",", BC30306, "," ReDim Scen8b(5, , ) Dim scen8c(,,) As Integer 'COMPILEERROR: BC30306, "(", BC30306, "," ReDim scen8c(, , 5) Exit Sub End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30306: Array subscript expression missing. ReDim scen4(, ) ~ BC30306: Array subscript expression missing. ReDim scen4(, ) ~ BC30306: Array subscript expression missing. ReDim scen8a(, , ) ~ BC30306: Array subscript expression missing. ReDim scen8a(, , ) ~ BC30306: Array subscript expression missing. ReDim scen8a(, , ) ~ BC30306: Array subscript expression missing. ReDim Scen8b(5, , ) ~ BC30306: Array subscript expression missing. ReDim Scen8b(5, , ) ~ BC30306: Array subscript expression missing. ReDim scen8c(, , 5) ~ BC30306: Array subscript expression missing. ReDim scen8c(, , 5) ~ </expected>) End Sub ' <Fact()> ' Public Sub BC30310ERR_FieldOfValueFieldOfMarshalByRef3() ' Dim compilation = CompilationUtils.CreateCompilationWithMscorlib( '<compilation name="FieldOfValueFieldOfMarshalByRef3"> ' <file name="a.vb"> ' </file> '</compilation>) ' CompilationUtils.AssertTheseErrors(compilation, '<expected> 'BC30310: Local variable cannot have the same name as the function containing it. ' Dim Foo As Date ' ~~~~ 'BC30310: Local variable cannot have the same name as the function containing it. ' Dim scen16 = 3 ' ~~~~ '</expected>) ' End Sub <Fact()> Public Sub BC30311ERR_TypeMismatch2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System Public Class C Sub FOO() Dim a As S1? Dim b As E1? Dim c As System.Exception Dim d As I1 Dim e As C1.C2 Dim f As C1.C2(,) Dim z = DirectCast (b, S1?) z = DirectCast (b, System.Nullable) z = DirectCast (a, E1?) z = DirectCast (a, System.Nullable) z = DirectCast (c, S1?) z = DirectCast (c, E1?) z = DirectCast (c, System.Nullable) z = DirectCast (d, S1?) z = DirectCast (d, E1?) z = DirectCast (d, System.Nullable) z = DirectCast (d, System.ValueType) z = DirectCast (e, S1?) z = DirectCast (e, E1?) z = DirectCast (e, System.Nullable) z = DirectCast (e, System.ValueType) z = DirectCast (f, S1?) z = DirectCast (f, E1?) z = DirectCast (f, System.Nullable) z = DirectCast (f, System.ValueType) End Sub End Class Structure S1 End Structure Enum E1 one End Enum Interface I1 End Interface Class C1 Public Class C2 End Class End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30311: Value of type 'E1?' cannot be converted to 'S1?'. Dim z = DirectCast (b, S1?) ~ BC30311: Value of type 'E1?' cannot be converted to 'Nullable'. z = DirectCast (b, System.Nullable) ~ BC30311: Value of type 'S1?' cannot be converted to 'E1?'. z = DirectCast (a, E1?) ~ BC30311: Value of type 'S1?' cannot be converted to 'Nullable'. z = DirectCast (a, System.Nullable) ~ BC30311: Value of type 'Exception' cannot be converted to 'S1?'. z = DirectCast (c, S1?) ~ BC42104: Variable 'c' is used before it has been assigned a value. A null reference exception could result at runtime. z = DirectCast (c, S1?) ~ BC30311: Value of type 'Exception' cannot be converted to 'E1?'. z = DirectCast (c, E1?) ~ BC30311: Value of type 'Exception' cannot be converted to 'Nullable'. z = DirectCast (c, System.Nullable) ~ BC30311: Value of type 'I1' cannot be converted to 'S1?'. z = DirectCast (d, S1?) ~ BC42104: Variable 'd' is used before it has been assigned a value. A null reference exception could result at runtime. z = DirectCast (d, S1?) ~ BC30311: Value of type 'I1' cannot be converted to 'E1?'. z = DirectCast (d, E1?) ~ BC30311: Value of type 'Nullable' cannot be converted to 'S1?'. z = DirectCast (d, System.Nullable) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42322: Runtime errors might occur when converting 'I1' to 'Nullable'. z = DirectCast (d, System.Nullable) ~ BC30311: Value of type 'C1.C2' cannot be converted to 'S1?'. z = DirectCast (e, S1?) ~ BC42104: Variable 'e' is used before it has been assigned a value. A null reference exception could result at runtime. z = DirectCast (e, S1?) ~ BC30311: Value of type 'C1.C2' cannot be converted to 'E1?'. z = DirectCast (e, E1?) ~ BC30311: Value of type 'C1.C2' cannot be converted to 'Nullable'. z = DirectCast (e, System.Nullable) ~ BC30311: Value of type 'C1.C2' cannot be converted to 'ValueType'. z = DirectCast (e, System.ValueType) ~ BC30311: Value of type 'C1.C2(*,*)' cannot be converted to 'S1?'. z = DirectCast (f, S1?) ~ BC42104: Variable 'f' is used before it has been assigned a value. A null reference exception could result at runtime. z = DirectCast (f, S1?) ~ BC30311: Value of type 'C1.C2(*,*)' cannot be converted to 'E1?'. z = DirectCast (f, E1?) ~ BC30311: Value of type 'C1.C2(*,*)' cannot be converted to 'Nullable'. z = DirectCast (f, System.Nullable) ~ BC30311: Value of type 'C1.C2(*,*)' cannot be converted to 'ValueType'. z = DirectCast (f, System.ValueType) ~ </expected>) End Sub <Fact()> Public Sub BC30311ERR_TypeMismatch2_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System Class C Shared Sub Main() For Each x As Integer In New Exception() {Nothing, Nothing} Next End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30311: Value of type 'Exception' cannot be converted to 'Integer'. For Each x As Integer In New Exception() {Nothing, Nothing} ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30311ERR_TypeMismatch2_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C Public Shared Sub Main() Dim numbers2D As Integer()() = New Integer()() {New Integer() {1, 2}, New Integer() {1, 2}} For Each i As Integer In numbers2D System.Console.Write("{0} ", i) Next End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30311: Value of type 'Integer()' cannot be converted to 'Integer'. For Each i As Integer In numbers2D ~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30311ERR_TypeMismatch2_3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Module Program Sub Main(args As String()) End Sub Private Function fun(Of T)(Parm1 As T) As T Dim temp As T Return If(temp, temp, 1) End Function End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30311: Value of type 'T' cannot be converted to 'Boolean'. Return If(temp, temp, 1) ~~~~ </expected>) End Sub <Fact()> Public Sub BC30311ERR_TypeMismatch2_4() CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Public Class Test Public Sub Test() Dim at1 = New With {.f1 = Nothing, .f2 = String.Empty} Dim at2 = New With {.f2 = String.Empty, .f1 = Nothing} at1 = at2 End Sub End Class </file> </compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_TypeMismatch2, "at2").WithArguments("<anonymous type: f2 As String, f1 As Object>", "<anonymous type: f1 As Object, f2 As String>")) End Sub <Fact()> Public Sub BC30311ERR_TypeMismatch2_5() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Module Program Public Sub Main() Dim arr1 As Integer(,) = New Integer(2, 1) {{1, 2}, {3, 4}, {5, 6}} arr1 = 0 ' Invalid End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30311: Value of type 'Integer' cannot be converted to 'Integer(*,*)'. arr1 = 0 ' Invalid ~ </expected>) End Sub <Fact()> Public Sub BC30311ERR_TypeMismatch2_6() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module Program Public Sub Main() Dim arr As Integer(,) = New Integer(2, 1) {{6, 7}, {5, 8}, {8, 10}} Dim x As Integer x = arr 'Invalid arr = x 'Invalid End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30311: Value of type 'Integer(*,*)' cannot be converted to 'Integer'. x = arr 'Invalid ~~~ BC30311: Value of type 'Integer' cannot be converted to 'Integer(*,*)'. arr = x 'Invalid ~ </expected>) End Sub <Fact()> Public Sub BC30311ERR_TypeMismatch2_7() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Option Strict Off Option Infer On Class B Public Shared Sub Main() End Sub Private Sub Foo(Of T)() Dim x As T(,) = New T(1, 2) {} Dim Y As T(,) = New T(1, 2) {{1, 2, 3}, {1, 2, 3}} ' invalid End Sub End Class Public Class Class1(Of T) Private x As T(,) = New T(1, 2) {} Private Y As T(,) = New T(1, 2) {{1, 2, 3}, {1, 2, 3}} ' invalid Private Sub Foo() Dim x As T(,) = New T(1, 2) {} Dim Y As T(,) = New T(1, 2) {{1, 2, 3}, {1, 2, 3}} ' invalid End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30311: Value of type 'Integer' cannot be converted to 'T'. Dim Y As T(,) = New T(1, 2) {{1, 2, 3}, {1, 2, 3}} ' invalid ~ BC30311: Value of type 'Integer' cannot be converted to 'T'. Dim Y As T(,) = New T(1, 2) {{1, 2, 3}, {1, 2, 3}} ' invalid ~ BC30311: Value of type 'Integer' cannot be converted to 'T'. Dim Y As T(,) = New T(1, 2) {{1, 2, 3}, {1, 2, 3}} ' invalid ~ BC30311: Value of type 'Integer' cannot be converted to 'T'. Dim Y As T(,) = New T(1, 2) {{1, 2, 3}, {1, 2, 3}} ' invalid ~ BC30311: Value of type 'Integer' cannot be converted to 'T'. Dim Y As T(,) = New T(1, 2) {{1, 2, 3}, {1, 2, 3}} ' invalid ~ BC30311: Value of type 'Integer' cannot be converted to 'T'. Dim Y As T(,) = New T(1, 2) {{1, 2, 3}, {1, 2, 3}} ' invalid ~ BC30311: Value of type 'Integer' cannot be converted to 'T'. Private Y As T(,) = New T(1, 2) {{1, 2, 3}, {1, 2, 3}} ' invalid ~ BC30311: Value of type 'Integer' cannot be converted to 'T'. Private Y As T(,) = New T(1, 2) {{1, 2, 3}, {1, 2, 3}} ' invalid ~ BC30311: Value of type 'Integer' cannot be converted to 'T'. Private Y As T(,) = New T(1, 2) {{1, 2, 3}, {1, 2, 3}} ' invalid ~ BC30311: Value of type 'Integer' cannot be converted to 'T'. Private Y As T(,) = New T(1, 2) {{1, 2, 3}, {1, 2, 3}} ' invalid ~ BC30311: Value of type 'Integer' cannot be converted to 'T'. Private Y As T(,) = New T(1, 2) {{1, 2, 3}, {1, 2, 3}} ' invalid ~ BC30311: Value of type 'Integer' cannot be converted to 'T'. Private Y As T(,) = New T(1, 2) {{1, 2, 3}, {1, 2, 3}} ' invalid ~ BC30311: Value of type 'Integer' cannot be converted to 'T'. Dim Y As T(,) = New T(1, 2) {{1, 2, 3}, {1, 2, 3}} ' invalid ~ BC30311: Value of type 'Integer' cannot be converted to 'T'. Dim Y As T(,) = New T(1, 2) {{1, 2, 3}, {1, 2, 3}} ' invalid ~ BC30311: Value of type 'Integer' cannot be converted to 'T'. Dim Y As T(,) = New T(1, 2) {{1, 2, 3}, {1, 2, 3}} ' invalid ~ BC30311: Value of type 'Integer' cannot be converted to 'T'. Dim Y As T(,) = New T(1, 2) {{1, 2, 3}, {1, 2, 3}} ' invalid ~ BC30311: Value of type 'Integer' cannot be converted to 'T'. Dim Y As T(,) = New T(1, 2) {{1, 2, 3}, {1, 2, 3}} ' invalid ~ BC30311: Value of type 'Integer' cannot be converted to 'T'. Dim Y As T(,) = New T(1, 2) {{1, 2, 3}, {1, 2, 3}} ' invalid ~ </expected>) End Sub <Fact()> Public Sub BC30332ERR_ConvertArrayMismatch4() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ConvertArrayMismatch4"> <file name="a.vb"> Module M1 Class Cls2_1 End Class Class Cls2_2 End Class Sub Main() Dim Ary1_1() As Integer Dim Ary1_2() As Long = New Long() {1, 2} 'COMPILEERROR: BC30332, "Ary1_2" Ary1_1 = CType(Ary1_2, Integer()) Dim Ary2_1() As Cls2_1 = New Cls2_1() {} Dim Ary2_2(,) As Cls2_2 'COMPILEERROR: BC30332, "Ary2_1" Ary2_2 = CType(Ary2_1, Cls2_2()) Dim Ary3_1(,) As Double = New Double(,) {} Dim Ary3_2(,) As Cls2_2 'COMPILEERROR: BC30332, "Ary3_1" Ary3_2 = CType(Ary3_1, Cls2_2(,)) 'COMPILEERROR: BC30332, "Ary3_2" Ary3_1 = CType(Ary3_2, Double(,)) Dim Ary4_1() As Integer Dim Ary4_2() As Object = New Object() {} Ary4_1 = CType(Ary4_2, Integer()) End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30332: Value of type 'Long()' cannot be converted to 'Integer()' because 'Long' is not derived from 'Integer'. Ary1_1 = CType(Ary1_2, Integer()) ~~~~~~ BC30332: Value of type 'M1.Cls2_1()' cannot be converted to 'M1.Cls2_2()' because 'M1.Cls2_1' is not derived from 'M1.Cls2_2'. Ary2_2 = CType(Ary2_1, Cls2_2()) ~~~~~~ BC30332: Value of type 'Double(*,*)' cannot be converted to 'M1.Cls2_2(*,*)' because 'Double' is not derived from 'M1.Cls2_2'. Ary3_2 = CType(Ary3_1, Cls2_2(,)) ~~~~~~ BC30332: Value of type 'M1.Cls2_2(*,*)' cannot be converted to 'Double(*,*)' because 'M1.Cls2_2' is not derived from 'Double'. Ary3_1 = CType(Ary3_2, Double(,)) ~~~~~~ BC30332: Value of type 'Object()' cannot be converted to 'Integer()' because 'Object' is not derived from 'Integer'. Ary4_1 = CType(Ary4_2, Integer()) ~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30332ERR_ConvertArrayMismatch4_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ConvertArrayMismatch4"> <file name="a.vb"> Option Strict On Imports System Module Module1 Sub Main() Dim arrString$(,) = New Decimal(1, 2) {} ' Invalid Dim arrInteger%(,) = New Decimal(1, 2) {} ' Invalid Dim arrLong&amp;(,) = New Decimal(1, 2) {} ' Invalid Dim arrSingle!(,) = New Decimal(1, 2) {} ' Invalid End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30332: Value of type 'Decimal(*,*)' cannot be converted to 'String(*,*)' because 'Decimal' is not derived from 'String'. Dim arrString$(,) = New Decimal(1, 2) {} ' Invalid ~~~~~~~~~~~~~~~~~~~~ BC30332: Value of type 'Decimal(*,*)' cannot be converted to 'Integer(*,*)' because 'Decimal' is not derived from 'Integer'. Dim arrInteger%(,) = New Decimal(1, 2) {} ' Invalid ~~~~~~~~~~~~~~~~~~~~ BC30332: Value of type 'Decimal(*,*)' cannot be converted to 'Long(*,*)' because 'Decimal' is not derived from 'Long'. Dim arrLong&amp;(,) = New Decimal(1, 2) {} ' Invalid ~~~~~~~~~~~~~~~~~~~~ BC30332: Value of type 'Decimal(*,*)' cannot be converted to 'Single(*,*)' because 'Decimal' is not derived from 'Single'. Dim arrSingle!(,) = New Decimal(1, 2) {} ' Invalid ~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30333ERR_ConvertObjectArrayMismatch3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ConvertObjectArrayMismatch3"> <file name="a.vb"> Module M1 Sub Main() Dim Ary1() As Integer = New Integer() {} Dim Ary2() As Object Ary2 = CType(Ary1, Object()) End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30333: Value of type 'Integer()' cannot be converted to 'Object()' because 'Integer' is not a reference type. Ary2 = CType(Ary1, Object()) ~~~~ </expected>) End Sub <WorkItem(579764, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/579764")> <Fact()> Public Sub BC30311ERR_WithArray_ParseAndDeclarationErrors() 'This test is because previously in native command line compiler we would produce errors for both parsing and binding errors, now ' we won't produce the binding if parsing was not successful from the command line. However, the diagnostics will display both messages and ' hence the need for two tests to verify this behavior. Dim source = <compilation> <file name="ParseErrorOnly.vb"> Module M Dim x As Integer() {1, 2, 3} Dim y = CType({1, 2, 3}, System.Collections.Generic.List(Of Integer)) Sub main End Sub End Module </file> </compilation> CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_ExpectedEOS, "{"), Diagnostic(ERRID.ERR_TypeMismatch2, "{1, 2, 3}").WithArguments("Integer()", "System.Collections.Generic.List(Of Integer)")) ' This 2nd scenario will produce 1 error because it passed the parsing stage and now ' fails in the binding source = <compilation> <file name="ParseOK.vb"> Module M Dim x As Integer() = {1, 2, 3} Dim y = CType({1, 2, 3}, System.Collections.Generic.List(Of Integer)) Sub main End Sub End Module </file> </compilation> CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_TypeMismatch2, "{1, 2, 3}").WithArguments("Integer()", "System.Collections.Generic.List(Of Integer)")) End Sub <Fact(), WorkItem(542069, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542069")> Public Sub BC30337ERR_ForLoopType1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ForLoopType1"> <file name="a.vb"> Module M1 Sub Test() 'COMPILEERROR : BC30337, "i" For i = New base To New first() Next For j = New base To New first() step new second() Next End Sub End Module Class base End Class Class first Inherits base Overloads Shared Widening Operator CType(ByVal d As first) As second Return New second() End Operator End Class Class second Inherits base Overloads Shared Widening Operator CType(ByVal d As second) As first Return New first() End Operator End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30311: Value of type 'Integer' cannot be converted to 'base'. For i = New base To New first() ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC33038: Type 'base' must define operator '+' to be used in a 'For' statement. For j = New base To New first() step new second() ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC33038: Type 'base' must define operator '-' to be used in a 'For' statement. For j = New base To New first() step new second() ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC33038: Type 'base' must define operator '&lt;=' to be used in a 'For' statement. For j = New base To New first() step new second() ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC33038: Type 'base' must define operator '>=' to be used in a 'For' statement. For j = New base To New first() step new second() ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact(), WorkItem(542069, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542069")> Public Sub BC30337ERR_ForLoopType1_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ForLoopType1"> <file name="a.vb"> Option Strict On Option Infer Off Module Program Sub Main(args As String()) For x As Date = #1/2/0003# To 10 Next End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30337: 'For' loop control variable cannot be of type 'Date' because the type does not support the required operators. For x As Date = #1/2/0003# To 10 ~~~~~~~~~ </expected>) End Sub <Fact(), WorkItem(542069, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542069"), WorkItem(544464, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544464")> Public Sub BC30337ERR_ForLoopType1_3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ForLoopType1"> <file name="a.vb"> Option Strict On Option Infer Off Interface IFoo End Interface Module Program Sub Main(args As String()) For x As Boolean = False To True Next Dim foo as Boolean For foo = False To True Next for z as IFoo = nothing to nothing next End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30337: 'For' loop control variable cannot be of type 'Boolean' because the type does not support the required operators. For x As Boolean = False To True ~~~~~~~~~~~~ BC30337: 'For' loop control variable cannot be of type 'Boolean' because the type does not support the required operators. For foo = False To True ~~~ BC30337: 'For' loop control variable cannot be of type 'IFoo' because the type does not support the required operators. for z as IFoo = nothing to nothing ~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30367ERR_NoDefaultNotExtend1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C Shared Sub M(Of T)(x As C, y As T) N(x(0)) N(x!P) x(0) N(y(1)) N(y!Q) y(1) End Sub Shared Sub N(o As Object) End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30367: Class 'C' cannot be indexed because it has no default property. N(x(0)) ~ BC30367: Class 'C' cannot be indexed because it has no default property. N(x!P) ~ BC30454: Expression is not a method. x(0) ~ BC30547: 'T' cannot be indexed because it has no default property. N(y(1)) ~ BC30547: 'T' cannot be indexed because it has no default property. N(y!Q) ~ BC30454: Expression is not a method. y(1) ~ </expected>) End Sub <Fact()> Public Sub BC30369ERR_BadInstanceMemberAccess_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Structure S1 Dim b3 As Integer() Public Shared Sub Scenario_6() dim b4 = b3 End Sub shared Function foo() As Integer() Return b3 End Function End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30369: Cannot refer to an instance member of a class from within a shared method or shared member initializer without an explicit instance of the class. dim b4 = b3 ~~ BC30369: Cannot refer to an instance member of a class from within a shared method or shared member initializer without an explicit instance of the class. Return b3 ~~ </expected>) End Sub <Fact()> Public Sub BC30369ERR_BadInstanceMemberAccess_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C Property P Get Return Nothing End Get Set End Set End Property Shared Sub M() Dim o = P P = o End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30369: Cannot refer to an instance member of a class from within a shared method or shared member initializer without an explicit instance of the class. Dim o = P ~ BC30369: Cannot refer to an instance member of a class from within a shared method or shared member initializer without an explicit instance of the class. P = o ~ </expected>) End Sub <Fact()> Public Sub BC30369ERR_BadInstanceMemberAccess_3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C Shared Sub Main() For Each x As Integer In F(x) Next End Sub Private Sub F(x As Integer) End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30369: Cannot refer to an instance member of a class from within a shared method or shared member initializer without an explicit instance of the class. For Each x As Integer In F(x) ~ </expected>) End Sub <Fact()> Public Sub BC30369ERR_BadInstanceMemberAccess_4() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C Shared Sub Main() For Each x As Integer In F(x) Next End Sub Private Function F(x As Integer) As Object Return New Object() End Function End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30369: Cannot refer to an instance member of a class from within a shared method or shared member initializer without an explicit instance of the class. For Each x As Integer In F(x) ~ </expected>) End Sub <Fact()> Public Sub BC30369ERR_BadInstanceMemberAccess_5() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C Property P1(ByVal x As Integer) As integer Get Return x +5 End Get Set(ByVal Value As integer) End Set End Property Public Shared Sub Main() For Each x As integer In New integer() {P1(x), P1(x), P1(x)} Next End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30369: Cannot refer to an instance member of a class from within a shared method or shared member initializer without an explicit instance of the class. For Each x As integer In New integer() {P1(x), P1(x), P1(x)} ~~ BC30369: Cannot refer to an instance member of a class from within a shared method or shared member initializer without an explicit instance of the class. For Each x As integer In New integer() {P1(x), P1(x), P1(x)} ~~ BC30369: Cannot refer to an instance member of a class from within a shared method or shared member initializer without an explicit instance of the class. For Each x As integer In New integer() {P1(x), P1(x), P1(x)} ~~ </expected>) End Sub <Fact()> Public Sub BC30369ERR_BadInstanceMemberAccess_6() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C Public Shared Sub Main() For Each x As Integer In New Integer() {foo(x), foo(x), foo(x)} Next End Sub Function foo(ByRef x As Integer) As Integer x = 10 Return x + 10 End Function End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30369: Cannot refer to an instance member of a class from within a shared method or shared member initializer without an explicit instance of the class. For Each x As Integer In New Integer() {foo(x), foo(x), foo(x)} ~~~ BC30369: Cannot refer to an instance member of a class from within a shared method or shared member initializer without an explicit instance of the class. For Each x As Integer In New Integer() {foo(x), foo(x), foo(x)} ~~~ BC30369: Cannot refer to an instance member of a class from within a shared method or shared member initializer without an explicit instance of the class. For Each x As Integer In New Integer() {foo(x), foo(x), foo(x)} ~~~ </expected>) End Sub <Fact()> Public Sub BC30369ERR_BadInstanceMemberAccess_7() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Option Strict Off Option Infer On Public Class MyClass1 Dim global_x As Integer = 10 Const global_y As Long = 20 Public Shared Sub Main() For global_x = global_y To 10 Next End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30369: Cannot refer to an instance member of a class from within a shared method or shared member initializer without an explicit instance of the class. For global_x = global_y To 10 ~~~~~~~~ </expected>) End Sub <Fact, WorkItem(529193, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529193")> Public Sub BC30369ERR_BadInstanceMemberAccess_8() CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class derive Shared Sub main() TestEvents End Sub Shared Sub TestEvents() Dim Obj As New Class1 RemoveHandler Obj.MyEvent, AddressOf EventHandler End Sub Function EventHandler() Return Nothing End Function Public Class Class1 Public Event MyEvent(ByRef x As Decimal) Sub CauseSomeEvent() RaiseEvent MyEvent(x:=1) End Sub End Class End Class </file> </compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_BadInstanceMemberAccess, "AddressOf EventHandler")) End Sub <Fact()> Public Sub BC30375ERR_NewIfNullOnNonClass() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="NewIfNullOnNonClass"> <file name="a.vb"> Module M1 Sub Foo() Dim interf1 As New Interface1() Dim interf2 = New Interface1() End Sub End Module Interface Interface1 End Interface </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30375: 'New' cannot be used on an interface. Dim interf1 As New Interface1() ~~~~~~~~~~~~~~~~ BC30375: 'New' cannot be used on an interface. Dim interf2 = New Interface1() ~~~~~~~~~~~~~~~~ </expected>) End Sub ''' We decided to not implement this for Roslyn as BC30569 and BC31411 cover the scenarios that BC30376 addresses. <Fact()> Public Sub BC30376ERR_NewIfNullOnAbstractClass1() CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="NewIfNullOnAbstractClass1"> <file name="a.vb"> Module M1 Sub Foo() Throw (New C1) End Sub End Module MustInherit Class C1 MustOverride Sub foo() End Class </file> </compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_NewOnAbstractClass, "New C1"), Diagnostic(ERRID.ERR_CantThrowNonException, "Throw (New C1)").WithArguments("C1")) End Sub <Fact(), WorkItem(999399, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/999399")> Public Sub BC30387ERR_NoConstructorOnBase2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="NoConstructorOnBase2"> <file name="a.vb"> Module M1 Class Base Sub New(ByVal x As Integer) End Sub End Class Class c1 Inherits Base End Class End Module </file> </compilation>) Dim expected = <expected> BC30387: Class 'M1.c1' must declare a 'Sub New' because its base class 'M1.Base' does not have an accessible 'Sub New' that can be called with no arguments. Class c1 ~~ </expected> CompilationUtils.AssertTheseDiagnostics(compilation, expected) CompilationUtils.AssertTheseDiagnostics(compilation.GetDiagnosticsForSyntaxTree(CompilationStage.Compile, compilation.SyntaxTrees.Single()), expected) End Sub <Fact()> Public Sub BC30389ERR_InaccessibleSymbol2() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module mod30389 Sub foo() 'COMPILEERROR: BC30389, "Namespace1.Module1.Class1.Struct1" Dim Scen3 As Namespace1.Module1.Class1.Struct1 Exit Sub End Sub End Module Namespace Namespace1 Module Module1 Private Class Class1 Public Structure Struct1 Public Int As Integer End Structure End Class End Module End Namespace </file> </compilation>) Dim expectedErrors1 = <errors> BC42024: Unused local variable: 'Scen3'. Dim Scen3 As Namespace1.Module1.Class1.Struct1 ~~~~~ BC30389: 'Namespace1.Module1.Class1' is not accessible in this context because it is 'Private'. Dim Scen3 As Namespace1.Module1.Class1.Struct1 ~~~~~~~~~~~~~~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC30389ERR_InaccessibleSymbol2_1() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C Protected Structure S End Structure Private F As Integer Private Property P As Integer Protected Shared ReadOnly Property Q(o) Get Return Nothing End Get End Property End Class Class D Shared Sub M(o) Dim x As C = Nothing M(New C.S()) M(x.F) M(x.P) M(C.Q(Nothing)) End Sub End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC30389: 'C.S' is not accessible in this context because it is 'Protected'. M(New C.S()) ~~~ BC30389: 'C.F' is not accessible in this context because it is 'Private'. M(x.F) ~~~ BC30389: 'C.P' is not accessible in this context because it is 'Private'. M(x.P) ~~~ BC30389: 'C.Q(o As Object)' is not accessible in this context because it is 'Protected'. M(C.Q(Nothing)) ~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC30390ERR_InaccessibleMember3() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C Protected Shared Function F() Return Nothing End Function Private Sub M(o) End Sub End Class Class D Shared Sub M(x As C) x.M(C.F()) End Sub End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC30390: 'C.Private Sub M(o As Object)' is not accessible in this context because it is 'Private'. x.M(C.F()) ~~~ BC30390: 'C.Protected Shared Function F() As Object' is not accessible in this context because it is 'Protected'. x.M(C.F()) ~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC30390ERR_InaccessibleMember3_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Class C1 Public Delegate Sub myDelegate() private shared sub mySub() end sub End Class Module M1 Sub Main() Dim d1 As C1.myDelegate d1 = New C1.myDelegate(addressof C1.mySub) d1 = addressof C1.mysub End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30390: 'C1.Private Shared Sub mySub()' is not accessible in this context because it is 'Private'. d1 = New C1.myDelegate(addressof C1.mySub) ~~~~~~~~ BC30390: 'C1.Private Shared Sub mySub()' is not accessible in this context because it is 'Private'. d1 = addressof C1.mysub ~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30390ERR_InaccessibleMember3_2a() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="BC30390ERR_InaccessibleMember3_2a"> <file name="a.vb"> Imports System Module M1 Class B Private Sub M() Console.WriteLine("B.M()") End Sub End Class Class D Inherits B Public Sub M() Console.WriteLine("D.M()") End Sub Public Sub Test() MyBase.M() Me.M() End Sub End Class Public Sub Main() Call (New D()).Test() End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30390: 'B.Private Sub M()' is not accessible in this context because it is 'Private'. MyBase.M() ~~~~~~~~ </expected>) End Sub <WorkItem(540640, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540640")> <Fact()> Public Sub BC30390ERR_InaccessibleMember3_3() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BC30390ERR_InaccessibleMember3_3"> <file name="a.vb"><![CDATA[ Imports System Namespace AttrRegress001 Public Class Attr Inherits Attribute Public Property PriSet() As Short Get Return 1 End Get Private Set(ByVal value As Short) End Set End Property Public Property ProSet() As Short Get Return 2 End Get Protected Set(ByVal value As Short) End Set End Property End Class 'COMPILEERROR: BC30390, "foo1" <Attr(PriSet:=1)> Class Scen2 End Class 'COMPILEERROR: BC30390, "foo2" <Attr(ProSet:=1)> Class Scen3 End Class End Namespace ]]></file> </compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_InaccessibleMember3, "PriSet").WithArguments("AttrRegress001.Attr", "Public Property PriSet As Short", "Private"), Diagnostic(ERRID.ERR_InaccessibleMember3, "ProSet").WithArguments("AttrRegress001.Attr", "Public Property ProSet As Short", "Protected")) End Sub <Fact()> Public Sub BC30392ERR_CatchNotException1() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="CatchNotException1"> <file name="a.vb"> Module M1 Sub Foo() Try Catch o As Object Throw End Try End Sub End Module </file> </compilation>) Dim expectedErrors1 = <errors> BC30392: 'Catch' cannot catch type 'Object' because it is not 'System.Exception' or a class that inherits from 'System.Exception'. Catch o As Object ~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC30393ERR_ExitTryNotWithinTry() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="ExitTryNotWithinTry"> <file name="a.vb"> Class S1 sub FOO() if (true) exit try End If End sub End CLASS </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30393: 'Exit Try' can only appear inside a 'Try' statement. exit try ~~~~~~~~ </expected>) End Sub <WorkItem(542801, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542801")> <Fact()> Public Sub BC30393ERR_ExitTryNotWithinTry_ExitFromFinally() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndReferences( <compilation name="ExitTryNotWithinTry"> <file name="a.vb"> Imports System Imports System.Linq Class BaseClass Function Method() As String Dim x = New Integer() {} x.Where(Function(y) Try Exit Try Catch ex1 As Exception When True Exit Try Finally Exit Try End Try Return y = "" End Function) Return "x" End Function End Class Class DerivedClass Inherits BaseClass Shared Sub Main() End Sub End Class </file> </compilation>, {Net40.SystemCore}) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30393: 'Exit Try' can only appear inside a 'Try' statement. Exit Try ~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30399ERR_MyBaseAbstractCall1_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> MustInherit Class Base MustOverride Sub Pearl() End Class MustInherit Class C2 Inherits Base Sub foo() Call MyBase.Pearl() End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30399: 'MyBase' cannot be used with method 'Public MustOverride Sub Pearl()' because it is declared 'MustOverride'. Call MyBase.Pearl() ~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30399ERR_MyBaseAbstractCall1_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> MustInherit Class A MustOverride Property P End Class Class B Inherits A Overrides Property P Get Return Nothing End Get Set(ByVal value As Object) End Set End Property Sub M() MyBase.P = MyBase.P End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30399: 'MyBase' cannot be used with method 'Public MustOverride Property P As Object' because it is declared 'MustOverride'. MyBase.P = MyBase.P ~~~~~~~~ BC30399: 'MyBase' cannot be used with method 'Public MustOverride Property P As Object' because it is declared 'MustOverride'. MyBase.P = MyBase.P ~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30399ERR_MyBaseAbstractCall1_3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System MustInherit Class Base MustOverride Sub Pearl() End Class MustInherit Class C2 Inherits Base Sub foo() Dim _action As Action = AddressOf MyBase.Pearl End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30399: 'MyBase' cannot be used with method 'Public MustOverride Sub Pearl()' because it is declared 'MustOverride'. Dim _action As Action = AddressOf MyBase.Pearl ~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30399ERR_MyBaseAbstractCall1_4() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System MustInherit Class Base MustOverride Function GetBar(i As Integer) As Integer End Class MustInherit Class C2 Inherits Base Sub foo() Dim f As Func(Of Func(Of Integer, String)) = Function() New Func(Of Integer, String)(AddressOf MyBase.GetBar) End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30399: 'MyBase' cannot be used with method 'Public MustOverride Function GetBar(i As Integer) As Integer' because it is declared 'MustOverride'. Dim f As Func(Of Func(Of Integer, String)) = Function() New Func(Of Integer, String)(AddressOf MyBase.GetBar) ~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30399ERR_MyBaseAbstractCall1_5() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System MustInherit Class Base MustOverride Function GetBar(i As Integer) As Integer End Class MustInherit Class C2 Inherits Base Public FLD As Func(Of Func(Of Integer, String)) = Function() New Func(Of Integer, String)(AddressOf MyBase.GetBar) Public Property PROP As Func(Of Func(Of Integer, String)) = Function() New Func(Of Integer, String)(AddressOf MyBase.GetBar) Public Overrides Function GetBar(i As Integer) As Integer Return Nothing End Function End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30399: 'MyBase' cannot be used with method 'Public MustOverride Function GetBar(i As Integer) As Integer' because it is declared 'MustOverride'. Function() New Func(Of Integer, String)(AddressOf MyBase.GetBar) ~~~~~~~~~~~~~ BC30399: 'MyBase' cannot be used with method 'Public MustOverride Function GetBar(i As Integer) As Integer' because it is declared 'MustOverride'. Function() New Func(Of Integer, String)(AddressOf MyBase.GetBar) ~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30399ERR_MyBaseAbstractCall1_6() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Class Base Function GetBar(i As Integer) As Integer Return Nothing End Function End Class Class C2 Inherits Base Sub foo() Dim f As Func(Of Func(Of Integer, String)) = Function() New Func(Of Integer, String)(AddressOf MyBase.GetBar) End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <errors></errors>) End Sub <Fact()> Public Sub BC30399ERR_MyBaseAbstractCall1_7() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Class Base Shared Function GetBar(i As Integer) As Integer Return 0 End Function Function GetFoo(i As Integer) As Integer Return 0 End Function End Class MustInherit Class C2 Inherits Base Public FLD As Func(Of Func(Of Integer, String)) = Function() New Func(Of Integer, String)(AddressOf MyBase.GetBar) Public Property PROP As Func(Of Func(Of Integer, String)) = Function() New Func(Of Integer, String)(AddressOf MyBase.GetFoo) End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <errors></errors>) End Sub <Fact> Public Sub BC30399ERR_MyBaseAbstractCall1_8() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Imports System.Runtime.CompilerServices MustInherit Class B Sub New() End Sub <DllImport("doo")> Shared Function DllImp(i As Integer) As Integer End Function Declare Function DeclareFtn Lib "foo" (i As Integer) As Integer End Class MustInherit Class C Inherits B Public FLD1 As Func(Of Func(Of Integer, String)) = Function() New Func(Of Integer, String)(AddressOf MyBase.DllImp) Public FLD2 As Func(Of Func(Of Integer, String)) = Function() New Func(Of Integer, String)(AddressOf MyBase.DeclareFtn) End Class ]]> </file> </compilation> CompileAndVerify(source) End Sub <Fact()> Public Sub BC30414ERR_ConvertArrayRankMismatch2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ConvertArrayRankMismatch2"> <file name="a.vb"> Module M1 Sub Main() Dim Ary1() As Integer = New Integer() {1} Dim Ary2 As Integer(,) = CType(Ary1, Integer(,)) End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30414: Value of type 'Integer()' cannot be converted to 'Integer(*,*)' because the array types have different numbers of dimensions. Dim Ary2 As Integer(,) = CType(Ary1, Integer(,)) ~~~~ </expected>) End Sub <Fact()> Public Sub BC30414ERR_ConvertArrayRankMismatch2_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ConvertArrayRankMismatch2"> <file name="a.vb"> Option Strict On Imports System Module Module1 Sub Main() Dim arr1 As Integer(,,) = New Integer(9, 5) {} ' Invalid Dim arr2 As Integer() = New Integer(9, 5) {} ' Invalid Dim arr3() As Integer = New Integer(2, 3) {} ' Invalid Dim arr4(,) As Integer = New Integer(2, 3, 1) {} ' Invalid End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30414: Value of type 'Integer(*,*)' cannot be converted to 'Integer(*,*,*)' because the array types have different numbers of dimensions. Dim arr1 As Integer(,,) = New Integer(9, 5) {} ' Invalid ~~~~~~~~~~~~~~~~~~~~ BC30414: Value of type 'Integer(*,*)' cannot be converted to 'Integer()' because the array types have different numbers of dimensions. Dim arr2 As Integer() = New Integer(9, 5) {} ' Invalid ~~~~~~~~~~~~~~~~~~~~ BC30414: Value of type 'Integer(*,*)' cannot be converted to 'Integer()' because the array types have different numbers of dimensions. Dim arr3() As Integer = New Integer(2, 3) {} ' Invalid ~~~~~~~~~~~~~~~~~~~~ BC30414: Value of type 'Integer(*,*,*)' cannot be converted to 'Integer(*,*)' because the array types have different numbers of dimensions. Dim arr4(,) As Integer = New Integer(2, 3, 1) {} ' Invalid ~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30414ERR_ConvertArrayRankMismatch2_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ConvertArrayRankMismatch2"> <file name="a.vb"> Option Strict On Imports System Module Module1 Sub Main() Dim myArray10 As Integer(,) = {1, 2} ' Invalid Dim myArray11 As Integer(,) = {{{1, 2}}} ' Invalid End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30414: Value of type 'Integer()' cannot be converted to 'Integer(*,*)' because the array types have different numbers of dimensions. Dim myArray10 As Integer(,) = {1, 2} ' Invalid ~~~~~~ BC30414: Value of type 'Integer(*,*,*)' cannot be converted to 'Integer(*,*)' because the array types have different numbers of dimensions. Dim myArray11 As Integer(,) = {{{1, 2}}} ' Invalid ~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30415ERR_RedimRankMismatch() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="RedimRankMismatch"> <file name="a.vb"> Class C1 Sub foo(ByVal Ary() As Date) ReDim Ary(4, 4) End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30415: 'ReDim' cannot change the number of dimensions of an array. ReDim Ary(4, 4) ~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30424ERR_ConstAsNonConstant() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="ConstAsNonConstant"> <file name="a.vb"> Class C1(Of T) Const f As T = Nothing Const c As C1(Of T) = Nothing End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30424: Constants must be of an intrinsic or enumerated type, not a class, structure, type parameter, or array type. Const f As T = Nothing ~ BC30424: Constants must be of an intrinsic or enumerated type, not a class, structure, type parameter, or array type. Const c As C1(Of T) = Nothing ~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30424ERR_ConstAsNonConstant02() Dim source = <compilation> <file name="a.vb"> Option strict on imports system Enum E foo End Enum structure S1 end structure Class C1 ' should work public const f1 as E = E.foo public const f2 as object = nothing public const f3 as boolean = True ' should not work public const f4 as C1 = nothing public const f5 as S1 = nothing public const f6() as integer = {1,2,3} public const f7() as S1 = {new S1(), new S1(), new S1()} Public shared Sub Main(args() as string) End sub End Class </file> </compilation> Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) CompilationUtils.AssertTheseDiagnostics(c1, <expected> BC30424: Constants must be of an intrinsic or enumerated type, not a class, structure, type parameter, or array type. public const f4 as C1 = nothing ~~ BC30424: Constants must be of an intrinsic or enumerated type, not a class, structure, type parameter, or array type. public const f5 as S1 = nothing ~~ BC30424: Constants must be of an intrinsic or enumerated type, not a class, structure, type parameter, or array type. public const f6() as integer = {1,2,3} ~~ BC30424: Constants must be of an intrinsic or enumerated type, not a class, structure, type parameter, or array type. public const f7() as S1 = {new S1(), new S1(), new S1()} ~~ </expected>) ' todo: the last two errors need to be removed once collection initialization is supported End Sub <Fact()> Public Sub BC30438ERR_ConstantWithNoValue() Dim source = <compilation> <file name="a.vb"> Option Strict On Option Infer On imports system Class C1 public const f1 public const f2 as object public const f3 as boolean Public shared Sub Main(args() as string) End sub End Class </file> </compilation> Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) CompilationUtils.AssertTheseDiagnostics(c1, <expected> BC30438: Constants must have a value. public const f1 ~~ BC30438: Constants must have a value. public const f2 as object ~~ BC30438: Constants must have a value. public const f3 as boolean ~~ </expected>) End Sub <Fact()> Public Sub BC30439ERR_ExpressionOverflow1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="ConvertArrayRankMismatch2"> <file name="a.vb"> Public Class C1 Shared Sub Main() Dim i As Integer i = 10000000000000 System.Console.WriteLine(i) End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30439: Constant expression not representable in type 'Integer'. i = 10000000000000 ~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30439ERR_ExpressionOverflow1_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="ConvertArrayRankMismatch2"> <file name="a.vb"> Public Class C1 Shared Sub Main() Dim FIRST As UInteger = (0UI - 860UI) End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30439: Constant expression not representable in type 'UInteger'. Dim FIRST As UInteger = (0UI - 860UI) ~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30451ERR_NameNotDeclared1_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C1 function foo() as integer return 1 End function End Class Class C2 function foo1() as integer dim s = foo() return 1 End function End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30451: 'foo' is not declared. It may be inaccessible due to its protection level. dim s = foo() ~~~ </expected>) End Sub <Fact()> Public Sub BC30451ERR_NameNotDeclared1_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C Shared ReadOnly Property P Get Return Nothing End Get End Property ReadOnly Property Q Get Return Nothing End Get End Property Property R Sub M() set_P(get_P) set_Q(get_Q) set_R(get_R) End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30451: 'set_P' is not declared. It may be inaccessible due to its protection level. set_P(get_P) ~~~~~ BC30451: 'get_P' is not declared. It may be inaccessible due to its protection level. set_P(get_P) ~~~~~ BC30451: 'set_Q' is not declared. It may be inaccessible due to its protection level. set_Q(get_Q) ~~~~~ BC30451: 'get_Q' is not declared. It may be inaccessible due to its protection level. set_Q(get_Q) ~~~~~ BC30451: 'set_R' is not declared. It may be inaccessible due to its protection level. set_R(get_R) ~~~~~ BC30451: 'get_R' is not declared. It may be inaccessible due to its protection level. set_R(get_R) ~~~~~ </expected>) End Sub <Fact()> Public Sub BC30451ERR_NameNotDeclared1_3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="NoDirectDelegateConstruction1"> <file name="a.vb"> Class C1 Public Delegate Sub myDelegate() private shared sub mySub() end sub End Class Module M1 Sub Main() Dim d1 As C1.myDelegate d1 = New C1.myDelegate(addressof BORG) d1 = addressof BORG End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30451: 'BORG' is not declared. It may be inaccessible due to its protection level. d1 = New C1.myDelegate(addressof BORG) ~~~~ BC30451: 'BORG' is not declared. It may be inaccessible due to its protection level. d1 = addressof BORG ~~~~ </expected>) End Sub <Fact()> Public Sub BC30451ERR_NameNotDeclared1_4() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="NoDirectDelegateConstruction1"> <file name="a.vb"> Class C Public Shared Sub Main() For Each x As Integer In New Integer() {1, 1, 1} 'COMPILEERROR: BC30451, "y" Next y 'escaped vs. nonescaped (should work)" For Each [x] As Integer In New Integer() {1, 1, 1} Next x End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30451: 'y' is not declared. It may be inaccessible due to its protection level. Next y ~ </expected>) End Sub <Fact()> Public Sub BC30451ERR_NameNotDeclared1_5() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="NoDirectDelegateConstruction1"> <file name="a.vb"> Option Infer Off Option Strict On Public Class MyClass1 Public Shared Sub Main() For n = 0 To 2 For m = 1 To 2 Next n Next m End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30451: 'n' is not declared. It may be inaccessible due to its protection level. For n = 0 To 2 ~ BC30451: 'm' is not declared. It may be inaccessible due to its protection level. For m = 1 To 2 ~ BC30451: 'n' is not declared. It may be inaccessible due to its protection level. Next n ~ BC30451: 'm' is not declared. It may be inaccessible due to its protection level. Next m ~ </expected>) End Sub <Fact()> Public Sub BC30451ERR_NameNotDeclared1_NoErrorDuplicationForObjectInitializer() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="BC30451ERR_NameNotDeclared1_NoErrorDuplicationForObjectInitializer"> <file name="a.vb"> Imports System Imports System.Collections.Generic Class S Public Y As Object End Class Public Module Program Public Sub Main(args() As String) Dim a, b, c As New S() With {.Y = aaa} End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30451: 'aaa' is not declared. It may be inaccessible due to its protection level. Dim a, b, c As New S() With {.Y = aaa} ~~~ </expected>) End Sub <Fact()> Public Sub BC30451ERR_NameNotDeclared1_NoWarningDuplicationForObjectInitializer() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="BC30451ERR_NameNotDeclared1_NoWarningDuplicationForObjectInitializer"> <file name="a.vb"> Option Strict On Imports System Class S Public Y As Byte End Class Public Module Program Public Sub Main(args() As String) Dim x As Integer = 1 Dim a, b, c As New S() With {.Y = x} End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30512: Option Strict On disallows implicit conversions from 'Integer' to 'Byte'. Dim a, b, c As New S() With {.Y = x} ~ </expected>) End Sub <Fact()> Public Sub BC30452ERR_BinaryOperands3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BinaryOperands3"> <file name="a.vb"> option infer on Class C1 dim d = new c1() + new c1.c2() function foo() as integer return 1 End function Class C2 function foo1() as integer dim d1 = new c1() dim d2 = new c2() dim d3 = d1 + d2 return 1 End function End Class End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30452: Operator '+' is not defined for types 'C1' and 'C1.C2'. dim d = new c1() + new c1.c2() ~~~~~~~~~~~~~~~~~~~~~~ BC30452: Operator '+' is not defined for types 'C1' and 'C1.C2'. dim d3 = d1 + d2 ~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30452ERR_BinaryOperands3_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BinaryOperands3"> <file name="a.vb"> Class C1 Class C2 function foo1(byval d1 as c1, byval d2 as c2 )as integer dim d3 as object = d1 + d2 return 1 End function End Class End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30452: Operator '+' is not defined for types 'C1' and 'C1.C2'. dim d3 as object = d1 + d2 ~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30452ERR_BinaryOperands3_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="None"> <file name="a.vb"> Imports System class myClass1 shared result = New Guid() And New Guid() End class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30452: Operator 'And' is not defined for types 'Guid' and 'Guid'. shared result = New Guid() And New Guid() ~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30452ERR_BinaryOperands3_3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="None"> <file name="a.vb"> Imports System Module Program Sub Main(args As String()) Dim f1 As New Foo(), f2 As New Foo(), f3 As New Foo() Dim b As Boolean = True f3 = If(b, f1 = New Foo(), f2 = New Foo()) b = False f3 = If(b, f1 = New Foo(), f2 = New Foo()) End Sub End Module Class Foo Public i As Integer End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30452: Operator '=' is not defined for types 'Foo' and 'Foo'. f3 = If(b, f1 = New Foo(), f2 = New Foo()) ~~~~~~~~~~~~~~ BC30452: Operator '=' is not defined for types 'Foo' and 'Foo'. f3 = If(b, f1 = New Foo(), f2 = New Foo()) ~~~~~~~~~~~~~~ BC30452: Operator '=' is not defined for types 'Foo' and 'Foo'. f3 = If(b, f1 = New Foo(), f2 = New Foo()) ~~~~~~~~~~~~~~ BC30452: Operator '=' is not defined for types 'Foo' and 'Foo'. f3 = If(b, f1 = New Foo(), f2 = New Foo()) ~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30452ERR_BinaryOperands3_4() CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="None"> <file name="a.vb"><![CDATA[ Module Program Sub Main() Dim First = New With {.a = 1, .b = 2} Dim Second = New With {.a = 1, .b = 2} 'COMPILEERROR: BC30452, "first = second" If first = second Then ElseIf second <> first Then End If End Sub End Module ]]></file> </compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_BinaryOperands3, "first = second").WithArguments("=", "<anonymous type: a As Integer, b As Integer>", "<anonymous type: a As Integer, b As Integer>"), Diagnostic(ERRID.ERR_BinaryOperands3, "second <> first").WithArguments("<>", "<anonymous type: a As Integer, b As Integer>", "<anonymous type: a As Integer, b As Integer>")) End Sub <Fact()> Public Sub BC30452ERR_BinaryOperands3_4a() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="BC30452ERR_BinaryOperands3_4a"> <file name="a.vb"><![CDATA[ Imports System Module Program Sub Main() 'COMPILEERROR: BC30452, "first = second" If New With {.a = 1, .b = 2} = New With {.a = 1, .b = 2} Then ElseIf New With {.a = 1, .b = 2} <> New With {.a = 1, .b = 2} Then End If End Sub End Module ]]></file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected><![CDATA[ BC30452: Operator '=' is not defined for types '<anonymous type: a As Integer, b As Integer>' and '<anonymous type: a As Integer, b As Integer>'. If New With {.a = 1, .b = 2} = New With {.a = 1, .b = 2} Then ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30452: Operator '<>' is not defined for types '<anonymous type: a As Integer, b As Integer>' and '<anonymous type: a As Integer, b As Integer>'. ElseIf New With {.a = 1, .b = 2} <> New With {.a = 1, .b = 2} Then ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></expected>) End Sub <Fact()> Public Sub BC30454ERR_ExpectedProcedure() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ExpectedProcedure"> <file name="a.vb"> Module IsNotError001mod Sub foo(byval value as integer()) value() exit sub End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30454: Expression is not a method. value() ~~~~~ </expected>) End Sub <Fact()> Public Sub BC30454ERR_ExpectedProcedure_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="ExpectedProcedure"> <file name="a.vb"> Class C Private s As String Shared Sub M(x As C, y() As Integer) Dim o As Object o = x.s(3) N(x.s(3)) x.s(3) ' BC30454 o = y(3) N(y(3)) y(3) ' BC30454 End Sub Shared Sub N(o) End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30454: Expression is not a method. x.s(3) ' BC30454 ~~~ BC30454: Expression is not a method. y(3) ' BC30454 ~ </expected>) End Sub <Fact()> Public Sub BC30455ERR_OmittedArgument2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C Default ReadOnly Property P(x, y) Get Return Nothing End Get End Property Shared Sub M(x As C) N(x!Q) End Sub Shared Sub N(o As Object) End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30455: Argument not specified for parameter 'y' of 'Public ReadOnly Default Property P(x As Object, y As Object) As Object'. N(x!Q) ~~~ </expected>) End Sub <Fact()> Public Sub BC30455ERR_OmittedArgument2_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Structure C1 &lt;System.Runtime.InteropServices.FieldOffset()&gt; Dim i As Integer End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30455: Argument not specified for parameter 'offset' of 'Public Overloads Sub New(offset As Integer)'. &lt;System.Runtime.InteropServices.FieldOffset()&gt; ~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30456ERR_NameNotMember2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class Class1 Private Shared foo As S1 Class Class2 Sub Test() foo.bar1() End Sub End Class End Class Structure S1 Public shared bar As String = "Hello" End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30456: 'bar1' is not a member of 'S1'. foo.bar1() ~~~~~~~~ </expected>) End Sub <WorkItem(538903, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538903")> <Fact()> Public Sub BC30456ERR_NameNotMember2_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module M1 Sub FOO() My.Application.Exit() End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30451: 'My' is not declared. It may be inaccessible due to its protection level. My.Application.Exit() ~~ </expected>) End Sub <Fact()> Public Sub BC30456ERR_NameNotMember2_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module M1 Sub FOO() Dim blnReturn As Boolean = False Dim x As System.Nullable(Of Integer) blnReturn = system.nullable.hasvalue(x) End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30456: 'hasvalue' is not a member of 'Nullable'. blnReturn = system.nullable.hasvalue(x) ~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30456ERR_NameNotMember2_3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C Shared ReadOnly Property P Get Return Nothing End Get End Property ReadOnly Property Q Get Return Nothing End Get End Property Sub M() C.set_P(C.get_P) Me.set_Q(Me.get_Q) End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30456: 'set_P' is not a member of 'C'. C.set_P(C.get_P) ~~~~~~~ BC30456: 'get_P' is not a member of 'C'. C.set_P(C.get_P) ~~~~~~~ BC30456: 'set_Q' is not a member of 'C'. Me.set_Q(Me.get_Q) ~~~~~~~~ BC30456: 'get_Q' is not a member of 'C'. Me.set_Q(Me.get_Q) ~~~~~~~~ </expected>) End Sub <WorkItem(10046, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub BC30456ERR_NameNotMember2_4() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Option Infer On Imports System Class Program Dim x As New Product With {.Name = "paperclips", .price1 = 1.29} End Class Class Product Property price As Double Property Name As String End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30456: 'price1' is not a member of 'Product'. Dim x As New Product With {.Name = "paperclips", .price1 = 1.29} ~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30456ERR_NameNotMember2_5() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="BC30456ERR_NameNotMember2_4"> <file name="a.vb"> Module M1 Class B End Class Class D Inherits B Public Shadows Sub M() End Sub Public Sub Test() MyBase.M() Me.M() End Sub End Class End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30456: 'M' is not a member of 'M1.B'. MyBase.M() ~~~~~~~~ </expected>) End Sub <WorkItem(529710, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529710")> <Fact()> Public Sub BC30456ERR_NameNotMember3_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Namespace N Module X Sub Main() N.Equals("", "") End Sub End Module End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30456: 'Equals' is not a member of 'N'. N.Equals("", "") ~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30469ERR_ObjectReferenceNotSupplied_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C1 function foo() as integer return 1 End function Class C2 function foo1() as integer dim s = foo() return 1 End function End Class End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30469: Reference to a non-shared member requires an object reference. dim s = foo() ~~~ </expected>) End Sub <Fact()> Public Sub BC30469ERR_ObjectReferenceNotSupplied_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="ObjectReferenceNotSupplied"> <file name="a.vb"> Class P(Of T) Public ReadOnly son As T Class P1 Sub New1(ByVal tval As T) son = tval End Sub End Class End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30469: Reference to a non-shared member requires an object reference. son = tval ~~~ </expected>) End Sub <Fact()> Public Sub BC30469ERR_ObjectReferenceNotSupplied_3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C Property P Get Return Nothing End Get Set(ByVal value) End Set End Property Shared Sub M() Dim o = C.P C.P = o End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30469: Reference to a non-shared member requires an object reference. Dim o = C.P ~~~ BC30469: Reference to a non-shared member requires an object reference. C.P = o ~~~ </expected>) End Sub <Fact()> Public Sub BC30469ERR_ObjectReferenceNotSupplied_4() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class A Property P Get Return Nothing End Get Set(ByVal value) End Set End Property Class B Sub M(ByVal value) P = value value = P End Sub End Class End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30469: Reference to a non-shared member requires an object reference. P = value ~ BC30469: Reference to a non-shared member requires an object reference. value = P ~ </expected>) End Sub <Fact()> Public Sub BC30469ERR_ObjectReferenceNotSupplied_FieldInitializers() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C1 public f1 as integer public shared f2 as integer = C1.f1 End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30469: Reference to a non-shared member requires an object reference. public shared f2 as integer = C1.f1 ~~~~~ </expected>) End Sub <Fact()> Public Sub BC30469ERR_ObjectReferenceNotSupplied_DelegateCreation() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="NoDirectDelegateConstruction1"> <file name="a.vb"> Class C1 Public Delegate Sub myDelegate() public sub mySub() end sub End Class Module M1 Sub foo() Dim d1 As C1.myDelegate d1 = New C1.myDelegate(addressof C1.mySub) End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30469: Reference to a non-shared member requires an object reference. d1 = New C1.myDelegate(addressof C1.mySub) ~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30470ERR_MyClassNotInClass() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="MyClassNotInClass"> <file name="a.vb"> Module M1 Sub FOO() MyClass.New() End Sub Sub New() End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30470: 'MyClass' cannot be used outside of a class. MyClass.New() ~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30487ERR_UnaryOperand2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="UnaryOperand2"> <file name="a.vb"> Class C1 Shared Sub FOO() Dim expr As c2 = new c2() expr = -expr End Sub End Class Class C2 End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30487: Operator '-' is not defined for type 'C2'. expr = -expr ~~~~~ </expected>) End Sub <Fact()> Public Sub BC30491ERR_VoidValue() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="VoidValue"> <file name="a.vb"> Structure C1 Sub FOO() 'Dim a1 = If (True, New Object, TestMethod) 'Dim a2 = If (True, {TestMethod()}, {TestMethod()}) Dim a3 = TestMethod() = TestMethod() End Sub Sub TestMethod() End Sub End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30491: Expression does not produce a value. Dim a3 = TestMethod() = TestMethod() ~~~~~~~~~~~~ BC30491: Expression does not produce a value. Dim a3 = TestMethod() = TestMethod() ~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30491ERR_VoidValue_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="VoidValue"> <file name="a.vb"> Imports System Module Program Sub Main(args As String()) Dim x = If(True, Console.WriteLine(0), Console.WriteLine(1)) Dim y = If(True, fun_void(), fun_int(1)) Dim z = If(True, fun_Exception(1), fun_int(1)) Dim r = If(True, fun_long(0), fun_int(1)) Dim s = If(False, fun_long(0), fun_int(1)) End Sub Private Sub fun_void() Return End Sub Private Function fun_int(x As Integer) As Integer Return x End Function Private Function fun_long(x As Integer) As Long Return CLng(x) End Function Private Function fun_Exception(x As Integer) As Exception Return New Exception() End Function End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30491: Expression does not produce a value. Dim x = If(True, Console.WriteLine(0), Console.WriteLine(1)) ~~~~~~~~~~~~~~~~~~~~ BC30491: Expression does not produce a value. Dim x = If(True, Console.WriteLine(0), Console.WriteLine(1)) ~~~~~~~~~~~~~~~~~~~~ BC30491: Expression does not produce a value. Dim y = If(True, fun_void(), fun_int(1)) ~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30491ERR_VoidValue_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="VoidValue"> <file name="a.vb"> Imports System Module Program Sub Main(args As String()) Dim x As Integer = 1 Dim y As Object = 0 Dim s = If(True, fun(x), y) Dim s1 = If(False, sub1(x), y) End Sub Private Function fun(Of T)(Parm1 As T) As T Return Parm1 End Function Private Sub sub1(Of T)(Parm1 As T) End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30491: Expression does not produce a value. Dim s1 = If(False, sub1(x), y) ~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30491ERR_VoidValue_SelectCase() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="VoidValue"> <file name="a.vb"> Structure C1 Sub Foo() Select Case TestMethod() End Select End Sub Sub TestMethod() End Sub End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30491: Expression does not produce a value. Select Case TestMethod() ~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30500ERR_CircularEvaluation1() Dim source = <compilation> <file name="a.vb"> Option strict on imports system Class C1 Enum E A = A End Enum public const f1 as integer = f2 public const f2 as integer = f1 Public shared Sub Main(args() as string) Console.WriteLine(E.A) End sub End Class </file> </compilation> Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) CompilationUtils.AssertTheseDiagnostics(c1, <expected> BC30500: Constant 'A' cannot depend on its own value. A = A ~ BC30500: Constant 'f1' cannot depend on its own value. public const f1 as integer = f2 ~~ </expected>) End Sub <Fact()> Public Sub BC30500ERR_CircularEvaluation1_02() Dim source = <compilation> <file name="a.vb"> Option Strict On Option Infer On imports system Class C1 private const f1 = f2 private const f2 = f1 Public shared Sub Main(args() as string) console.writeline(f1) console.writeline(f2) End sub End Class </file> </compilation> Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) CompilationUtils.AssertTheseDiagnostics(c1, <expected> BC30500: Constant 'f1' cannot depend on its own value. private const f1 = f2 ~~ </expected>) End Sub <Fact(), WorkItem(528728, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528728")> Public Sub BC30500ERR_CircularEvaluation1_03() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="CircularEvaluation1"> <file name="a.vb"> Module M1 Sub New() Const Val As Integer = Val End Sub End Module </file> </compilation>) compilation.AssertTheseDiagnostics( <expected> BC30500: Constant 'Val' cannot depend on its own value. Const Val As Integer = Val ~~~ </expected>) End Sub <Fact()> Public Sub BC30500ERR_CircularEvaluation1_04() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C Const c0, c1 = c2 + 1 Const c2, c3 = c0 + 1 End Class </file> </compilation>) compilation.AssertTheseDiagnostics( <expected> BC30500: Constant 'c0' cannot depend on its own value. Const c0, c1 = c2 + 1 ~~ BC30671: Explicit initialization is not permitted with multiple variables declared with a single type specifier. Const c0, c1 = c2 + 1 ~~~~~~~~~~~~~~~ BC30671: Explicit initialization is not permitted with multiple variables declared with a single type specifier. Const c2, c3 = c0 + 1 ~~~~~~~~~~~~~~~ BC30060: Conversion from 'Integer' to 'Object' cannot occur in a constant expression. Const c2, c3 = c0 + 1 ~ </expected>) End Sub <Fact()> Public Sub BC30512ERR_NarrowingConversionDisallowed2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="NarrowingConversionDisallowed2"> <file name="a.vb"> Option Strict On Imports System Module M1 Sub Foo() Dim b As Byte = 2 Dim c As Byte = 3 Dim s As Short = 2 Dim t As Short = 3 Dim i As Integer = 2 Dim j As Integer = 3 Dim l As Long = 2 Dim m As Long = 3 b = b &lt; c b = b ^ c s = s &lt; t s = s ^ t i = i &gt; j i = i ^ j l = l &gt; m l = l ^ m End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30512: Option Strict On disallows implicit conversions from 'Boolean' to 'Byte'. b = b &lt; c ~~~~~ BC30512: Option Strict On disallows implicit conversions from 'Double' to 'Byte'. b = b ^ c ~~~~~ BC30512: Option Strict On disallows implicit conversions from 'Boolean' to 'Short'. s = s &lt; t ~~~~~ BC30512: Option Strict On disallows implicit conversions from 'Double' to 'Short'. s = s ^ t ~~~~~ BC30512: Option Strict On disallows implicit conversions from 'Boolean' to 'Integer'. i = i &gt; j ~~~~~ BC30512: Option Strict On disallows implicit conversions from 'Double' to 'Integer'. i = i ^ j ~~~~~ BC30512: Option Strict On disallows implicit conversions from 'Boolean' to 'Long'. l = l &gt; m ~~~~~ BC30512: Option Strict On disallows implicit conversions from 'Double' to 'Long'. l = l ^ m ~~~~~ </expected>) End Sub <Fact()> Public Sub BC30512ERR_NarrowingConversionDisallowed2_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Option Strict On Class C Default ReadOnly Property P(i As Integer) As Object Get Return Nothing End Get End Property Shared Sub M(x As C) N(x("Q")) N(x!Q) End Sub Shared Sub N(o As Object) End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30512: Option Strict On disallows implicit conversions from 'String' to 'Integer'. N(x("Q")) ~~~ BC30512: Option Strict On disallows implicit conversions from 'String' to 'Integer'. N(x!Q) ~ </expected>) End Sub <Fact()> Public Sub BC30512ERR_NarrowingConversionDisallowed2_2() CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict On Module Program Sub Main(args As String()) Dim S1 As String = "3" Dim S1_b As Object = If(S1, 3, 2) Dim S2 As SByte = 4 Dim S2_b As Object = If(S2, 4, 2) Dim S3 As Byte = 5 Dim S3_b As Object = If(S3, 5, 2) Dim S4 As Short = 6 Dim S4_b As Object = If(S4, 6, 2) Dim S5 As UShort = 7 Dim S5_b As Object = If(S5, 7, 2) Dim S6 As Integer = 8 Dim S6_b As Object = If(S6, 8, 2) Dim S7 As UInteger = 9 Dim S7_b As Object = If(S7, 9, 2) Dim S8 As Long = 10 Dim S8_b As Object = If(S8, 10, 2) Dim S9 As Short? = 5 Dim S9_b As Object = If(S9, 3, 2) Dim S10 As Integer? = 51 Dim S10_b As Object = If(S10, 3, 2) Dim S11 As Boolean? = Nothing Dim S11_b As Object = If(S11, 3, 2) End Sub End Module </file> </compilation>).VerifyDiagnostics( Diagnostic(ERRID.ERR_NarrowingConversionDisallowed2, "S1").WithArguments("String", "Boolean"), Diagnostic(ERRID.ERR_NarrowingConversionDisallowed2, "S2").WithArguments("SByte", "Boolean"), Diagnostic(ERRID.ERR_NarrowingConversionDisallowed2, "S3").WithArguments("Byte", "Boolean"), Diagnostic(ERRID.ERR_NarrowingConversionDisallowed2, "S4").WithArguments("Short", "Boolean"), Diagnostic(ERRID.ERR_NarrowingConversionDisallowed2, "S5").WithArguments("UShort", "Boolean"), Diagnostic(ERRID.ERR_NarrowingConversionDisallowed2, "S6").WithArguments("Integer", "Boolean"), Diagnostic(ERRID.ERR_NarrowingConversionDisallowed2, "S7").WithArguments("UInteger", "Boolean"), Diagnostic(ERRID.ERR_NarrowingConversionDisallowed2, "S8").WithArguments("Long", "Boolean"), Diagnostic(ERRID.ERR_NarrowingConversionDisallowed2, "S9").WithArguments("Short?", "Boolean?"), Diagnostic(ERRID.ERR_NarrowingConversionDisallowed2, "S10").WithArguments("Integer?", "Boolean?")) End Sub <Fact()> Public Sub BC30512ERR_NarrowingConversionDisallowed2_3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict On Imports System Module Program Sub Main(args As String()) Dim S1_a As Short? = 5 Dim S1_b As Integer? = 51 Dim S1_c As Short? = If(True, S1_a, S1_b) Dim S1_d As Boolean? = If(True, S1_a, S1_b) Dim S2_a As Char Dim S2_b As String = "31" Dim S2_c As String = If(True, S2_a, S2_b) Dim S2_d As Char = If(False, S2_a, S2_b) Dim S2_e As Short = If(False, S2_a, S2_b) End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30512: Option Strict On disallows implicit conversions from 'Integer?' to 'Short?'. Dim S1_c As Short? = If(True, S1_a, S1_b) ~~~~~~~~~~~~~~~~~~~~ BC30512: Option Strict On disallows implicit conversions from 'Integer?' to 'Boolean?'. Dim S1_d As Boolean? = If(True, S1_a, S1_b) ~~~~~~~~~~~~~~~~~~~~ BC30512: Option Strict On disallows implicit conversions from 'String' to 'Char'. Dim S2_d As Char = If(False, S2_a, S2_b) ~~~~~~~~~~~~~~~~~~~~~ BC30512: Option Strict On disallows implicit conversions from 'String' to 'Short'. Dim S2_e As Short = If(False, S2_a, S2_b) ~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30512ERR_NarrowingConversionDisallowed2_4() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Option Strict On Public Class MyClass1 Public Shared Sub Main() For ivar As Integer = 0.1 To 10 Next For dvar As Double = #12:00:00 AM# To 10 Next For dvar As Double = True To 10 Next For dvar1 As Double = 123&amp; To 10 'ok Next End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30512: Option Strict On disallows implicit conversions from 'Double' to 'Integer'. For ivar As Integer = 0.1 To 10 ~~~ BC30532: Conversion from 'Date' to 'Double' requires calling the 'Date.ToOADate' method. For dvar As Double = #12:00:00 AM# To 10 ~~~~~~~~~~~~~ BC30512: Option Strict On disallows implicit conversions from 'Boolean' to 'Double'. For dvar As Double = True To 10 ~~~~ </expected>) End Sub <Fact()> Public Sub BC30512ERR_NarrowingConversionDisallowed2_5() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict On Imports System Module Module1 Sub Main() Dim arr As Integer(,) = New Integer(1.0, 4) {} ' Invalid Dim arr1 As Integer(,) = New Integer(CDbl(5), 4) {} ' Invalid Dim arr2 As Integer(,) = New Integer(CDec(5), 4) {} ' Invalid Dim arr3 As Integer(,) = New Integer(CSng(5), 4) {} ' Invalid Dim x As Double = 5 Dim arr4 As Integer(,) = New Integer(x, 4) {} ' Invalid Dim y As Single = 5 Dim arr5 As Integer(,) = New Integer(y, 4) {} ' Invalid Dim z As Decimal = 5 Dim arr6 As Integer(,) = New Integer(z, 4) {} ' Invalid Dim m As Boolean = True Dim arr7 As Integer(,) = New Integer(m, 4) {} ' Invalid End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30512: Option Strict On disallows implicit conversions from 'Double' to 'Integer'. Dim arr As Integer(,) = New Integer(1.0, 4) {} ' Invalid ~~~ BC30512: Option Strict On disallows implicit conversions from 'Double' to 'Integer'. Dim arr1 As Integer(,) = New Integer(CDbl(5), 4) {} ' Invalid ~~~~~~~ BC30512: Option Strict On disallows implicit conversions from 'Decimal' to 'Integer'. Dim arr2 As Integer(,) = New Integer(CDec(5), 4) {} ' Invalid ~~~~~~~ BC30512: Option Strict On disallows implicit conversions from 'Single' to 'Integer'. Dim arr3 As Integer(,) = New Integer(CSng(5), 4) {} ' Invalid ~~~~~~~ BC30512: Option Strict On disallows implicit conversions from 'Double' to 'Integer'. Dim arr4 As Integer(,) = New Integer(x, 4) {} ' Invalid ~ BC30512: Option Strict On disallows implicit conversions from 'Single' to 'Integer'. Dim arr5 As Integer(,) = New Integer(y, 4) {} ' Invalid ~ BC30512: Option Strict On disallows implicit conversions from 'Decimal' to 'Integer'. Dim arr6 As Integer(,) = New Integer(z, 4) {} ' Invalid ~ BC30512: Option Strict On disallows implicit conversions from 'Boolean' to 'Integer'. Dim arr7 As Integer(,) = New Integer(m, 4) {} ' Invalid ~ </expected>) End Sub <Fact()> Public Sub BC30512ERR_NarrowingConversionDisallowed2_6() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict On Imports System Module Module1 Sub Main() Dim myArray9 As Char(,) = New Char(2, 1) {{"a", "b"}, {"c", "d"}, {"e", "f"}} End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30512: Option Strict On disallows implicit conversions from 'String' to 'Char'. Dim myArray9 As Char(,) = New Char(2, 1) {{"a", "b"}, {"c", "d"}, {"e", "f"}} ~~~ BC30512: Option Strict On disallows implicit conversions from 'String' to 'Char'. Dim myArray9 As Char(,) = New Char(2, 1) {{"a", "b"}, {"c", "d"}, {"e", "f"}} ~~~ BC30512: Option Strict On disallows implicit conversions from 'String' to 'Char'. Dim myArray9 As Char(,) = New Char(2, 1) {{"a", "b"}, {"c", "d"}, {"e", "f"}} ~~~ BC30512: Option Strict On disallows implicit conversions from 'String' to 'Char'. Dim myArray9 As Char(,) = New Char(2, 1) {{"a", "b"}, {"c", "d"}, {"e", "f"}} ~~~ BC30512: Option Strict On disallows implicit conversions from 'String' to 'Char'. Dim myArray9 As Char(,) = New Char(2, 1) {{"a", "b"}, {"c", "d"}, {"e", "f"}} ~~~ BC30512: Option Strict On disallows implicit conversions from 'String' to 'Char'. Dim myArray9 As Char(,) = New Char(2, 1) {{"a", "b"}, {"c", "d"}, {"e", "f"}} ~~~ </expected>) End Sub <Fact()> Public Sub BC30512ERR_NarrowingConversionDisallowed2_7() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Infer On Option Strict On Imports System Imports Microsoft.VisualBasic.Strings Module Module1 Sub Main(args As String()) Dim arr As Integer(,) = New Integer(4, 4) {} Dim x As Integer = 0 Dim idx As Double = 2.0 Dim idx1 As ULong = 0 Dim idx2 As Char = ChrW(3) arr(idx, 3) = 100 ' Invalid arr(idx1, x) = 100 ' Invalid arr(idx2, 3) = 100 'Invalid arr(" "c, 32) = 100 'Invalid Dim arr1 As Integer(,,) = {{{1, 2}, {1, 2}}, {{1, 2}, {1, 2}}} Dim i1 As ULong = 0 Dim i2 As UInteger = 0 Dim i3 As Integer = 0 arr1(i1, i2, i3) = 9 ' Invalid End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30512: Option Strict On disallows implicit conversions from 'Double' to 'Integer'. arr(idx, 3) = 100 ' Invalid ~~~ BC30512: Option Strict On disallows implicit conversions from 'ULong' to 'Integer'. arr(idx1, x) = 100 ' Invalid ~~~~ BC32006: 'Char' values cannot be converted to 'Integer'. Use 'Microsoft.VisualBasic.AscW' to interpret a character as a Unicode value or 'Microsoft.VisualBasic.Val' to interpret it as a digit. arr(idx2, 3) = 100 'Invalid ~~~~ BC32006: 'Char' values cannot be converted to 'Integer'. Use 'Microsoft.VisualBasic.AscW' to interpret a character as a Unicode value or 'Microsoft.VisualBasic.Val' to interpret it as a digit. arr(" "c, 32) = 100 'Invalid ~~~~ BC30512: Option Strict On disallows implicit conversions from 'ULong' to 'Integer'. arr1(i1, i2, i3) = 9 ' Invalid ~~ BC30512: Option Strict On disallows implicit conversions from 'UInteger' to 'Integer'. arr1(i1, i2, i3) = 9 ' Invalid ~~ </expected>) End Sub <WorkItem(528762, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528762")> <Fact> Public Sub BC30512ERR_NarrowingConversionDisallowed2_8() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict On Option Infer On Public Class Class2(Of T As Res) Private x As T(,) = New T(1, 1) {{New Res(), New Res()}, {New Res(), New Res()}} ' invalid Public Sub Foo() Dim x As T(,) = New T(1, 2) {} End Sub End Class Public Class Res End Class </file> </compilation>).VerifyDiagnostics( Diagnostic(ERRID.ERR_NarrowingConversionDisallowed2, "New Res()").WithArguments("Res", "T"), Diagnostic(ERRID.ERR_NarrowingConversionDisallowed2, "New Res()").WithArguments("Res", "T"), Diagnostic(ERRID.ERR_NarrowingConversionDisallowed2, "New Res()").WithArguments("Res", "T"), Diagnostic(ERRID.ERR_NarrowingConversionDisallowed2, "New Res()").WithArguments("Res", "T")) End Sub <Fact()> Public Sub BC30512ERR_SelectCaseNarrowingConversionErrors() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports System Module M1 Sub Main() Dim success As Boolean = True For count = 0 To 13 Test(count, success) Next If success Then Console.Write("Success") Else Console.Write("Fail") End If End Sub Sub Test(count As Integer, ByRef success As Boolean) Dim Bo As Boolean Dim Ob As Object Dim SB As SByte Dim By As Byte Dim Sh As Short Dim US As UShort Dim [In] As Integer Dim UI As UInteger Dim Lo As Long Dim UL As ULong Dim De As Decimal Dim Si As Single Dim [Do] As Double Dim St As String Bo = False Ob = 1 SB = 2 By = 3 Sh = 4 US = 5 [In] = 6 UI = 7 Lo = 8 UL = 9 Si = 10 [Do] = 11 De = 12D St = "13" Select Case count Case Bo success = success AndAlso If(count = 0, True, False) Case Is < Ob success = success AndAlso If(count = 1, True, False) Case SB success = success AndAlso If(count = 2, True, False) Case By success = success AndAlso If(count = 3, True, False) Case Sh success = success AndAlso If(count = 4, True, False) Case US success = success AndAlso If(count = 5, True, False) Case [In] success = success AndAlso If(count = 6, True, False) Case UI To Lo success = success AndAlso If(count = 7, True, False) Case Lo success = success AndAlso If(count = 8, True, False) Case UL success = success AndAlso If(count = 9, True, False) Case Si success = success AndAlso If(count = 10, True, False) Case [Do] success = success AndAlso If(count = 11, True, False) Case De success = success AndAlso If(count = 12, True, False) Case St success = success AndAlso If(count = 13, True, False) Case Else success = False End Select End Sub End Module ]]></file> </compilation>) Dim expectedErrors = <errors><![CDATA[ BC30512: Option Strict On disallows implicit conversions from 'Boolean' to 'Integer'. Case Bo ~~ BC30038: Option Strict On prohibits operands of type Object for operator '<'. Case Is < Ob ~~ BC30512: Option Strict On disallows implicit conversions from 'UInteger' to 'Integer'. Case UI To Lo ~~ BC30512: Option Strict On disallows implicit conversions from 'Long' to 'Integer'. Case UI To Lo ~~ BC30512: Option Strict On disallows implicit conversions from 'Long' to 'Integer'. Case Lo ~~ BC30512: Option Strict On disallows implicit conversions from 'ULong' to 'Integer'. Case UL ~~ BC30512: Option Strict On disallows implicit conversions from 'Single' to 'Integer'. Case Si ~~ BC30512: Option Strict On disallows implicit conversions from 'Double' to 'Integer'. Case [Do] ~~~~ BC30512: Option Strict On disallows implicit conversions from 'Decimal' to 'Integer'. Case De ~~ BC30512: Option Strict On disallows implicit conversions from 'String' to 'Integer'. Case St ~~ ]]></errors> CompilationUtils.AssertTheseDiagnostics(compilation, expectedErrors) End Sub <Fact()> Public Sub BC30516ERR_NoArgumentCountOverloadCandidates1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="NoArgumentCountOverloadCandidates1"> <file name="a.vb"> Module Module1 Class C0 Public whichOne As String Sub Foo(ByVal t1 As String) whichOne = "T" End Sub End Class Class C1 Inherits C0 Overloads Sub Foo(ByVal y1 As String) whichOne = "Y" End Sub End Class Sub test() Dim [ident1] As C0 = New C0() Dim clsNarg2get As C1 = New C1() Dim str1 As String = "Visual Basic" 'COMPILEERROR: BC30516, "y" clsNarg2get.Foo(1, y1:=2) 'COMPILEERROR: BC30516, "x" clsNarg2get.Foo(y1:=1, y1:=1) End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30516: Overload resolution failed because no accessible 'Foo' accepts this number of arguments. clsNarg2get.Foo(1, y1:=2) ~~~ BC30516: Overload resolution failed because no accessible 'Foo' accepts this number of arguments. clsNarg2get.Foo(y1:=1, y1:=1) ~~~ </expected>) End Sub <Fact()> Public Sub BC30517ERR_NoViableOverloadCandidates1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="NoViableOverloadCandidates1"> <file name="a.vb"> Imports System &lt;AttributeUsage(AttributeTargets.All)&gt; Class attr2 Inherits Attribute Private Sub New(ByVal i As Integer) End Sub Protected Sub New(ByVal i As Char) End Sub End Class &lt;attr2(1)&gt; Class target2 End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30517: Overload resolution failed because no 'New' is accessible. &lt;attr2(1)&gt; Class target2 ~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30518ERR_NoCallableOverloadCandidates2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="NoCallableOverloadCandidates2"> <file name="a.vb"> class M1 Sub sub1(Of U, V) (ByVal p1 As U, ByVal p2 As V) End Sub Sub sub1(Of U, V) (ByVal p1() As V, ByVal p2() As U) End Sub Sub GenMethod6210() sub1(Of String, Integer) (17@, #3/3/2003#) sub1(Of Integer, String) (New Integer() {1, 2, 3}, New String() {"a", "b"}) End Sub End class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30518: Overload resolution failed because no accessible 'sub1' can be called with these arguments: 'Public Sub sub1(Of String, Integer)(p1 As String, p2 As Integer)': Value of type 'Date' cannot be converted to 'Integer'. 'Public Sub sub1(Of String, Integer)(p1 As Integer(), p2 As String())': Value of type 'Decimal' cannot be converted to 'Integer()'. 'Public Sub sub1(Of String, Integer)(p1 As Integer(), p2 As String())': Value of type 'Date' cannot be converted to 'String()'. sub1(Of String, Integer) (17@, #3/3/2003#) ~~~~~~~~~~~~~~~~~~~~~~~~ BC30518: Overload resolution failed because no accessible 'sub1' can be called with these arguments: 'Public Sub sub1(Of Integer, String)(p1 As Integer, p2 As String)': Value of type 'Integer()' cannot be converted to 'Integer'. 'Public Sub sub1(Of Integer, String)(p1 As Integer, p2 As String)': Value of type 'String()' cannot be converted to 'String'. 'Public Sub sub1(Of Integer, String)(p1 As String(), p2 As Integer())': Value of type 'Integer()' cannot be converted to 'String()' because 'Integer' is not derived from 'String'. 'Public Sub sub1(Of Integer, String)(p1 As String(), p2 As Integer())': Value of type 'String()' cannot be converted to 'Integer()' because 'String' is not derived from 'Integer'. sub1(Of Integer, String) (New Integer() {1, 2, 3}, New String() {"a", "b"}) ~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <WorkItem(546763, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546763")> <Fact()> Public Sub BC30518ERR_NoCallableOverloadCandidates_LateBindingDisabled() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="a.vb"> Option Strict On Option Infer On Imports System Imports System.Threading.Tasks Public Module Program Sub Main() Dim a As Object = Nothing Parallel.ForEach(a, Sub(x As Object) Console.WriteLine(x)) End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30518: Overload resolution failed because no accessible 'ForEach' can be called with these arguments: 'Public Shared Overloads Function ForEach(Of TSource)(source As IEnumerable(Of TSource), body As Action(Of TSource)) As ParallelLoopResult': Data type(s) of the type parameter(s) cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error. 'Public Shared Overloads Function ForEach(Of TSource)(source As IEnumerable(Of TSource), body As Action(Of TSource, ParallelLoopState)) As ParallelLoopResult': Data type(s) of the type parameter(s) cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error. 'Public Shared Overloads Function ForEach(Of TSource)(source As IEnumerable(Of TSource), body As Action(Of TSource, ParallelLoopState, Long)) As ParallelLoopResult': Data type(s) of the type parameter(s) cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error. 'Public Shared Overloads Function ForEach(Of TSource)(source As Partitioner(Of TSource), body As Action(Of TSource)) As ParallelLoopResult': Data type(s) of the type parameter(s) cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error. 'Public Shared Overloads Function ForEach(Of TSource)(source As Partitioner(Of TSource), body As Action(Of TSource, ParallelLoopState)) As ParallelLoopResult': Data type(s) of the type parameter(s) cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error. 'Public Shared Overloads Function ForEach(Of TSource)(source As OrderablePartitioner(Of TSource), body As Action(Of TSource, ParallelLoopState, Long)) As ParallelLoopResult': Data type(s) of the type parameter(s) cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error. Parallel.ForEach(a, Sub(x As Object) Console.WriteLine(x)) ~~~~~~~ </expected>) End Sub <Fact(), WorkItem(542956, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542956")> Public Sub BC30518ERR_NoCallableOverloadCandidates2_trycatch() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndReferences( <compilation name="ExitTryNotWithinTry"> <file name="a.vb"> Imports System Imports System.Linq Class BaseClass Function Method() As String Dim x = New Integer() {} x.Where(Function(y) Try Exit Try Catch ex1 As Exception When True Exit Try Finally Exit Function End Try Return y = "" End Function) Return "x" End Function End Class Class DerivedClass Inherits BaseClass Shared Sub Main() End Sub End Class </file> </compilation>, {Net40.SystemCore}) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30101: Branching out of a 'Finally' is not valid. Exit Function ~~~~~~~~~~~~~ BC42353: Function '&lt;anonymous method>' doesn't return a value on all code paths. Are you missing a 'Return' statement? End Function) ~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30519ERR_NoNonNarrowingOverloadCandidates2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="NoNonNarrowingOverloadCandidates2"> <file name="a.vb"> Module Module1 Class C0(Of T) Public whichOne As String Sub Foo(ByVal t1 As T) whichOne = "T" End Sub Default Property Prop1(ByVal t1 As T) As Integer Get Return 100 End Get Set(ByVal Value As Integer) whichOne = "T" End Set End Property End Class Class C1(Of T, Y) Inherits C0(Of T) Overloads Sub Foo(ByVal y1 As Y) whichOne = "Y" End Sub Default Overloads Property Prop1(ByVal y1 As Y) As Integer Get Return 200 End Get Set(ByVal Value As Integer) whichOne = "Y" End Set End Property End Class Structure S1 Dim i As Integer End Structure Class Scenario11 Public Shared Narrowing Operator CType(ByVal Arg As Scenario11) As C1(Of Integer, Integer) Return New C1(Of Integer, Integer) End Operator Public Shared Narrowing Operator CType(ByVal Arg As Scenario11) As S1 Return New S1 End Operator End Class Sub GenUnif0060() Dim iTmp As Integer = 2000 Dim dTmp As Decimal = CDec(2000000) Dim tc2 As New C1(Of S1, C1(Of Integer, Integer)) Dim tc3 As New C1(Of Short, Long) Dim sc11 As New Scenario11 ' COMPILEERROR: BC30519,"Call tc2.Foo (New Scenario11)" Call tc2.Foo(New Scenario11) ' COMPILEERROR: BC30519,"Call tc2.Foo (sc11)" Call tc2.Foo(sc11) ' COMPILEERROR: BC30519,"Call tc3.Foo (dTmp)" Call tc3.Foo(dTmp) ' COMPILEERROR: BC30519,"tc2 (New Scenario11) = 1000" tc2(New Scenario11) = 1000 ' COMPILEERROR: BC30519,"tc2 (New Scenario11)" iTmp = tc2(New Scenario11) ' COMPILEERROR: BC30519,"tc3 (dTmp) = 2000" tc3(dTmp) = 2000 ' COMPILEERROR: BC30519,"tc3 (dTmp)" iTmp = tc3(dTmp) End Sub End Module </file> </compilation>) compilation.VerifyDiagnostics( Diagnostic(ERRID.ERR_NoNonNarrowingOverloadCandidates2, "Foo").WithArguments("Foo", <![CDATA[ 'Public Overloads Sub Foo(y1 As Module1.C1(Of Integer, Integer))': Argument matching parameter 'y1' narrows from 'Module1.Scenario11' to 'Module1.C1(Of Integer, Integer)'. 'Public Sub Foo(t1 As Module1.S1)': Argument matching parameter 't1' narrows from 'Module1.Scenario11' to 'Module1.S1'.]]>.Value.Replace(vbLf, Environment.NewLine)), Diagnostic(ERRID.ERR_NoNonNarrowingOverloadCandidates2, "Foo").WithArguments("Foo", <![CDATA[ 'Public Overloads Sub Foo(y1 As Module1.C1(Of Integer, Integer))': Argument matching parameter 'y1' narrows from 'Module1.Scenario11' to 'Module1.C1(Of Integer, Integer)'. 'Public Sub Foo(t1 As Module1.S1)': Argument matching parameter 't1' narrows from 'Module1.Scenario11' to 'Module1.S1'.]]>.Value.Replace(vbLf, Environment.NewLine)), Diagnostic(ERRID.ERR_NoNonNarrowingOverloadCandidates2, "Foo").WithArguments("Foo", <![CDATA[ 'Public Overloads Sub Foo(y1 As Long)': Argument matching parameter 'y1' narrows from 'Decimal' to 'Long'. 'Public Sub Foo(t1 As Short)': Argument matching parameter 't1' narrows from 'Decimal' to 'Short'.]]>.Value.Replace(vbLf, Environment.NewLine)), Diagnostic(ERRID.ERR_NoNonNarrowingOverloadCandidates2, "tc2").WithArguments("Prop1", <![CDATA[ 'Public Overloads Default Property Prop1(y1 As Module1.C1(Of Integer, Integer)) As Integer': Argument matching parameter 'y1' narrows from 'Module1.Scenario11' to 'Module1.C1(Of Integer, Integer)'. 'Public Default Property Prop1(t1 As Module1.S1) As Integer': Argument matching parameter 't1' narrows from 'Module1.Scenario11' to 'Module1.S1'.]]>.Value.Replace(vbLf, Environment.NewLine)), Diagnostic(ERRID.ERR_NoNonNarrowingOverloadCandidates2, "tc2").WithArguments("Prop1", <![CDATA[ 'Public Overloads Default Property Prop1(y1 As Module1.C1(Of Integer, Integer)) As Integer': Argument matching parameter 'y1' narrows from 'Module1.Scenario11' to 'Module1.C1(Of Integer, Integer)'. 'Public Default Property Prop1(t1 As Module1.S1) As Integer': Argument matching parameter 't1' narrows from 'Module1.Scenario11' to 'Module1.S1'.]]>.Value.Replace(vbLf, Environment.NewLine)), Diagnostic(ERRID.ERR_NoNonNarrowingOverloadCandidates2, "tc3").WithArguments("Prop1", <![CDATA[ 'Public Overloads Default Property Prop1(y1 As Long) As Integer': Argument matching parameter 'y1' narrows from 'Decimal' to 'Long'. 'Public Default Property Prop1(t1 As Short) As Integer': Argument matching parameter 't1' narrows from 'Decimal' to 'Short'.]]>.Value.Replace(vbLf, Environment.NewLine)), Diagnostic(ERRID.ERR_NoNonNarrowingOverloadCandidates2, "tc3").WithArguments("Prop1", <![CDATA[ 'Public Overloads Default Property Prop1(y1 As Long) As Integer': Argument matching parameter 'y1' narrows from 'Decimal' to 'Long'. 'Public Default Property Prop1(t1 As Short) As Integer': Argument matching parameter 't1' narrows from 'Decimal' to 'Short'.]]>.Value.Replace(vbLf, Environment.NewLine)) ) End Sub <Fact()> Public Sub BC30520ERR_ArgumentNarrowing3_RoslynBC30519() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ArgumentNarrowing3"> <file name="a.vb"> Option Strict Off Module Module1 Class sample7C1(Of X) Enum E e1 e2 e3 End Enum End Class Class sample7C2(Of T, Y) Public whichOne As String Sub Foo(ByVal p1 As sample7C1(Of T).E) whichOne = "1" End Sub Sub Foo(ByVal p1 As sample7C1(Of Y).E) whichOne = "2" End Sub Sub Scenario8(ByVal p1 As sample7C1(Of T).E) Call Me.Foo(p1) End Sub End Class Sub test() Dim tc7 As New sample7C2(Of Integer, Integer) Dim sc7 As New sample7C1(Of Byte) 'COMPILEERROR: BC30520, "sample7C1(Of Long).E.e1" Call tc7.Foo (sample7C1(Of Long).E.e1) 'COMPILEERROR: BC30520, "sample7C1(Of Short).E.e2" Call tc7.Foo (sample7C1(Of Short).E.e2) 'COMPILEERROR: BC30520, "sc7.E.e3" Call tc7.Foo (sc7.E.e3) End Sub End Module </file> </compilation>) ' BC0000 - Test bug ' Roslyn BC30519 - Dev11 BC30520 compilation.VerifyDiagnostics( Diagnostic(ERRID.ERR_NoNonNarrowingOverloadCandidates2, "Foo").WithArguments("Foo", <![CDATA[ 'Public Sub Foo(p1 As Module1.sample7C1(Of Integer).E)': Argument matching parameter 'p1' narrows from 'Module1.sample7C1(Of Long).E' to 'Module1.sample7C1(Of Integer).E'. 'Public Sub Foo(p1 As Module1.sample7C1(Of Integer).E)': Argument matching parameter 'p1' narrows from 'Module1.sample7C1(Of Long).E' to 'Module1.sample7C1(Of Integer).E'.]]>.Value.Replace(vbLf, Environment.NewLine)), Diagnostic(ERRID.ERR_NoNonNarrowingOverloadCandidates2, "Foo").WithArguments("Foo", <![CDATA[ 'Public Sub Foo(p1 As Module1.sample7C1(Of Integer).E)': Argument matching parameter 'p1' narrows from 'Module1.sample7C1(Of Short).E' to 'Module1.sample7C1(Of Integer).E'. 'Public Sub Foo(p1 As Module1.sample7C1(Of Integer).E)': Argument matching parameter 'p1' narrows from 'Module1.sample7C1(Of Short).E' to 'Module1.sample7C1(Of Integer).E'.]]>.Value.Replace(vbLf, Environment.NewLine)), Diagnostic(ERRID.WRN_SharedMemberThroughInstance, "sc7.E"), Diagnostic(ERRID.ERR_NoNonNarrowingOverloadCandidates2, "Foo").WithArguments("Foo", <![CDATA[ 'Public Sub Foo(p1 As Module1.sample7C1(Of Integer).E)': Argument matching parameter 'p1' narrows from 'Module1.sample7C1(Of Byte).E' to 'Module1.sample7C1(Of Integer).E'. 'Public Sub Foo(p1 As Module1.sample7C1(Of Integer).E)': Argument matching parameter 'p1' narrows from 'Module1.sample7C1(Of Byte).E' to 'Module1.sample7C1(Of Integer).E'.]]>.Value.Replace(vbLf, Environment.NewLine)) ) 'CompilationUtils.AssertTheseErrors(compilation, ' <expected> 'BC30520: Argument matching parameter 'p1' narrows from 'ConsoleApplication10.Module1.sample7C1(Of Long).E' to 'ConsoleApplication10.Module1.sample7C1(Of Integer).E'. ' Call tc7.Foo (sample7C1(Of Long).E.e1) ' ~~~~ 'BC30520: Argument matching parameter 'p1' narrows from 'ConsoleApplication10.Module1.sample7C1(Of Short).E' to 'ConsoleApplication10.Module1.sample7C1(Of Integer).E'. ' Call tc7.Foo (sample7C1(Of Short).E.e2) ' ~~~~ 'BC30520: Argument matching parameter 'p1' narrows from 'ConsoleApplication10.Module1.sample7C1(Of Byte).E' to 'ConsoleApplication10.Module1.sample7C1(Of Integer).E'. ' Call tc7.Foo (sc7.E.e3) ' ~~~~ '</expected>) End Sub <Fact()> Public Sub BC30521ERR_NoMostSpecificOverload2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="NoMostSpecificOverload2"> <file name="a.vb"> Module Module1 Class C0(Of T) Sub Foo(ByVal t1 As T) End Sub End Class Class C1(Of T, Y) Inherits C0(Of T) Overloads Sub Foo(ByVal y1 As Y) End Sub End Class Structure S1 Dim i As Integer End Structure Class C2 Public Shared Widening Operator CType(ByVal Arg As C2) As C1(Of Integer, Integer) Return New C1(Of Integer, Integer) End Operator Public Shared Widening Operator CType(ByVal Arg As C2) As S1 Return New S1 End Operator End Class Sub test() Dim C As New C1(Of S1, C1(Of Integer, Integer)) Call C.Foo(New C2) End Sub End Module </file> </compilation>) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_NoMostSpecificOverload2, "Foo").WithArguments("Foo", <![CDATA[ 'Public Overloads Sub Module1.C1(Of Module1.S1, Module1.C1(Of Integer, Integer)).Foo(y1 As Module1.C1(Of Integer, Integer))': Not most specific. 'Public Sub Module1.C0(Of Module1.S1).Foo(t1 As Module1.S1)': Not most specific.]]>.Value.Replace(vbLf, Environment.NewLine)) ) End Sub <Fact()> Public Sub BC30524ERR_NoGetProperty1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C WriteOnly Property P Set End Set End Property Shared WriteOnly Property Q Set End Set End Property Sub M() Dim o o = P o = Me.P o = Q o = C.Q End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30524: Property 'P' is 'WriteOnly'. o = P ~ BC30524: Property 'P' is 'WriteOnly'. o = Me.P ~~~~ BC30524: Property 'Q' is 'WriteOnly'. o = Q ~ BC30524: Property 'Q' is 'WriteOnly'. o = C.Q ~~~ </expected>) End Sub <Fact()> Public Sub BC30524ERR_NoGetProperty1_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Interface I Default WriteOnly Property P(s As String) End Interface Structure S Default WriteOnly Property Q(s As String) Set(value) End Set End Property End Structure Class C Default WriteOnly Property R(s As String) Set(value) End Set End Property Shared Sub M(x As I, y As S, z As C) x!Q = x!R y!Q = y!R z!Q = z!R End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30524: Property 'P' is 'WriteOnly'. x!Q = x!R ~~~ BC30524: Property 'Q' is 'WriteOnly'. y!Q = y!R ~~~ BC30524: Property 'R' is 'WriteOnly'. z!Q = z!R ~~~ </expected>) End Sub <Fact()> Public Sub BC30524ERR_NoGetProperty1_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module M1 Sub Main() foo(p) End Sub WriteOnly Property p() As Single Set(ByVal Value As Single) End Set End Property Public Sub foo(ByRef x As Single) End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30524: Property 'p' is 'WriteOnly'. foo(p) ~ </expected>) End Sub <Fact(), WorkItem(6810, "DevDiv_Projects/Roslyn")> Public Sub BC30524ERR_NoGetProperty1_3() CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C WriteOnly Property P As Object() Set(value As Object()) End Set End Property WriteOnly Property Q As System.Action(Of Object) Set(value As System.Action(Of Object)) End Set End Property WriteOnly Property R As C Set(value As C) End Set End Property Default ReadOnly Property S(i As Integer) Get Return Nothing End Get End Property Sub M() Dim o o = P()(1) o = Q()(2) o = R()(3) o = P(1) o = Q(2) o = R(3) End Sub End Class </file> </compilation>).VerifyDiagnostics( Diagnostic(ERRID.ERR_NoGetProperty1, "P()").WithArguments("P"), Diagnostic(ERRID.ERR_NoGetProperty1, "Q()").WithArguments("Q"), Diagnostic(ERRID.ERR_NoGetProperty1, "R()").WithArguments("R"), Diagnostic(ERRID.ERR_NoGetProperty1, "P").WithArguments("P"), Diagnostic(ERRID.ERR_NoGetProperty1, "Q").WithArguments("Q"), Diagnostic(ERRID.ERR_NoGetProperty1, "R").WithArguments("R")) End Sub ''' <summary> ''' Report BC30524 even in cases when the ''' expression will be ignored. ''' </summary> ''' <remarks></remarks> <Fact()> Public Sub BC30524ERR_NoGetProperty1_4() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Class A Class B Friend Const F As Object = Nothing End Class Shared WriteOnly Property P As A Set(value As A) End Set End Property Shared ReadOnly Property Q As A Get Return Nothing End Get End Property Shared Sub M() Dim o As Object o = P.B.F o = Q.B.F End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30524: Property 'P' is 'WriteOnly'. o = P.B.F ~ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. o = Q.B.F ~~~ </expected>) End Sub <Fact()> Public Sub BC30526ERR_NoSetProperty1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C ReadOnly Property P Get Return Nothing End Get End Property Shared ReadOnly Property Q Get Return Nothing End Get End Property Sub M() P = Nothing Me.P = Nothing Q = Nothing C.Q = Nothing End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30526: Property 'P' is 'ReadOnly'. P = Nothing ~~~~~~~~~~~ BC30526: Property 'P' is 'ReadOnly'. Me.P = Nothing ~~~~~~~~~~~~~~ BC30526: Property 'Q' is 'ReadOnly'. Q = Nothing ~~~~~~~~~~~ BC30526: Property 'Q' is 'ReadOnly'. C.Q = Nothing ~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30526ERR_NoSetProperty1_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Interface I Default ReadOnly Property P(s As String) End Interface Structure S Default ReadOnly Property Q(s As String) Get Return Nothing End Get End Property End Structure Class C Default ReadOnly Property R(s As String) Get Return Nothing End Get End Property Shared Sub M(x As I, y As S, z As C) x!Q = x!R y!Q = y!R z!Q = z!R End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30526: Property 'P' is 'ReadOnly'. x!Q = x!R ~~~~~~~~~ BC30526: Property 'Q' is 'ReadOnly'. y!Q = y!R ~~~~~~~~~ BC30526: Property 'R' is 'ReadOnly'. z!Q = z!R ~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30532ERR_DateToDoubleConversion() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="DateToDoubleConversion"> <file name="a.vb"> Structure s1 function foo() as double return #1/1/2000# End function End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30532: Conversion from 'Date' to 'Double' requires calling the 'Date.ToOADate' method. return #1/1/2000# ~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30532ERR_DateToDoubleConversion_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="DateToDoubleConversion"> <file name="a.vb"> Imports System Class C Shared Sub Main() For Each x As Double In New Date() {#12:00:00 AM#} Next End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30532: Conversion from 'Date' to 'Double' requires calling the 'Date.ToOADate' method. For Each x As Double In New Date() {#12:00:00 AM#} ~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30533ERR_DoubleToDateConversion() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="DoubleToDateConversion"> <file name="a.vb"> Structure s1 Function foo() As Date Dim a As Double = 12 Return a End Function End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30533: Conversion from 'Double' to 'Date' requires calling the 'Date.FromOADate' method. Return a ~ </expected>) End Sub <Fact()> Public Sub BC30542ERR_ZeroDivide() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="DateToDoubleConversion"> <file name="a.vb"> Module M1 'Const z = 0 Sub foo() Dim s = 1 \ Nothing Dim m = 1 \ 0 'Dim n = 1 \ z If (1 \ 0 = 1) Then End If End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30542: Division by zero occurred while evaluating this expression. Dim s = 1 \ Nothing ~~~~~~~~~~~ BC30542: Division by zero occurred while evaluating this expression. Dim m = 1 \ 0 ~~~~~ BC30542: Division by zero occurred while evaluating this expression. If (1 \ 0 = 1) Then ~~~~~ </expected>) End Sub <Fact()> Public Sub BC30545ERR_PropertyAccessIgnored() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="PropertyAccessIgnored"> <file name="a.vb"> Class C Shared Property P ReadOnly Property Q Get Return Nothing End Get End Property Property R(o) Get Return Nothing End Get Set(value) End Set End Property Sub M(o) P M(P) C.P C.P = Nothing Q M(Q) Me.Q M(Me.Q) R(Nothing) R(Nothing) = Nothing Me.R(Nothing) M(Me.R(Nothing)) End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30545: Property access must assign to the property or use its value. P ~ BC30545: Property access must assign to the property or use its value. C.P ~~~ BC30545: Property access must assign to the property or use its value. Q ~ BC30545: Property access must assign to the property or use its value. Me.Q ~~~~ BC30545: Property access must assign to the property or use its value. R(Nothing) ~~~~~~~~~~ BC30545: Property access must assign to the property or use its value. Me.R(Nothing) ~~~~~~~~~~~~~ </expected>) End Sub <WorkItem(531311, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531311")> <Fact()> Public Sub BC30545ERR_PropertyAccessIgnored_Latebound() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="PropertyAccessIgnored"> <file name="a.vb"> Structure s1 Dim z As Integer Property foo(ByVal i As Integer) Get Return Nothing End Get Set(ByVal Value) End Set End Property Property foo(ByVal i As Double) Get Return Nothing End Get Set(ByVal Value) End Set End Property Sub goo() Dim o As Object = 1 'COMPILEERROR: BC30545, "foo(o)" foo(o) End Sub End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30545: Property access must assign to the property or use its value. foo(o) ~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30547ERR_InterfaceNoDefault1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Namespace N Interface I End Interface Class C Shared Sub M(x As I) N(x(0)) N(x!P) End Sub Shared Sub N(o As Object) End Sub End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30547: 'I' cannot be indexed because it has no default property. N(x(0)) ~ BC30547: 'I' cannot be indexed because it has no default property. N(x!P) ~ </expected>) End Sub <Fact()> Public Sub BC30554ERR_AmbiguousInUnnamedNamespace1() Dim Lib1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="App1"> <file name="a.vb"> Public Class C1 End Class </file> </compilation>) Dim Lib2 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="App2"> <file name="a.vb"> Public Class C1 End Class </file> </compilation>) Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="APP"> <file name="a.vb"> Imports System Module Module1 Sub Main() Dim obj = New C1() End Sub End Module </file> </compilation>) Dim ref1 = New VisualBasicCompilationReference(Lib1) Dim ref2 = New VisualBasicCompilationReference(Lib2) compilation1 = compilation1.AddReferences(ref1) compilation1 = compilation1.AddReferences(ref2) Dim expectedErrors1 = <errors> BC30554: 'C1' is ambiguous. Dim obj = New C1() ~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC30555ERR_DefaultMemberNotProperty1() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Class C Shared Sub M(a As Array, f As Func(Of Dictionary(Of Object, Object))) Dim o As Object o = Function() Return New Dictionary(Of String, String) End Function!a o = a!b o = f!c o = f()!d End Sub End Class </file> </compilation>) ' For now, lambdas result in BC30491 which differs from Dev10. ' This should change once lambda support is complete. Dim expectedErrors1 = <errors> BC30555: Default member of 'Function &lt;generated method&gt;() As Dictionary(Of String, String)' is not a property. o = Function() ~~~~~~~~~~~ BC30555: Default member of 'Array' is not a property. o = a!b ~ BC30555: Default member of 'Func(Of Dictionary(Of Object, Object))' is not a property. o = f!c ~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC30565ERR_ArrayInitializerTooFewDimensions() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ArrayInitializerTooFewDimensions"> <file name="a.vb"> Module Module1 Sub test() Dim FixedRankArray_1(,) As Double 'COMPILEERROR: BC30565, "(0", BC30198, "," FixedRankArray_1 = New Double(,) {(0.1), {2.4, 4.6}} Exit Sub End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30565: Array initializer has too few dimensions. FixedRankArray_1 = New Double(,) {(0.1), {2.4, 4.6}} ~~~~~ </expected>) End Sub <Fact()> Public Sub BC30566ERR_ArrayInitializerTooManyDimensions() CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ArrayInitializerTooManyDimensions"> <file name="a.vb"> Module Module1 Structure S1 Public x As Long Public s As String End Structure Sub foo() Dim obj = New S1() {{1, "one"}} Exit Sub End Sub End Module </file> </compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_ArrayInitializerTooManyDimensions, "{1, ""one""}")) End Sub ' Roslyn too many extra errors (last 4) <Fact()> Public Sub BC30566ERR_ArrayInitializerTooManyDimensions_1() CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ArrayInitializerTooManyDimensions"> <file name="a.vb"> Module Module1 Sub foo() Dim myArray As Integer(,) = New Integer(2, 1) {{{1, 2}, {3, 4}, {5, 6}}} End Sub End Module </file> </compilation>).VerifyDiagnostics( Diagnostic(ERRID.ERR_ArrayInitializerTooManyDimensions, "{1, 2}"), Diagnostic(ERRID.ERR_ArrayInitializerTooManyDimensions, "{3, 4}"), Diagnostic(ERRID.ERR_ArrayInitializerTooManyDimensions, "{5, 6}"), Diagnostic(ERRID.ERR_InitializerTooManyElements1, "{{1, 2}, {3, 4}, {5, 6}}").WithArguments("1"), Diagnostic(ERRID.ERR_InitializerTooFewElements1, "{{{1, 2}, {3, 4}, {5, 6}}}").WithArguments("2")) End Sub <Fact()> Public Sub BC30567ERR_InitializerTooFewElements1() CreateCompilationWithMscorlib40( <compilation name="InitializerTooFewElements1"> <file name="a.vb"> Class A Sub foo() Dim x = {{1, 2, 3}, {4, 5}} End Sub End Class </file> </compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_InitializerTooFewElements1, "{4, 5}").WithArguments("1")) End Sub <Fact()> Public Sub BC30567ERR_InitializerTooFewElements1_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="InitializerTooFewElements1"> <file name="a.vb"> Class A Sub foo() Dim x127 As Object(,) = New System.Exception(,) {{New System.AccessViolationException, New System.ArgumentException}, {New System.Exception}} End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30567: Array initializer is missing 1 elements. Dim x127 As Object(,) = New System.Exception(,) {{New System.AccessViolationException, New System.ArgumentException}, {New System.Exception}} ~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30567ERR_InitializerTooFewElements1_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C Private A() As Object = New Object(0) {} Private B As Object() = New Object(2) {} Private C As Object(,) = New Object(1, 0) {} Private D As Object(,) = New Object(1, 0) {{}, {2}} Private E As Object(,) = New Object(0, 2) {} Private F()() As Object = New Object(0)() {} Private G()() As Object = New Object(0)() {New Object(0) {}} End Class </file> </compilation>) compilation.AssertTheseDiagnostics( <expected> BC30567: Array initializer is missing 1 elements. Private D As Object(,) = New Object(1, 0) {{}, {2}} ~~ </expected>) End Sub <Fact()> Public Sub BC30568ERR_InitializerTooManyElements1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="InitializerTooManyElements1"> <file name="a.vb"> Class A Sub foo() Dim x127 As Object(,) = New System.Exception(,) {{New System.AccessViolationException}, {New System.Exception, New System.ArgumentException}} End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30568: Array initializer has 1 too many elements. Dim x127 As Object(,) = New System.Exception(,) {{New System.AccessViolationException}, {New System.Exception, New System.ArgumentException}} ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30569ERR_NewOnAbstractClass() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="NewOnAbstractClass"> <file name="a.vb"> Class C1 MustInherit Class C2 Public foo As New C2() End Class Public foo As New C2() End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30569: 'New' cannot be used on a class that is declared 'MustInherit'. Public foo As New C2() ~~~~~~~~ BC30569: 'New' cannot be used on a class that is declared 'MustInherit'. Public foo As New C2() ~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30574ERR_StrictDisallowsLateBinding() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="StrictDisallowsLateBinding"> <file name="a.vb"> Module Module1 Dim bol As Boolean Class C1 Property Prop As Long End Class Sub foo() Dim Obj As Object = New C1() bol = Obj(1) bol = Obj!P End Sub End Module </file> </compilation>, TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.On)) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30574: Option Strict On disallows late binding. bol = Obj(1) ~~~ BC30574: Option Strict On disallows late binding. bol = Obj!P ~~~~~ </expected>) compilation = compilation.WithOptions(compilation.Options.WithOptionStrict(OptionStrict.Custom)) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42017: Late bound resolution; runtime errors could occur. bol = Obj(1) ~~~ BC42016: Implicit conversion from 'Object' to 'Boolean'. bol = Obj(1) ~~~~~~ BC42016: Implicit conversion from 'Object' to 'Boolean'. bol = Obj!P ~~~~~ BC42017: Late bound resolution; runtime errors could occur. bol = Obj!P ~~~~~ </expected>) End Sub <WorkItem(546763, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546763")> <Fact()> Public Sub BC30574ERR_StrictDisallowsLateBinding_16745() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict On Option Infer On Public Module Program Sub Main() Dim a As Object = Nothing a.DoSomething() End Sub End Module </file> </compilation>, TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.On)) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30574: Option Strict On disallows late binding. a.DoSomething() ~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30574ERR_StrictDisallowsLateBinding1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="StrictDisallowsLateBinding"> <file name="a.vb"> Imports System Module Program Delegate Sub d1(ByRef x As Integer, y As Integer) Sub Main() Dim obj As Object = New cls1 Dim o As d1 = AddressOf obj.foo Dim l As Integer = 0 o(l, 2) Console.WriteLine(l) End Sub Class cls1 Shared Sub foo(ByRef x As Integer, y As Integer) x = 42 Console.WriteLine(x + y) End Sub End Class End Module </file> </compilation>, TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.On)) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30574: Option Strict On disallows late binding. Dim o As d1 = AddressOf obj.foo ~~~~~~~ </expected>) compilation = compilation.WithOptions(compilation.Options.WithOptionStrict(OptionStrict.Custom)) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42017: Late bound resolution; runtime errors could occur. Dim o As d1 = AddressOf obj.foo ~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30577ERR_AddressOfOperandNotMethod() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="AddressOfOperandNotMethod"> <file name="a.vb"> Delegate Function MyDelegate() Module M1 Enum MyEnum One End Enum Sub Main() Dim x As MyDelegate Dim oEnum As MyEnum x = AddressOf oEnum x.Invoke() End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30577: 'AddressOf' operand must be the name of a method (without parentheses). x = AddressOf oEnum ~~~~~ </expected>) End Sub <Fact()> Public Sub BC30581ERR_AddressOfNotDelegate1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="AddressOfNotDelegate1"> <file name="a.vb"> Module M Sub Main() Dim x = New Object() Dim f = AddressOf x.GetType End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30581: 'AddressOf' expression cannot be converted to 'Object' because 'Object' is not a delegate type. Dim f = AddressOf x.GetType ~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30582ERR_SyncLockRequiresReferenceType1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="SyncLockRequiresReferenceType1"> <file name="a.vb"> Imports System Module M1 Class C Private Shared count = 0 Sub IncrementCount() Dim i As Integer SyncLock i = 0 count = count + 1 End SyncLock End Sub End Class End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30582: 'SyncLock' operand cannot be of type 'Boolean' because 'Boolean' is not a reference type. SyncLock i = 0 ~~~~~ </expected>) End Sub <Fact()> Public Sub BC30582ERR_SyncLockRequiresReferenceType1_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="SyncLockRequiresReferenceType1"> <file name="a.vb"> Imports System Module Program Sub Main(args As String()) Dim S1_a As New Object() Dim S1_b As Integer? = 4 Dim S1_c As Integer? = 41 SyncLock If(False, S1_a, S1_a) End SyncLock SyncLock If(True, S1_b, S1_b) End SyncLock SyncLock If(False, S1_b, 1) End SyncLock End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30582: 'SyncLock' operand cannot be of type 'Integer?' because 'Integer?' is not a reference type. SyncLock If(True, S1_b, S1_b) ~~~~~~~~~~~~~~~~~~~~ BC30582: 'SyncLock' operand cannot be of type 'Integer?' because 'Integer?' is not a reference type. SyncLock If(False, S1_b, 1) ~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30582ERR_SyncLockRequiresReferenceType1_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="SyncLockRequiresReferenceType1"> <file name="a.vb"> Interface I End Interface Class A End Class Class C Shared Sub M(Of T1, T2 As Class, T3 As Structure, T4 As New, T5 As I, T6 As A, T7 As U, U)(_1 As T1, _2 As T2, _3 As T3, _4 As T4, _5 As T5, _6 As T6, _7 As T7) SyncLock _1 End SyncLock SyncLock _2 End SyncLock SyncLock _3 End SyncLock SyncLock _4 End SyncLock SyncLock _5 End SyncLock SyncLock _6 End SyncLock SyncLock _7 End SyncLock End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30582: 'SyncLock' operand cannot be of type 'T1' because 'T1' is not a reference type. SyncLock _1 ~~ BC30582: 'SyncLock' operand cannot be of type 'T3' because 'T3' is not a reference type. SyncLock _3 ~~ BC30582: 'SyncLock' operand cannot be of type 'T4' because 'T4' is not a reference type. SyncLock _4 ~~ BC30582: 'SyncLock' operand cannot be of type 'T5' because 'T5' is not a reference type. SyncLock _5 ~~ BC30582: 'SyncLock' operand cannot be of type 'T7' because 'T7' is not a reference type. SyncLock _7 ~~ </expected>) End Sub <Fact> Public Sub BC30587ERR_NamedParamArrayArgument() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="NamedParamArrayArgument"> <file name="a.vb"> Class C1 Shared Sub Main() Dim a As New C1 a.abc(s:=10) End Sub Sub abc(ByVal ParamArray s() As Integer) End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30587: Named argument cannot match a ParamArray parameter. a.abc(s:=10) ~ </expected>) End Sub <Fact()> Public Sub BC30588ERR_OmittedParamArrayArgument() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="OmittedParamArrayArgument"> <file name="a.vb"> Imports System Imports C1(Of String, Integer) Class C1(Of T As {Class}, U As Structure) Public Shared Property Overloaded(ByVal ParamArray y() As Exception) As C2 Get Return New C2 End Get Set(ByVal value As C2) End Set End Property End Class Class C2 End Class Module M1 Sub FOO() Overloaded(, , ) = Nothing End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30588: Omitted argument cannot match a ParamArray parameter. Overloaded(, , ) = Nothing ~ BC30588: Omitted argument cannot match a ParamArray parameter. Overloaded(, , ) = Nothing ~ BC30588: Omitted argument cannot match a ParamArray parameter. Overloaded(, , ) = Nothing ~ </expected>) End Sub <Fact()> Public Sub BC30611ERR_NegativeArraySize() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="NegativeArraySize"> <file name="a.vb"> Class C1 Sub foo() Dim x8(-2) As String End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30611: Array dimensions cannot have a negative size. Dim x8(-2) As String ~~ </expected>) End Sub <Fact()> Public Sub BC30611ERR_NegativeArraySize_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="NegativeArraySize"> <file name="a.vb"> Class C1 Sub foo() Dim arr11 As Integer(,) = New Integer(-2, -2) {} ' Invalid End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30611: Array dimensions cannot have a negative size. Dim arr11 As Integer(,) = New Integer(-2, -2) {} ' Invalid ~~ BC30611: Array dimensions cannot have a negative size. Dim arr11 As Integer(,) = New Integer(-2, -2) {} ' Invalid ~~ </expected>) End Sub <Fact()> Public Sub BC30611ERR_NegativeArraySize_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="NegativeArraySize"> <file name="a.vb"> Class C1 Sub foo() Dim arr(0 To 0, 0 To -2) As Integer 'Invalid End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30611: Array dimensions cannot have a negative size. Dim arr(0 To 0, 0 To -2) As Integer 'Invalid ~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30614ERR_MyClassAbstractCall1_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BC30614ERR_MyClassAbstractCall1_1"> <file name="a.vb"> MustInherit Class C1 Public Sub UseMyClass() MyClass.foo() End Sub MustOverride Sub foo() End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30614: 'MustOverride' method 'Public MustOverride Sub foo()' cannot be called with 'MyClass'. MyClass.foo() ~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30614ERR_MyClassAbstractCall1_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BC30614ERR_MyClassAbstractCall1_2"> <file name="a.vb"> Public MustInherit Class Base1 Public MustOverride Property P1() Public Sub M2() MyClass.P1 = MyClass.P1 End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30614: 'MustOverride' method 'Public MustOverride Property P1 As Object' cannot be called with 'MyClass'. MyClass.P1 = MyClass.P1 ~~~~~~~~~~ BC30614: 'MustOverride' method 'Public MustOverride Property P1 As Object' cannot be called with 'MyClass'. MyClass.P1 = MyClass.P1 ~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30614ERR_MyClassAbstractCall1_3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BC30614ERR_MyClassAbstractCall1_3"> <file name="a.vb"> Imports System Public MustInherit Class Base1 Public MustOverride Function F1() As Integer Public Sub M2() Dim _func As Func(Of Integer) = AddressOf MyClass.F1 End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30614: 'MustOverride' method 'Public MustOverride Function F1() As Integer' cannot be called with 'MyClass'. Dim _func As Func(Of Integer) = AddressOf MyClass.F1 ~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30614ERR_MyClassAbstractCall1_4() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BC30614ERR_MyClassAbstractCall1_4"> <file name="a.vb"> Imports System Public MustInherit Class Base1 Public MustOverride Function F1() As Integer Public Function F2() As Integer Return 1 End Function Public Sub M2() Dim _func As Func(Of Func(Of Integer)) = Function() New Func(Of Integer)(AddressOf MyClass.F1) Dim _func2 As Func(Of Func(Of Integer)) = Function() New Func(Of Integer)(AddressOf MyClass.F2) End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30614: 'MustOverride' method 'Public MustOverride Function F1() As Integer' cannot be called with 'MyClass'. Dim _func As Func(Of Func(Of Integer)) = Function() New Func(Of Integer)(AddressOf MyClass.F1) ~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30614ERR_MyClassAbstractCall1_5() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BC30614ERR_MyClassAbstractCall1_5"> <file name="a.vb"> Imports System Public MustInherit Class Base1 Public MustOverride Function F1() As Integer Public Function F2() As Integer Return 1 End Function Public FLD As Func(Of Func(Of Integer)) = Function() New Func(Of Integer)(AddressOf MyClass.F1) Public Property PROP As Func(Of Func(Of Integer)) = Function() New Func(Of Integer)(AddressOf MyClass.F1) Public FLD2 As Func(Of Func(Of Integer)) = Function() New Func(Of Integer)(AddressOf MyClass.F2) Public Property PROP2 As Func(Of Func(Of Integer)) = Function() New Func(Of Integer)(AddressOf MyClass.F2) End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30614: 'MustOverride' method 'Public MustOverride Function F1() As Integer' cannot be called with 'MyClass'. Function() New Func(Of Integer)(AddressOf MyClass.F1) ~~~~~~~~~~ BC30614: 'MustOverride' method 'Public MustOverride Function F1() As Integer' cannot be called with 'MyClass'. Function() New Func(Of Integer)(AddressOf MyClass.F1) ~~~~~~~~~~ </expected>) End Sub ' Different error <Fact()> Public Sub BC30615ERR_EndDisallowedInDllProjects() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="EndDisallowedInDllProjects"> <file name="a.vb"> Class C1 Function foo() End End Class </file> </compilation>, options:=TestOptions.ReleaseDll) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30027: 'End Function' expected. Function foo() ~~~~~~~~~~~~~~ BC30615: 'End' statement cannot be used in class library projects. End ~~~ </expected>) End Sub <Fact()> Public Sub BC30616ERR_BlockLocalShadowing1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="BlockLocalShadowing1"> <file name="a.vb"> Class C1 Sub foo() dim s = 10 if s>5 dim s = 5 if s > 7 dim s = 7 End If End If End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30616: Variable 's' hides a variable in an enclosing block. dim s = 5 ~ BC30616: Variable 's' hides a variable in an enclosing block. dim s = 7 ~ </expected>) End Sub ' spec changes in Roslyn <WorkItem(528680, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528680")> <Fact()> Public Sub BC30616ERR_BlockLocalShadowing1_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="BlockLocalShadowing1"> <file name="a.vb"> Class C Private field As Integer = 0 Private Property [property]() As Integer Get Return m_property End Get Set(value As Integer) m_property = value End Set End Property Property prop() As Integer Get Return 1 End Get Set(ByVal Value As Integer) ' Was Dev10: COMPILEERROR: BC30616, "value" ' now Dev10: BC30734: 'value' is already declared as a parameter of this method. For Each value As Byte In New Byte() {1, 2, 3} Next End Set End Property Private m_property As Integer Shared Sub Main() Dim ints As Integer() = New Integer() {1, 2, 3} Dim strings As String() = New String() {"1", "2", "3"} Dim conflict As Integer = 1 For Each field As Integer In ints Next For Each [property] As String In strings Next For Each conflict As String In strings Next Dim [qq] As Integer = 23 'COMPILEERROR: BC30616, "qq" For Each qq As Integer In New Integer() {1, 2, 3} Next Dim ww As Integer = 23 'COMPILEERROR: BC30616, "[ww]" For Each [ww] As Integer In New Integer() {1, 2, 3} Next For Each z As Integer In New Integer() {1, 2, 3} 'COMPILEERROR: BC30616, "z" For Each z As Decimal In New Decimal() {1, 2, 3} Next Next For Each t As Long In New Long() {1, 2, 3} For Each u As Boolean In New Boolean() {False, True} 'COMPILEERROR: BC30616, "t" Dim t As Integer Next Next End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30734: 'value' is already declared as a parameter of this method. For Each value As Byte In New Byte() {1, 2, 3} ~~~~~ BC30616: Variable 'conflict' hides a variable in an enclosing block. For Each conflict As String In strings ~~~~~~~~ BC30616: Variable 'qq' hides a variable in an enclosing block. For Each qq As Integer In New Integer() {1, 2, 3} ~~ BC30616: Variable 'ww' hides a variable in an enclosing block. For Each [ww] As Integer In New Integer() {1, 2, 3} ~~~~ BC30616: Variable 'z' hides a variable in an enclosing block. For Each z As Decimal In New Decimal() {1, 2, 3} ~ BC30616: Variable 't' hides a variable in an enclosing block. Dim t As Integer ~ BC42024: Unused local variable: 't'. Dim t As Integer ~ </expected>) End Sub <Fact()> Public Sub BC30616ERR_BlockLocalShadowing1_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="BlockLocalShadowing1"> <file name="a.vb"> Option Strict Off Option Infer On Public Class MyClass1 Public Shared Sub Main() Dim var1 As Integer For var1 As Integer = 1 To 10 Next End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42024: Unused local variable: 'var1'. Dim var1 As Integer ~~~~ BC30616: Variable 'var1' hides a variable in an enclosing block. For var1 As Integer = 1 To 10 ~~~~ </expected>) End Sub <Fact()> Public Sub BC30616ERR_BlockLocalShadowing1_4() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="BlockLocalShadowing1"> <file name="a.vb"> Public Class MyClass1 Public Shared Sub Main() Static var2 As Long For var2 As Short = 0 To 10 Next var2 = 0 End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30616: Variable 'var2' hides a variable in an enclosing block. For var2 As Short = 0 To 10 ~~~~ </expected>) End Sub <Fact()> Public Sub BC30616ERR_BlockLocalShadowing1_5() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="BlockLocalShadowing1"> <file name="a.vb"> Public Class MyClass1 Public Shared Sub Main() For varo As Integer = 0 To 10 For varo As Integer = 0 To 10 Next Next End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30616: Variable 'varo' hides a variable in an enclosing block. For varo As Integer = 0 To 10 ~~~~ </expected>) End Sub <Fact()> Public Sub BC30616ERR_BlockLocalShadowing1_6() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="BlockLocalShadowing1"> <file name="a.vb"> Public Class MyClass1 Public Shared Sub Main() For varo As Integer = 0 To 10 Dim [qqq] As Integer For qqq As Integer = 0 To 10 Next Dim www As Integer For [www] As Integer = 0 To 10 Next Next End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42024: Unused local variable: 'qqq'. Dim [qqq] As Integer ~~~~~ BC30616: Variable 'qqq' hides a variable in an enclosing block. For qqq As Integer = 0 To 10 ~~~ BC42024: Unused local variable: 'www'. Dim www As Integer ~~~ BC30616: Variable 'www' hides a variable in an enclosing block. For [www] As Integer = 0 To 10 ~~~~~ </expected>) End Sub <Fact()> Public Sub BC30616ERR_BlockLocalShadowing1_7() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="BlockLocalShadowing1"> <file name="a.vb"> Public Class MyClass1 Public Shared Sub Main() For x As Integer = 0 To 10 Dim x As Integer Next End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30616: Variable 'x' hides a variable in an enclosing block. Dim x As Integer ~ BC42024: Unused local variable: 'x'. Dim x As Integer ~ </expected>) End Sub <Fact()> Public Sub BC30616ERR_BlockLocalShadowing1_8() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="BlockLocalShadowing1"> <file name="a.vb"> Public Class MyClass1 Public Shared Sub Main() For var1 As Integer = 0 To 10 For var2 As Integer = 0 To 10 Dim var1 As Integer Next Next End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30616: Variable 'var1' hides a variable in an enclosing block. Dim var1 As Integer ~~~~ BC42024: Unused local variable: 'var1'. Dim var1 As Integer ~~~~ </expected>) End Sub <Fact()> Public Sub BC30616ERR_BlockLocalShadowing1_9() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="DuplicateLocals1"> <file name="a.vb"> Class C Shared Sub Main() For Each r As Integer In New Integer() {1, 2, 3} 'Was COMPILEERROR: BC30288, "r" in Dev10 'Now BC30616 Dim r As Integer Next End Sub End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC30616: Variable 'r' hides a variable in an enclosing block. Dim r As Integer ~ BC42024: Unused local variable: 'r'. Dim r As Integer ~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC30647ERR_ReturnFromNonFunction() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="ReturnFromNonFunction"> <file name="a.vb"> Structure S1 shared sub foo() return 1 end sub End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30647: 'Return' statement in a Sub or a Set cannot return a value. return 1 ~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30654ERR_ReturnWithoutValue() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="ReturnWithoutValue"> <file name="a.vb"> Structure S1 shared Function foo return end Function End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30654: 'Return' statement in a Function, Get, or Operator must return a value. return ~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30657ERR_UnsupportedMethod1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="UnsupportedMethod1"> <file name="a.vb"> Class C1 Dim x As System.Threading.IOCompletionCallback Sub Sub1() End Sub Sub New() x = New System.Threading.IOCompletionCallback(AddressOf Sub1) End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30657: 'IOCompletionCallback' has a return type that is not supported or parameter types that are not supported. x = New System.Threading.IOCompletionCallback(AddressOf Sub1) ~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30658ERR_NoNonIndexProperty1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="NoNonIndexProperty1"> <file name="a.vb"> Option Explicit On Imports System Module M1 Class MyAttr Inherits Attribute Public Property Prop(ByVal i As Integer) As Integer Get Return Nothing End Get Set(ByVal Value As Integer) End Set End Property End Class &lt;MyAttr(Prop:=1)&gt;'BIND:"Prop" Class C1 End Class End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30658: Property 'Prop' with no parameters cannot be found. &lt;MyAttr(Prop:=1)&gt;'BIND:"Prop" ~~~~ </expected>) VerifyOperationTreeForTest(Of IdentifierNameSyntax)(compilation, "a.vb", <![CDATA[ IPropertyReferenceOperation: Property M1.MyAttr.Prop(i As System.Int32) As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsInvalid) (Syntax: 'Prop') Instance Receiver: null]]>.Value) End Sub <Fact()> Public Sub BC30659ERR_BadAttributePropertyType1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BadAttributePropertyType1"> <file name="a.vb"><![CDATA[ Imports System <AttributeUsage(AttributeTargets.Class, AllowMultiple:=True, Inherited:=True)> Class MultiUseAttribute Inherits System.Attribute Public Sub New(ByVal Value As Integer) End Sub End Class <AttributeUsage(AttributeTargets.Class, Inherited:=True)> Class SingleUseAttribute Inherits Attribute Property A() As Date Get Return Nothing End Get Set(value As Date) End Set End Property Public Sub New(ByVal Value As Integer) End Sub End Class <SingleUse(1, A:=1.1), MultiUse(1)> Class Base End Class <SingleUse(0, A:=1.1), MultiUse(0)> Class Derived Inherits Base End Class ]]></file> </compilation>).VerifyDiagnostics( Diagnostic(ERRID.ERR_BadAttributePropertyType1, "A").WithArguments("A"), Diagnostic(ERRID.ERR_DoubleToDateConversion, "1.1"), Diagnostic(ERRID.ERR_BadAttributePropertyType1, "A").WithArguments("A"), Diagnostic(ERRID.ERR_DoubleToDateConversion, "1.1")) ' BC30533: Dev10 NOT report End Sub <Fact()> Public Sub BC30661ERR_PropertyOrFieldNotDefined1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="PropertyOrFieldNotDefined1"> <file name="a.vb"><![CDATA[ Imports System <AttributeUsage(AttributeTargets.All)> Public Class GeneralAttribute Inherits Attribute End Class <General(NotExist:=10)> Class C1 End Class ]]></file> </compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_PropertyOrFieldNotDefined1, "NotExist").WithArguments("NotExist")) End Sub <Fact()> Public Sub BC30665ERR_CantThrowNonException() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module M1 Sub Foo() Throw (Nothing) End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30665: 'Throw' operand must derive from 'System.Exception'. Throw (Nothing) ~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30665ERR_CantThrowNonException_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Class A End Class Class C Shared Sub M1(Of T As System.Exception)(e As T) Throw e End Sub Shared Sub M2(Of T As {System.Exception, New})() Throw New T() End Sub Shared Sub M3(Of T As A)(a As T) Throw a End Sub Shared Sub M4(Of U As New)() Throw New U() End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30665: 'Throw' operand must derive from 'System.Exception'. Throw a ~~~~~~~ BC30665: 'Throw' operand must derive from 'System.Exception'. Throw New U() ~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30666ERR_MustBeInCatchToRethrow() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="MustBeInCatchToRethrow"> <file name="a.vb"> Imports System Class C1 Sub foo() Try Throw Catch ex As Exception End Try End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30666: 'Throw' statement cannot omit operand outside a 'Catch' statement or inside a 'Finally' statement. Throw ~~~~~ </expected>) End Sub <Fact()> Public Sub BC30671ERR_InitWithMultipleDeclarators() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="InitWithMultipleDeclarators"> <file name="a.vb"> Imports System Public Structure Class1 implements IDisposable Public Sub Dispose() implements Idisposable.Dispose End Sub End Structure Public Class Class2 Sub foo() Dim a, b As Class1 = New Class1 a = nothing b = nothing Using c, d as Class1 = nothing End Using End Sub End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC30671: Explicit initialization is not permitted with multiple variables declared with a single type specifier. Dim a, b As Class1 = New Class1 ~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36011: 'Using' resource variable must have an explicit initialization. Using c, d as Class1 = nothing ~ BC30671: Explicit initialization is not permitted with multiple variables declared with a single type specifier. Using c, d as Class1 = nothing ~~~~~~~~~~~~~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC30671ERR_InitWithMultipleDeclarators02() Dim source = <compilation> <file name="a.vb"> Option strict on imports system Class C1 ' not so ok public i, j as integer = 23 ' ok enough :) public k as integer,l as integer = 23 Public shared Sub Main(args() as string) End sub End Class </file> </compilation> Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) CompilationUtils.AssertTheseDiagnostics(c1, <expected> BC30671: Explicit initialization is not permitted with multiple variables declared with a single type specifier. public i, j as integer = 23 ~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30672ERR_InitWithExplicitArraySizes() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="InitWithExplicitArraySizes"> <file name="a.vb"> Structure myStruct1 sub foo() Dim a6(,) As Integer Dim b6(5, 5) As Integer = a6 end Sub End structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30672: Explicit initialization is not permitted for arrays declared with explicit bounds. Dim b6(5, 5) As Integer = a6 ~~~~~~~~ BC42104: Variable 'a6' is used before it has been assigned a value. A null reference exception could result at runtime. Dim b6(5, 5) As Integer = a6 ~~ </expected>) End Sub <WorkItem(542258, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542258")> <Fact()> Public Sub BC30672ERR_InitWithExplicitArraySizes_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="InitWithExplicitArraySizes"> <file name="a.vb"> Class Cls1 Public Arr(3) As Cls1 = New Cls1() {New Cls1} Sub foo Dim Arr(3) As Cls1 = New Cls1() {New Cls1} End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30672: Explicit initialization is not permitted for arrays declared with explicit bounds. Public Arr(3) As Cls1 = New Cls1() {New Cls1} ~~~~~~ BC30672: Explicit initialization is not permitted for arrays declared with explicit bounds. Dim Arr(3) As Cls1 = New Cls1() {New Cls1} ~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30672ERR_InitWithExplicitArraySizes_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="InitWithExplicitArraySizes"> <file name="a.vb"> Option Infer On Imports System Module Module1 Sub Main() Dim arr14(1, 2) = New Double(1, 2) {} ' Invalid End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30672: Explicit initialization is not permitted for arrays declared with explicit bounds. Dim arr14(1, 2) = New Double(1, 2) {} ' Invalid ~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30676ERR_NameNotEvent2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="NameNotEvent2"> <file name="a.vb"> Option Strict Off Module M Sub Foo() Dim x As C1 = New C1 AddHandler x.E, Sub() Console.WriteLine() End Sub End Module Class C1 Public Dim E As String End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30676: 'E' is not an event of 'C1'. AddHandler x.E, Sub() Console.WriteLine() ~ </expected>) End Sub <Fact()> Public Sub BC30677ERR_AddOrRemoveHandlerEvent() CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="AddOrRemoveHandlerEvent"> <file name="a.vb"> Module M Sub Main() AddHandler Nothing, Nothing End Sub End Module </file> </compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_AddOrRemoveHandlerEvent, "Nothing")) End Sub <Fact(), WorkItem(918579, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/918579"), WorkItem(34, "CodePlex")> Public Sub BC30685ERR_AmbiguousAcrossInterfaces3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="AmbiguousAcrossInterfaces3"> <file name="a.vb"> Interface A Sub fun(ByVal i As Integer) End Interface Interface AB Inherits A Shadows Sub fun(ByVal i As Integer) End Interface Interface AC Inherits A Shadows Sub fun(ByVal i As Integer) End Interface Interface ABS Inherits AB, AC End Interface Class Test Sub D(ByVal d As ABS) d.fun(2) End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30521: Overload resolution failed because no accessible 'fun' is most specific for these arguments: 'Sub AB.fun(i As Integer)': Not most specific. 'Sub AC.fun(i As Integer)': Not most specific. d.fun(2) ~~~ </expected>) End Sub <Fact()> Public Sub BC30686ERR_DefaultPropertyAmbiguousAcrossInterfaces4() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="DefaultPropertyAmbiguousAcrossInterfaces4"> <file name="a.vb"> Option Strict On Interface IA(Of T) Default ReadOnly Property P(o As T) As Object End Interface Interface IB1(Of T) Inherits IA(Of T) End Interface Interface IB2(Of T) Inherits IA(Of T) Default Overloads ReadOnly Property P(x As T, y As T) As Object End Interface Interface IB3(Of T) Inherits IA(Of T) Default Overloads ReadOnly Property Q(x As Integer, y As Integer, z As Integer) As Object End Interface Interface IC1 Inherits IA(Of String), IB1(Of String) End Interface Interface IC2 Inherits IA(Of String), IB1(Of Object) End Interface Interface IC3 Inherits IA(Of String), IB2(Of String) End Interface Interface IC4 Inherits IA(Of String), IB3(Of String) End Interface Module M Sub M(c1 As IC1, c2 As IC2, c3 As IC3, c4 As IC4) Dim value As Object value = c1("") value = c2("") value = c3("") value = c4("") End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC40007: Default property 'Q' conflicts with the default property 'P' in the base interface 'IA'. 'Q' will be the default property. 'Q' should be declared 'Shadows'. Default Overloads ReadOnly Property Q(x As Integer, y As Integer, z As Integer) As Object ~ BC30686: Default property access is ambiguous between the inherited interface members 'ReadOnly Default Property P(o As String) As Object' of interface 'IA(Of String)' and 'ReadOnly Default Property P(o As Object) As Object' of interface 'IA(Of Object)'. value = c2("") ~~ BC30686: Default property access is ambiguous between the inherited interface members 'ReadOnly Default Property P(o As String) As Object' of interface 'IA(Of String)' and 'ReadOnly Default Property P(x As String, y As String) As Object' of interface 'IB2(Of String)'. value = c3("") ~~ BC30686: Default property access is ambiguous between the inherited interface members 'ReadOnly Default Property P(o As String) As Object' of interface 'IA(Of String)' and 'ReadOnly Default Property Q(x As Integer, y As Integer, z As Integer) As Object' of interface 'IB3(Of String)'. value = c4("") ~~ </expected>) End Sub <Fact()> Public Sub BC30690ERR_StructureNoDefault1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Namespace N Structure S End Structure End Namespace Namespace M Class C Shared Sub M(x As N.S) N(x(0)) N(x!P) End Sub Shared Sub N(o As Object) End Sub End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30690: Structure 'S' cannot be indexed because it has no default property. N(x(0)) ~ BC30690: Structure 'S' cannot be indexed because it has no default property. N(x!P) ~ </expected>) End Sub <Fact()> Public Sub BC30734ERR_LocalNamedSameAsParam1() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="LocalNamedSameAsParam1"> <file name="a.vb"> Class cls0(Of G) Sub foo(Of T) (ByVal x As T) Dim x As T End Sub End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC30734: 'x' is already declared as a parameter of this method. Dim x As T ~ BC42024: Unused local variable: 'x'. Dim x As T ~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC30734ERR_LocalNamedSameAsParam1_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="BC30734ERR_LocalNamedSameAsParam1_2"> <file name="a.vb"> Class C Private field As Integer = 0 Private Property [property]() As Integer Get Return m_property End Get Set(value As Integer) m_property = value End Set End Property Property prop() As Integer Get Return 1 End Get Set(ByVal Value As Integer) ' Was Dev10: COMPILEERROR: BC30616, "value" ' Now: BC30734 For Each value As Byte In New Byte() {1, 2, 3} Next End Set End Property Private m_property As Integer Shared Sub Main() End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30734: 'value' is already declared as a parameter of this method. For Each value As Byte In New Byte() {1, 2, 3} ~~~~~ </expected>) End Sub <WorkItem(528680, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528680")> <Fact()> Public Sub BC30734ERR_LocalNamedSameAsParam1_3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="BlockLocalShadowing1"> <file name="a.vb"> Public Class MyClass1 Public Shared Sub Main() End Sub Sub foo(ByVal p1 As Integer) For p1 As Integer = 1 To 10 Next End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30734: 'p1' is already declared as a parameter of this method. For p1 As Integer = 1 To 10 ~~ </expected>) End Sub <Fact()> Public Sub BC30742ERR_CannotConvertValue2() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports microsoft.visualbasic.strings Module M1 Sub foo() Dim i As Integer Dim c As Char I% = Asc("") i% = Asc("" + "" + "" + "" + "" + "" + "" + "" + "") c = ChrW(65536) c = ChrW(-68888) End Sub End module </file> </compilation>) Dim expectedErrors1 = <errors> BC30742: Value '' cannot be converted to 'Integer'. I% = Asc("") ~~~~~~~ BC30742: Value '' cannot be converted to 'Integer'. i% = Asc("" + "" + "" + "" + "" + "" + "" + "" + "") ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30742: Value '65536' cannot be converted to 'Char'. c = ChrW(65536) ~~~~~~~~~~~ BC30742: Value '-68888' cannot be converted to 'Char'. c = ChrW(-68888) ~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC30742ERR_CannotConvertValue2_2() Dim source = <compilation> <file name="a.vb"> Option strict on imports system imports microsoft.visualbasic.strings Imports System.Text Class C1 private const f1 as integer = Asc("") ' empty string private const f2 as integer = AscW("") ' empty string private const f3 as integer = Asc(CStr(nothing)) ' nothing string private const f4 as integer = AscW(CStr(nothing)) ' nothing string private const f5 as Char = ChrW(65536) Public shared Sub Main(args() as string) End sub End Class </file> </compilation> Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) AssertTheseDiagnostics(c1, <expected> BC30742: Value '' cannot be converted to 'Integer'. private const f1 as integer = Asc("") ' empty string ~~~~~~~ BC30742: Value '' cannot be converted to 'Integer'. private const f2 as integer = AscW("") ' empty string ~~~~~~~~ BC30742: Value '' cannot be converted to 'Integer'. private const f3 as integer = Asc(CStr(nothing)) ' nothing string ~~~~~~~~~~~~~~~~~~ BC30742: Value '' cannot be converted to 'Integer'. private const f4 as integer = AscW(CStr(nothing)) ' nothing string ~~~~~~~~~~~~~~~~~~~ BC30742: Value '65536' cannot be converted to 'Char'. private const f5 as Char = ChrW(65536) ~~~~~~~~~~~ </expected>) End Sub <WorkItem(574290, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/574290")> <Fact()> Public Sub BC30742ERR_PassVBNullToAsc() Dim source = <compilation name="ExpressionContext"> <file name="a.vb"> Imports Microsoft.VisualBasic Module Module1 Sub Main Asc(vbnullstring) End Sub End MOdule </file> </compilation> CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_CannotConvertValue2, "Asc(vbnullstring)").WithArguments("", "Integer")) End Sub <Fact()> Public Sub BC30752ERR_OnErrorInSyncLock() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="OnErrorInSyncLock"> <file name="a.vb"> Imports System Class C Sub IncrementCount() SyncLock GetType(C) On Error GoTo 0 End SyncLock End Sub End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC30752: 'On Error' statements are not valid within 'SyncLock' statements. On Error GoTo 0 ~~~~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC30753ERR_NarrowingConversionCollection2() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="NarrowingConversionCollection2"> <file name="a.vb"> option strict on Imports System class C1 Function Main() As Microsoft.VisualBasic.Collection 'Dim collection As Microsoft.VisualBasic. = Nothing Dim _collection As _Collection = Nothing return _collection End function End Class Interface _Collection End Interface </file> </compilation>) Dim expectedErrors1 = <errors> BC30753: Option Strict On disallows implicit conversions from '_Collection' to 'Collection'; the Visual Basic 6.0 collection type is not compatible with the .NET Framework collection type. return _collection ~~~~~~~~~~~ BC42322: Runtime errors might occur when converting '_Collection' to 'Collection'. return _collection ~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC30754ERR_GotoIntoTryHandler() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GotoIntoTryHandler"> <file name="a.vb"> Imports System Class C1 Sub Main() Do While (True) GoTo LB1 Loop Try Catch ex As Exception Finally LB1: End Try End Sub End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC30754: 'GoTo LB1' is not valid because 'LB1' is inside a 'Try', 'Catch' or 'Finally' statement that does not contain this statement. GoTo LB1 ~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <WorkItem(543055, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543055")> <Fact()> Public Sub BC30754ERR_GotoIntoTryHandler_2() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GotoIntoTryHandler"> <file name="a.vb"> Imports System Module Program Sub Main(args As String()) Try GoTo label GoTo label5 Catch ex As Exception label: Finally label5: End Try End Sub End Module </file> </compilation>) Dim expectedErrors1 = <errors> BC30754: 'GoTo label' is not valid because 'label' is inside a 'Try', 'Catch' or 'Finally' statement that does not contain this statement. GoTo label ~~~~~ BC30754: 'GoTo label5' is not valid because 'label5' is inside a 'Try', 'Catch' or 'Finally' statement that does not contain this statement. GoTo label5 ~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC30755ERR_GotoIntoSyncLock() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GotoIntoSyncLock"> <file name="a.vb"> Imports System Class C Sub IncrementCount() SyncLock GetType(C) label: End SyncLock GoTo label End Sub End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC30755: 'GoTo label' is not valid because 'label' is inside a 'SyncLock' statement that does not contain this statement. GoTo label ~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC30756ERR_GotoIntoWith() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GotoIntoWith"> <file name="a.vb"> Class C1 Sub Main() Dim s = New Type1() With s .x = 1 GoTo lab1 End With With s lab1: .x = 1 End With End Sub End Class Class Type1 Public x As Short End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC30756: 'GoTo lab1' is not valid because 'lab1' is inside a 'With' statement that does not contain this statement. GoTo lab1 ~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC30756ERR_GotoIntoWith_1() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GotoIntoWith"> <file name="a.vb"> Class C1 Function Main() Dim s = New Type1() With s lab1: .x = 1 End With GoTo lab1 End Function End Class Class Type1 Public x As Short End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC30756: 'GoTo lab1' is not valid because 'lab1' is inside a 'With' statement that does not contain this statement. GoTo lab1 ~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC30757ERR_GotoIntoFor() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GotoIntoFor"> <file name="a.vb"> Class C1 Sub Main() Dim s = New Type1() With s .x = 1 GoTo label1 End With For i = 0 To 5 GoTo label1 label1: Continue For Next End Sub End Class Class Type1 Public x As Short End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC30757: 'GoTo label1' is not valid because 'label1' is inside a 'For' or 'For Each' statement that does not contain this statement. GoTo label1 ~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC30757ERR_GotoIntoFor_1() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GotoIntoFor"> <file name="a.vb"> Class C1 Function Main() if (true) GoTo label1 End If For i as Integer = 0 To 5 GoTo label1 label1: Continue For Next return 1 End Function End Class Class Type1 Public x As Short End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC30757: 'GoTo label1' is not valid because 'label1' is inside a 'For' or 'For Each' statement that does not contain this statement. GoTo label1 ~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC30757ERR_GotoIntoFor_2() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GotoIntoFor"> <file name="a.vb"> Option Infer On Option Strict Off Class C1 Function Main() Dim s As Type1 = New Type1() If (True) GoTo label1 End If For Each i In s GoTo label1 label1: Continue For Next Return 1 End Function End Class Class Type1 Public x As Short End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC30757: 'GoTo label1' is not valid because 'label1' is inside a 'For' or 'For Each' statement that does not contain this statement. GoTo label1 ~~~~~~ BC32023: Expression is of type 'Type1', which is not a collection type. For Each i In s ~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <WorkItem(540627, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540627")> <Fact()> Public Sub BC30758ERR_BadAttributeNonPublicConstructor() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BadAttributeNonPublicConstructor"> <file name="at30758.vb"><![CDATA[ Imports System <AttributeUsage(AttributeTargets.All)> Public MustInherit Class MyAttribute Inherits Attribute Friend Sub New() End Sub End Class <My()> Class Foo End Class ]]></file> </compilation>).VerifyDiagnostics( Diagnostic(ERRID.ERR_AttributeCannotBeAbstract, "My").WithArguments("MyAttribute"), Diagnostic(ERRID.ERR_BadAttributeNonPublicConstructor, "My")) End Sub <Fact()> Public Sub BC30782ERR_ContinueDoNotWithinDo() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ContinueDoNotWithinDo"> <file name="a.vb"> Class C1 Sub Main() While True Continue Do End While End Sub End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC30782: 'Continue Do' can only appear inside a 'Do' statement. Continue Do ~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC30783ERR_ContinueForNotWithinFor() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ContinueForNotWithinFor"> <file name="a.vb"> Class C1 Sub Main() Continue for End Sub End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC30783: 'Continue For' can only appear inside a 'For' statement. Continue for ~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC30784ERR_ContinueWhileNotWithinWhile() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ContinueWhileNotWithinWhile"> <file name="a.vb"> Class C1 Sub Main() Continue while End Sub End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC30784: 'Continue While' can only appear inside a 'While' statement. Continue while ~~~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC30793ERR_TryCastOfUnconstrainedTypeParam1() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="TryCastOfUnconstrainedTypeParam1"> <file name="a.vb"> Module M1 Sub Foo(Of T) (ByVal x As T) Dim o As Object = TryCast(x, T) End Sub End Module </file> </compilation>) Dim expectedErrors1 = <errors> BC30793: 'TryCast' operands must be class-constrained type parameter, but 'T' has no class constraint. Dim o As Object = TryCast(x, T) ~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC30794ERR_AmbiguousDelegateBinding2() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="AmbiguousDelegateBinding2"> <file name="a.vb"> Module Module1 Public Delegate Sub Bar(ByVal x As Integer, ByVal y As Integer) Public Sub Foo(Of T, R)(ByVal x As T, ByVal y As R) End Sub Public Sub Foo(Of T)(ByVal x As T, ByVal y As T) End Sub End Module Class C1 Sub FOO() Dim x1 As Module1.Bar = AddressOf Module1.Foo End Sub End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC30794: No accessible 'Foo' is most specific: Public Sub Foo(Of Integer, Integer)(x As Integer, y As Integer) Public Sub Foo(Of Integer)(x As Integer, y As Integer) Dim x1 As Module1.Bar = AddressOf Module1.Foo ~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact> Public Sub BC30917ERR_NoNonObsoleteConstructorOnBase3() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="NoNonObsoleteConstructorOnBase3"> <file name="a.vb"> Imports System Class C1 &lt;Obsolete(Nothing, True)&gt; Sub New() End Sub End Class Class C2 Inherits C1 End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC30917: Class 'C2' must declare a 'Sub New' because the 'Public Sub New()' in its base class 'C1' is marked obsolete. Class C2 ~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact> Public Sub BC30918ERR_NoNonObsoleteConstructorOnBase4() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="NoNonObsoleteConstructorOnBase4"> <file name="a.vb"> Imports System Class C1 &lt;Obsolete("hello", True)&gt; Sub New() End Sub End Class Class C2 Inherits C1 End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC30918: Class 'C2' must declare a 'Sub New' because the 'Public Sub New()' in its base class 'C1' is marked obsolete: 'hello'. Class C2 ~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact> Public Sub BC30919ERR_RequiredNonObsoleteNewCall3() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="RequiredNonObsoleteNewCall3"> <file name="a.vb"> Imports System Class C1 &lt;Obsolete(Nothing, True)&gt; Sub New() End Sub End Class Class C2 Inherits C1 Sub New() End Sub End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC30919: First statement of this 'Sub New' must be an explicit call to 'MyBase.New' or 'MyClass.New' because the 'Public Sub New()' in the base class 'C1' of 'C2' is marked obsolete. Sub New() ~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact> Public Sub BC30920ERR_RequiredNonObsoleteNewCall4() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="RequiredNonObsoleteNewCall4"> <file name="a.vb"> Imports System Class C1 &lt;Obsolete("hello", True)&gt; Sub New() End Sub End Class Class C2 Inherits C1 Sub New() End Sub End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC30920: First statement of this 'Sub New' must be an explicit call to 'MyBase.New' or 'MyClass.New' because the 'Public Sub New()' in the base class 'C1' of 'C2' is marked obsolete: 'hello'. Sub New() ~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <WorkItem(531309, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531309")> <Fact()> Public Sub BC30933ERR_LateBoundOverloadInterfaceCall1() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="LateBoundOverloadInterfaceCall1"> <file name="a.vb"> Module m1 Interface i1 Sub s1(ByVal p1 As Integer) Sub s1(ByVal p1 As Double) End Interface Class c1 Implements i1 Public Overloads Sub s1(ByVal p1 As Integer) Implements i1.s1 End Sub Public Overloads Sub s2(ByVal p1 As Double) Implements i1.s1 End Sub End Class Sub Main() Dim refer As i1 = New c1 Dim o1 As Object = 3.1415 refer.s1(o1) End Sub End Module Module m2 Interface i1 Property s1(ByVal p1 As Integer) Property s1(ByVal p1 As Double) End Interface Class c1 Implements i1 Public Property s1(p1 As Double) As Object Implements i1.s1 Get Return Nothing End Get Set(value As Object) End Set End Property Public Property s1(p1 As Integer) As Object Implements i1.s1 Get Return Nothing End Get Set(value As Object) End Set End Property End Class Sub Main() Dim refer As i1 = New c1 Dim o1 As Object = 3.1415 refer.s1(o1) = 1 End Sub End Module </file> </compilation>) Dim expectedErrors1 = <errors> BC30933: Late bound overload resolution cannot be applied to 's1' because the accessing instance is an interface type. refer.s1(o1) ~~ BC30933: Late bound overload resolution cannot be applied to 's1' because the accessing instance is an interface type. refer.s1(o1) = 1 ~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC30934ERR_RequiredAttributeConstConversion2() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="a.vb"><![CDATA[ Imports System <A(<a/>)> Class A Inherits Attribute Public Sub New(o As Object) End Sub End Class ]]></file> </compilation>, references:=XmlReferences) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_RequiredAttributeConstConversion2, "<a/>").WithArguments("System.Xml.Linq.XElement", "Object")) End Sub <Fact()> Public Sub BC30939ERR_AddressOfNotCreatableDelegate1() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="AddressOfNotCreatableDelegate1"> <file name="a.vb"> Imports System Module M1 Sub foo() Dim x As [Delegate] = AddressOf main End Sub Sub main() End Sub End Module </file> </compilation>) Dim expectedErrors1 = <errors> BC30939: 'AddressOf' expression cannot be converted to '[Delegate]' because type '[Delegate]' is declared 'MustInherit' and cannot be created. Dim x As [Delegate] = AddressOf main ~~~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact(), WorkItem(529157, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529157")> Public Sub BC30940ERR_ReturnFromEventMethod() 'diag behavior change by design- not worth investing in. Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="ReturnFromEventMethod"> <file name="a.vb"> Class C1 Delegate Sub EH() Custom Event e1 As EH AddHandler(ByVal value As EH) Return value End AddHandler RemoveHandler(ByVal value As EH) Return value End RemoveHandler RaiseEvent() Return value End RaiseEvent End Event End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC30647: 'Return' statement in a Sub or a Set cannot return a value. Return value ~~~~~~~~~~~~ BC30647: 'Return' statement in a Sub or a Set cannot return a value. Return value ~~~~~~~~~~~~ BC30647: 'Return' statement in a Sub or a Set cannot return a value. Return value ~~~~~~~~~~~~ BC30451: 'value' is not declared. It may be inaccessible due to its protection level. Return value ~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <WorkItem(542270, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542270")> <Fact()> Public Sub BC30949ERR_ArrayInitializerForNonConstDim() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ArrayInitializerForNonConstDim"> <file name="a.vb"> Option Strict On Module M Sub Main() Dim x as integer = 1 Dim y as Object = New Integer(x) {1, 2} End Sub End Module </file> </compilation>) Dim expectedErrors1 = <errors> BC30949: Array initializer cannot be specified for a non constant dimension; use the empty initializer '{}'. Dim y as Object = New Integer(x) {1, 2} ~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <WorkItem(542270, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542270")> <Fact()> Public Sub BC30949ERR_ArrayInitializerForNonConstDim_1() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="ArrayInitializerForNonConstDim"> <file name="a.vb"> Option Strict On Imports System Class M1 Public Shared Sub Main() Dim myLength As Integer = 2 Dim arr As Integer(,) = New Integer(myLength - 1, 1) {{1, 2}, {3, 4}, {5, 6}} End Sub Private Class A Private x As Integer = 1 Private arr As Integer(,) = New Integer(x, 1) {{1, 2}, {3, 4}, {5, 6}} End Class End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC30949: Array initializer cannot be specified for a non constant dimension; use the empty initializer '{}'. Dim arr As Integer(,) = New Integer(myLength - 1, 1) {{1, 2}, {3, 4}, {5, 6}} ~~~~~~~~~~~~~~~~~~~~~~~~ BC30949: Array initializer cannot be specified for a non constant dimension; use the empty initializer '{}'. Private arr As Integer(,) = New Integer(x, 1) {{1, 2}, {3, 4}, {5, 6}} ~~~~~~~~~~~~~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC30950ERR_DelegateBindingFailure3() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="DelegateBindingFailure3"> <file name="a.vb"> Option Strict On Imports System Module M Dim f As Action(Of Object) = CType(AddressOf 1.ToString, Action(Of Object)) End Module </file> </compilation>) Dim expectedErrors1 = <errors> </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC30978ERR_IterationVariableShadowLocal1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="IterationVariableShadowLocal1"> <file name="a.vb"> Option Infer On Option Strict Off Imports System.Linq Module M Sub Bar() Dim x = From bar In "" End Sub Function Foo() Dim x = From foo In "" Return Nothing End Function End Module </file> </compilation>, {Net40.SystemCore}) Dim expectedErrors1 = <errors> BC30978: Range variable 'foo' hides a variable in an enclosing block or a range variable previously defined in the query expression. Dim x = From foo In "" ~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation, expectedErrors1) End Sub <Fact()> Public Sub BC30978ERR_IterationVariableShadowLocal1_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="IterationVariableShadowLocal1"> <file name="a.vb"> Option Infer Off Imports System Imports System.Linq Module Program Sub Main(args As String()) Dim arr As String() = New String() {"aaa", "bbb", "ccc"} Dim arr_int As Integer() = New Integer() {111, 222, 333} Dim x = 1 Dim s = If(True, (From x In arr Select x).ToList(), From y As Integer In arr_int Select y) End Sub End Module </file> </compilation>, {Net40.SystemCore}, options:=TestOptions.ReleaseExe) Dim expectedErrors1 = <errors> BC30978: Range variable 'x' hides a variable in an enclosing block or a range variable previously defined in the query expression. Dim s = If(True, (From x In arr Select x).ToList(), From y As Integer In arr_int Select y) ~ BC30978: Range variable 'x' hides a variable in an enclosing block or a range variable previously defined in the query expression. Dim s = If(True, (From x In arr Select x).ToList(), From y As Integer In arr_int Select y) ~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation, expectedErrors1) End Sub <Fact()> Public Sub BC30980ERR_CircularInference1() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="CircularInference2"> <file name="a.vb"> Module M Const x = 1 Sub Main() Dim x = Function() x End Sub End Module </file> </compilation>) ' Extra Warning in Roslyn compilation1.VerifyDiagnostics( Diagnostic(ERRID.ERR_CircularInference1, "x").WithArguments("x") ) End Sub <Fact()> Public Sub BC30980ERR_CircularInference1_2() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="CircularInference2"> <file name="a.vb"> Option Infer On Imports System Class C Shared Sub Main() Dim f As Func(Of Integer) = Function() For Each x In x + 1 Return x Next return 0 End Function End Sub End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC30980: Type of 'x' cannot be inferred from an expression containing 'x'. For Each x In x + 1 ~ BC42104: Variable 'x' is used before it has been assigned a value. A null reference exception could result at runtime. For Each x In x + 1 ~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC30980ERR_CircularInference2_2() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="CircularInference2_2"> <file name="a.vb"> Class C Shared Sub Main() For Each y In New Object() {New With {Key .y = y}} Next End Sub End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC30980: Type of 'y' cannot be inferred from an expression containing 'y'. For Each y In New Object() {New With {Key .y = y}} ~ BC42104: Variable 'y' is used before it has been assigned a value. A null reference exception could result at runtime. For Each y In New Object() {New With {Key .y = y}} ~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC30980ERR_CircularInference2_2a() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="CircularInference2_2a"> <file name="a.vb"> Class C Shared Sub Main() 'For Each y As Object In New Object() {y} For Each y As Object In New Object() {New With {Key .y = y}} Next End Sub End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC42104: Variable 'y' is used before it has been assigned a value. A null reference exception could result at runtime. For Each y As Object In New Object() {New With {Key .y = y}} ~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <WorkItem(542268, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542268")> <Fact()> Public Sub BC30980ERR_CircularInference2_3() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="CircularInference2_3"> <file name="a.vb"> Option Infer On Class C Shared Sub Main() Dim a = a.b End Sub End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC30980: Type of 'a' cannot be inferred from an expression containing 'a'. Dim a = a.b ~ BC42104: Variable 'a' is used before it has been assigned a value. A null reference exception could result at runtime. Dim a = a.b ~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <WorkItem(542268, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542268")> <Fact()> Public Sub BC30980ERR_CircularInference2_3a() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="CircularInference2_3a"> <file name="a.vb"> Option Infer Off Class C Shared Sub Main() Dim a = a.ToString() End Sub End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC42104: Variable 'a' is used before it has been assigned a value. A null reference exception could result at runtime. Dim a = a.ToString() ~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact(), WorkItem(542191, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542191")> Public Sub BC30982ERR_NoSuitableWidestType1() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="NoSuitableWidestType1"> <file name="a.vb"> Option Infer On Module M Sub Main() Dim stepVar = "1"c For i = 1 To 10 Step stepVar Next End Sub End Module </file> </compilation>) Dim expectedErrors1 = <errors> BC30982: Type of 'i' cannot be inferred because the loop bounds and the step clause do not convert to the same type. For i = 1 To 10 Step stepVar ~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact(), WorkItem(12261, "DevDiv_Projects/Roslyn")> Public Sub BC30983ERR_AmbiguousWidestType3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="AmbiguousWidestType3"> <file name="a.vb"> Module modErr30983 Sub Test() 'COMPILEERROR : BC30983, "i" For i = New first(1) To New second(2) Step New third(3) Next End Sub End Module Class base End Class Class first Inherits base Dim m_count As ULong Sub New(ByVal d As ULong) m_count = d End Sub Overloads Shared Widening Operator CType(ByVal d As first) As second Return New second(d.m_count) End Operator End Class Class second Inherits base Dim m_count As ULong Sub New(ByVal d As ULong) m_count = d End Sub Overloads Shared Widening Operator CType(ByVal d As second) As first Return New first(d.m_count) End Operator End Class Class third Inherits first Sub New(ByVal d As ULong) MyBase.New(d) End Sub Overloads Shared Widening Operator CType(ByVal d As third) As Integer Return 1 End Operator End Class </file> </compilation>) 'BC30983: Type of 'i' is ambiguous because the loop bounds and the step clause do not convert to the same type. 'For i = New first(1) To New second(2) Step New third(3) ' ~ compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_AmbiguousWidestType3, "i").WithArguments("i")) End Sub <Fact()> Public Sub BC30989ERR_DuplicateAggrMemberInit1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="DuplicateAggrMemberInit1"> <file name="a.vb"> Module M Sub Main() Dim cust = New Customer() With {.Name = "Bob", .Name = "Robert"} End Sub End Module Class Customer Property Name As String End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30989: Multiple initializations of 'Name'. Fields and properties can be initialized only once in an object initializer expression. Dim cust = New Customer() With {.Name = "Bob", .Name = "Robert"} ~~~~ </expected>) End Sub <Fact()> Public Sub BC30990ERR_NonFieldPropertyAggrMemberInit1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="NonFieldPropertyAggrMemberInit1"> <file name="a.vb"> Module M1 Class WithSubX Public Sub x() End Sub End Class Sub foo() Dim z As WithSubX = New WithSubX With {.x = 5} End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30990: Member 'x' cannot be initialized in an object initializer expression because it is not a field or property. Dim z As WithSubX = New WithSubX With {.x = 5} ~ </expected>) End Sub <Fact()> Public Sub BC30991ERR_SharedMemberAggrMemberInit1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="SharedMemberAggrMemberInit1"> <file name="a.vb"> Module M Sub Main() Dim cust As New Customer With {.totalCustomers = 21} End Sub End Module Public Class Customer Public Shared totalCustomers As Integer End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30991: Member 'totalCustomers' cannot be initialized in an object initializer expression because it is shared. Dim cust As New Customer With {.totalCustomers = 21} ~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30992ERR_ParameterizedPropertyInAggrInit1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ParameterizedPropertyInAggrInit1"> <file name="a.vb"> Module M Sub Main() Dim strs As New C1() With {.defaultProp = "One"} End Sub End Module Public Class C1 Private myStrings() As String Default Property defaultProp(ByVal index As Integer) As String Get Return myStrings(index) End Get Set(ByVal Value As String) myStrings(index) = Value End Set End Property End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30992: Property 'defaultProp' cannot be initialized in an object initializer expression because it requires arguments. Dim strs As New C1() With {.defaultProp = "One"} ~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC30993ERR_NoZeroCountArgumentInitCandidates1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="NoZeroCountArgumentInitCandidates1"> <file name="a.vb"> Module M Sub Main() Dim aCoinObject = nothing Dim coinCollection As New C1 With {.Item = aCoinObject} End Sub End Module Class C1 WriteOnly Property Item(ByVal Key As String) As Object Set(ByVal value As Object) End Set End Property WriteOnly Property Item(ByVal Index As Integer) As Object Set(ByVal value As Object) End Set End Property private WriteOnly Property Item(ByVal Index As Long) As Object Set(ByVal value As Object) End Set End Property End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30993: Property 'Item' cannot be initialized in an object initializer expression because all accessible overloads require arguments. Dim coinCollection As New C1 With {.Item = aCoinObject} ~~~~ </expected>) End Sub <Fact()> Public Sub BC30994ERR_AggrInitInvalidForObject() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="AggrInitInvalidForObject"> <file name="a.vb"> Module M Sub Main() Dim obj = New Object With {.ToString = "hello"} End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30994: Object initializer syntax cannot be used to initialize an instance of 'System.Object'. Dim obj = New Object With {.ToString = "hello"} ~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC31080ERR_ReferenceComparison3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="ReferenceComparison3"> <file name="a.vb"> Interface I1 Interface I2 End Interface End Interface Class C1 Sub FOO() Dim scenario1 As I1.I2 If scenario1 = Nothing Then End If End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42104: Variable 'scenario1' is used before it has been assigned a value. A null reference exception could result at runtime. If scenario1 = Nothing Then ~~~~~~~~~ BC31080: Operator '=' is not defined for types 'I1.I2' and 'I1.I2'. Use 'Is' operator to compare two reference types. If scenario1 = Nothing Then ~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC31082ERR_CatchVariableNotLocal1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="CatchVariableNotLocal1"> <file name="a.vb"> Imports System Module M Dim ex As Exception Sub Main() Try Catch ex End Try End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC31082: 'ex' is not a local variable or parameter, and so cannot be used as a 'Catch' variable. Catch ex ~~ </expected>) End Sub <WorkItem(538613, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538613")> <Fact()> Public Sub BC30251_ModuleConstructorCall() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module M Sub [New]() M.New() End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30251: Type 'M' has no constructors. M.New() ~~~~~ </expected>) End Sub <WorkItem(538613, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538613")> <Fact()> Public Sub BC30251_ModuleGenericConstructorCall() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module M Sub [New](Of T)() M.New(Of Integer) End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30251: Type 'M' has no constructors. M.New(Of Integer) ~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact(), WorkItem(570936, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/570936")> Public Sub BC31092ERR_ParamArrayWrongType() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ParamArrayWrongType"> <file name="a.vb"> Module M1 Sub Foo() Dim x As New C1 Dim sResult As String = x.Foo(1, 2, 3, 4) End Sub End Module Class C1 Function Foo(&lt;System.[ParamArray]()&gt; ByVal x As Integer) As String Return "He" End Function End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC31092: ParamArray parameters must have an array type. Dim sResult As String = x.Foo(1, 2, 3, 4) ~~~ </expected>) End Sub <Fact(), WorkItem(570936, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/570936")> Public Sub BC31092ERR_ParamArrayWrongType_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ParamArrayWrongType"> <file name="a.vb"> Module M1 Sub Foo() Dim x As New C1 Dim sResult As String = x.Foo(1) End Sub End Module Class C1 Function Foo(&lt;System.[ParamArray]()&gt; ByVal x As Integer) As String Return "He" End Function End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC31092: ParamArray parameters must have an array type. Dim sResult As String = x.Foo(1) ~~~ </expected>) End Sub <Fact()> Public Sub BC31095ERR_InvalidMyClassReference() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BC31095ERR_InvalidMyClassReference"> <file name="a.vb"> Class cls0 Public s2 As String End Class Class Cls1 Inherits cls0 Sub New(ByVal x As Short) End Sub Sub New() 'COMPILEERROR: BC31095, "MyClass" MyClass.New(MyClass.s2) End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC31095: Reference to object under construction is not valid when calling another constructor. MyClass.New(MyClass.s2) ~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC31095ERR_InvalidMyBaseReference() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BC31095ERR_InvalidMyBaseReference"> <file name="a.vb"> Class cls0 Public s2 As String End Class Class Cls1 Inherits cls0 Sub New(ByVal x As Short) End Sub Sub New() 'COMPILEERROR: BC31095, "MyBase" MyClass.New(MyBase.s2) End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC31095: Reference to object under construction is not valid when calling another constructor. MyClass.New(MyBase.s2) ~~~~~~ </expected>) End Sub <WorkItem(541798, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541798")> <Fact()> Public Sub BC31095ERR_InvalidMeReference() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="InvalidMeReference"> <file name="a.vb"> Class cls0 Public s2 As String End Class Class Cls1 Inherits cls0 Sub New(ByVal x As String) End Sub Sub New(ByVal x As Short) Me.New(Me.s2) 'COMPILEERROR: BC31095, "Me" End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC31095: Reference to object under construction is not valid when calling another constructor. Me.New(Me.s2) 'COMPILEERROR: BC31095, "Me" ~~ </expected>) End Sub <WorkItem(541799, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541799")> <Fact()> Public Sub BC31096ERR_InvalidImplicitMeReference() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="InvalidImplicitMeReference"> <file name="a.vb"> Imports System Module M1 Class clsTest1 Private strTest As String = "Hello" Sub New() 'COMPILEERROR: BC31096, "strTest" Me.New(strTest) End Sub Sub New(ByVal ArgX As String) End Sub End Class End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC31096: Implicit reference to object under construction is not valid when calling another constructor. Me.New(strTest) ~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC31096ERR_InvalidImplicitMeReference_MyClass() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="BC31096ERR_InvalidImplicitMeReference_MyClass"> <file name="a.vb"> Imports System Module M1 Class clsTest1 Private strTest As String = "Hello" Sub New() 'COMPILEERROR: BC31096, "strTest" MyClass.New(strTest) End Sub Sub New(ByVal ArgX As String) End Sub End Class End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC31096: Implicit reference to object under construction is not valid when calling another constructor. MyClass.New(strTest) ~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC31096ERR_InvalidImplicitMeReference_MyBase() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="BC31096ERR_InvalidImplicitMeReference_MyBase"> <file name="a.vb"> Imports System Module M1 Class clsTest0 Public Sub New(ByVal strTest As String) End Sub End Class Class clsTest1 Inherits clsTest0 Private strTest As String = "Hello" Sub New() 'COMPILEERROR: BC31096, "strTest" MyBase.New(strTest) End Sub End Class End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC31096: Implicit reference to object under construction is not valid when calling another constructor. MyBase.New(strTest) ~~~~~~~ </expected>) End Sub ' Different error <Fact()> Public Sub BC31109ERR_InAccessibleCoClass3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="C"> <file name="a.vb"> Imports System.Runtime.InteropServices &lt;Assembly: ImportedFromTypeLib("NoPIANew1-PIA2.dll")&gt; &lt;Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")&gt; Public Class Class1 &lt;Guid("bd60d4b3-f50b-478b-8ef2-e777df99d810")&gt; _ &lt;ComImport()&gt; _ &lt;InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)&gt; _ &lt;CoClass(GetType(FooImpl))&gt; _ Public Interface IFoo End Interface &lt;Guid("c9dcf748-b634-4504-a7ce-348cf7c61891")&gt; _ Friend Class FooImpl End Class End Class </file> </compilation>) Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="InAccessibleCoClass3"> <file name="a.vb"> Public Module Module1 Public Sub Main() Dim i1 As New Class1.IFoo(1) Dim i2 = New Class1.IFoo(Nothing) End Sub End Module </file> </compilation>) Dim compRef = New VisualBasicCompilationReference(compilation) compilation1 = compilation1.AddReferences(compRef) compilation1.VerifyDiagnostics(Diagnostic(ERRID.ERR_InAccessibleCoClass3, "New Class1.IFoo(1)").WithArguments("Class1.FooImpl", "Class1.IFoo", "Friend"), Diagnostic(ERRID.ERR_InAccessibleCoClass3, "New Class1.IFoo(Nothing)").WithArguments("Class1.FooImpl", "Class1.IFoo", "Friend")) End Sub <WorkItem(6977, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub BC31110ERR_MissingValuesForArraysInApplAttrs() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="MissingValuesForArraysInApplAttrs"> <file name="a.vb"><![CDATA[ Imports System <AttributeUsage(AttributeTargets.All)> Public Class MyAttribute Inherits Attribute Public Sub New(ByVal o As Object) End Sub End Class Namespace AttributeRegress003 Friend Module AttributeRegress003mod 'COMPILEERROR: BC31110, "{}" <My(New Integer(3) {})> Class Test End Class End Module End Namespace ]]></file> </compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_MissingValuesForArraysInApplAttrs, "{}")) End Sub <Fact()> Public Sub BC31102ERR_NoAccessibleSet() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="NoAccessibleSet"> <file name="a.vb"> Class A Shared Property P Get Return Nothing End Get Private Set End Set End Property Property Q Get Return Nothing End Get Private Set End Set End Property End Class Class B Sub M(ByVal x As A) A.P = Nothing x.Q = Nothing End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC31102: 'Set' accessor of property 'P' is not accessible. A.P = Nothing ~~~~~~~~~~~~~ BC31102: 'Set' accessor of property 'Q' is not accessible. x.Q = Nothing ~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC31103ERR_NoAccessibleGet() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="NoAccessibleGet"> <file name="a.vb"> Class A Shared Property P Private Get Return Nothing End Get Set End Set End Property Property Q Private Get Return Nothing End Get Set End Set End Property End Class Class B Sub M(ByVal x As A) N(A.P) N(x.Q) End Sub Sub N(ByVal o As Object) End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC31103: 'Get' accessor of property 'P' is not accessible. N(A.P) ~~~ BC31103: 'Get' accessor of property 'Q' is not accessible. N(x.Q) ~~~ </expected>) End Sub <Fact()> Public Sub BC31143ERR_DelegateBindingIncompatible2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="DelegateBindingIncompatible2"> <file name="a.vb"> Public Class C1 Delegate Function FunDel(ByVal i As Integer, ByVal d As Double) As Integer Function ExampleMethod1(ByVal m As Integer, ByVal aDate As Date) As Integer Return 1 End Function Sub Main() Dim d1 As FunDel = AddressOf ExampleMethod1 End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC31143: Method 'Public Function ExampleMethod1(m As Integer, aDate As Date) As Integer' does not have a signature compatible with delegate 'Delegate Function C1.FunDel(i As Integer, d As Double) As Integer'. Dim d1 As FunDel = AddressOf ExampleMethod1 ~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC31148ERR_UndefinedXmlPrefix() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Imports <xmlns:p0="http://roslyn/"> Module M Private F1 = GetXmlNamespace(p1) Private F2 = <%= GetXmlNamespace(p0) %> Private F3 = <%= GetXmlNamespace(p3) %> Private F4 = <p4:x xmlns:p4="http://roslyn/"><%= GetXmlNamespace(p4) %></p4:x> End Module ]]></file> </compilation>, references:=XmlReferences) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC31148: XML namespace prefix 'p1' is not defined. Private F1 = GetXmlNamespace(p1) ~~ BC31172: An embedded expression cannot be used here. Private F2 = <%= GetXmlNamespace(p0) %> ~~~~~~~~~~~~~~~~~~~~~~~~~~ BC31172: An embedded expression cannot be used here. Private F3 = <%= GetXmlNamespace(p3) %> ~~~~~~~~~~~~~~~~~~~~~~~~~~ BC31148: XML namespace prefix 'p3' is not defined. Private F3 = <%= GetXmlNamespace(p3) %> ~~ BC31148: XML namespace prefix 'p4' is not defined. Private F4 = <p4:x xmlns:p4="http://roslyn/"><%= GetXmlNamespace(p4) %></p4:x> ~~ ]]></errors>) End Sub <Fact()> Public Sub BC31148ERR_UndefinedXmlPrefix_1() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Imports System.Xml.Linq Class C Private F1 As XElement = <p1:a q1:b="c" xmlns:p1="..." xmlns:q1="..."/> Private F2 As XElement = <p2:a q2:b="c"><b xmlns:p2="..." xmlns:q2="..."/></p2:a> Private F3 As String = <p3:a q3:b="c" xmlns:p3="..." xmlns:q3="..."/>.<p3:a>.@q3:b End Class ]]></file> </compilation>, references:=XmlReferences) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC31148: XML namespace prefix 'p2' is not defined. Private F2 As XElement = <p2:a q2:b="c"><b xmlns:p2="..." xmlns:q2="..."/></p2:a> ~~ BC31148: XML namespace prefix 'q2' is not defined. Private F2 As XElement = <p2:a q2:b="c"><b xmlns:p2="..." xmlns:q2="..."/></p2:a> ~~ BC31148: XML namespace prefix 'p3' is not defined. Private F3 As String = <p3:a q3:b="c" xmlns:p3="..." xmlns:q3="..."/>.<p3:a>.@q3:b ~~ BC31148: XML namespace prefix 'q3' is not defined. Private F3 As String = <p3:a q3:b="c" xmlns:p3="..." xmlns:q3="..."/>.<p3:a>.@q3:b ~~ ]]></errors>) End Sub <Fact()> Public Sub BC31148ERR_UndefinedXmlPrefix_2() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Imports <xmlns:p0="..."> Module M Private F = <x1 xmlns:p1="..."> <x2 xmlns:p2="..." p0:a0="..." p1:a1="..." p2:a2="..." p6:a6="..." p7:a7="..." p8:a8="..."> <%= <x3> <x4 p0:a0="..." p1:a1="..." p2:a2="..." p6:a6="..." p7:a7="..." p8:a8="..."> <%= <x5> <x6 xmlns:p6="..." p0:a0="..." p1:a1="..." p2:a2="..." p6:a6="..." p7:a7="..." p8:a8="..."> <%= <x7 xmlns:p7="..."> <x8 xmlns:p8="..."> <x9 p0:a0="..." p1:a1="..." p2:a2="..." p6:a6="..." p7:a7="..." p8:a8="..."/> </x8> </x7> %> </x6> </x5> %> </x4> </x3> %> </x2> </x1> End Module ]]></file> </compilation>, references:=XmlReferences) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC31148: XML namespace prefix 'p6' is not defined. <x2 xmlns:p2="..." p0:a0="..." p1:a1="..." p2:a2="..." p6:a6="..." p7:a7="..." p8:a8="..."> ~~ BC31148: XML namespace prefix 'p7' is not defined. <x2 xmlns:p2="..." p0:a0="..." p1:a1="..." p2:a2="..." p6:a6="..." p7:a7="..." p8:a8="..."> ~~ BC31148: XML namespace prefix 'p8' is not defined. <x2 xmlns:p2="..." p0:a0="..." p1:a1="..." p2:a2="..." p6:a6="..." p7:a7="..." p8:a8="..."> ~~ BC31148: XML namespace prefix 'p1' is not defined. <x4 p0:a0="..." p1:a1="..." p2:a2="..." p6:a6="..." p7:a7="..." p8:a8="..."> ~~ BC31148: XML namespace prefix 'p2' is not defined. <x4 p0:a0="..." p1:a1="..." p2:a2="..." p6:a6="..." p7:a7="..." p8:a8="..."> ~~ BC31148: XML namespace prefix 'p6' is not defined. <x4 p0:a0="..." p1:a1="..." p2:a2="..." p6:a6="..." p7:a7="..." p8:a8="..."> ~~ BC31148: XML namespace prefix 'p7' is not defined. <x4 p0:a0="..." p1:a1="..." p2:a2="..." p6:a6="..." p7:a7="..." p8:a8="..."> ~~ BC31148: XML namespace prefix 'p8' is not defined. <x4 p0:a0="..." p1:a1="..." p2:a2="..." p6:a6="..." p7:a7="..." p8:a8="..."> ~~ BC31148: XML namespace prefix 'p1' is not defined. <x6 xmlns:p6="..." p0:a0="..." p1:a1="..." p2:a2="..." p6:a6="..." p7:a7="..." p8:a8="..."> ~~ BC31148: XML namespace prefix 'p2' is not defined. <x6 xmlns:p6="..." p0:a0="..." p1:a1="..." p2:a2="..." p6:a6="..." p7:a7="..." p8:a8="..."> ~~ BC31148: XML namespace prefix 'p7' is not defined. <x6 xmlns:p6="..." p0:a0="..." p1:a1="..." p2:a2="..." p6:a6="..." p7:a7="..." p8:a8="..."> ~~ BC31148: XML namespace prefix 'p8' is not defined. <x6 xmlns:p6="..." p0:a0="..." p1:a1="..." p2:a2="..." p6:a6="..." p7:a7="..." p8:a8="..."> ~~ BC31148: XML namespace prefix 'p1' is not defined. <x9 p0:a0="..." p1:a1="..." p2:a2="..." p6:a6="..." p7:a7="..." p8:a8="..."/> ~~ BC31148: XML namespace prefix 'p2' is not defined. <x9 p0:a0="..." p1:a1="..." p2:a2="..." p6:a6="..." p7:a7="..." p8:a8="..."/> ~~ BC31148: XML namespace prefix 'p6' is not defined. <x9 p0:a0="..." p1:a1="..." p2:a2="..." p6:a6="..." p7:a7="..." p8:a8="..."/> ~~ ]]></errors>) End Sub <WorkItem(531633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531633")> <Fact()> Public Sub BC31148ERR_UndefinedXmlPrefix_3() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Module M Sub Main() Dim x As Object x = <x/>.@Return:a End Sub End Module ]]></file> </compilation>, references:=XmlReferences) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC31148: XML namespace prefix 'Return' is not defined. x = <x/>.@Return:a ~~~~~~ ]]></errors>) End Sub <Fact()> Public Sub BC31149ERR_DuplicateXmlAttribute() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Module M Private F1 = <x a="b" a="c" A="d" A="e"/> Private F2 = <x a="b" a="c" a="d" xmlns="http://roslyn"/> Private F3 = <x p:a="b" p:a="c" xmlns:p="http://roslyn"/> Private F4 = <x xmlns:a="b" xmlns:a="c"/> Private F5 = <x p:a="b" q:a="c" xmlns:p="http://roslyn" xmlns:q="http://roslyn"/> Private F6 = <x p:a="b" P:a="c" xmlns:p="http://roslyn/p" xmlns:P="http://roslyn/P"/> Private F7 = <x a="b" <%= "a" %>="c" <%= "a" %>="d"/> End Module ]]></file> </compilation>, references:=XmlReferences) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC31149: Duplicate XML attribute 'a'. Private F1 = <x a="b" a="c" A="d" A="e"/> ~ BC31149: Duplicate XML attribute 'A'. Private F1 = <x a="b" a="c" A="d" A="e"/> ~ BC31149: Duplicate XML attribute 'a'. Private F2 = <x a="b" a="c" a="d" xmlns="http://roslyn"/> ~ BC31149: Duplicate XML attribute 'a'. Private F2 = <x a="b" a="c" a="d" xmlns="http://roslyn"/> ~ BC31149: Duplicate XML attribute 'p:a'. Private F3 = <x p:a="b" p:a="c" xmlns:p="http://roslyn"/> ~~~ BC31149: Duplicate XML attribute 'xmlns:a'. Private F4 = <x xmlns:a="b" xmlns:a="c"/> ~~~~~~~ BC31149: Duplicate XML attribute 'q:a'. Private F5 = <x p:a="b" q:a="c" xmlns:p="http://roslyn" xmlns:q="http://roslyn"/> ~~~ ]]></errors>) End Sub <Fact()> Public Sub BC31149ERR_DuplicateXmlAttribute_1() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports <xmlns="http://roslyn/"> Imports <xmlns:p="http://roslyn/"> Imports <xmlns:q=""> Class C Private Shared F1 As Object = <x a="b" a="c"/> Private Shared F2 As Object = <x p:a="b" a="c"/> Private Shared F3 As Object = <x q:a="b" a="c"/> End Class ]]></file> </compilation>, references:=XmlReferences) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC31149: Duplicate XML attribute 'a'. Private Shared F1 As Object = <x a="b" a="c"/> ~ BC31149: Duplicate XML attribute 'a'. Private Shared F3 As Object = <x q:a="b" a="c"/> ~ ]]></errors>) End Sub ' Should report duplicate xmlns attributes, even for xmlns ' attributes that match Imports since those have special handling. <Fact()> Public Sub BC31149ERR_DuplicateXmlAttribute_2() Dim options = TestOptions.ReleaseDll.WithGlobalImports(GlobalImport.Parse({"<xmlns:p=""http://roslyn/p"">"})) Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports <xmlns:q="http://roslyn/q"> Module M Private F1 As Object = <x xmlns:p="http://roslyn/p" xmlns:p="http://roslyn/other"/> Private F2 As Object = <x xmlns:q="http://roslyn/other" xmlns:q="http://roslyn/q"/> End Module ]]></file> </compilation>, references:=XmlReferences, options:=options) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC31149: Duplicate XML attribute 'xmlns:p'. Private F1 As Object = <x xmlns:p="http://roslyn/p" xmlns:p="http://roslyn/other"/> ~~~~~~~ BC31149: Duplicate XML attribute 'xmlns:q'. Private F2 As Object = <x xmlns:q="http://roslyn/other" xmlns:q="http://roslyn/q"/> ~~~~~~~ ]]></errors>) End Sub <Fact()> Public Sub BC31152ERR_ReservedXmlPrefix() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Imports <xmlns="http://roslyn/"> Imports <xmlns:xml="http://roslyn/xml"> Imports <xmlns:xmlns="http://roslyn/xmlns"> Imports <xmlns:Xml="http://roslyn/xml"> Imports <xmlns:Xmlns="http://roslyn/xmlns"> Module M Private F1 As Object = <x xmlns="http://roslyn/" xmlns:xml="http://roslyn/xml" xmlns:xmlns="http://roslyn/xmlns"/> Private F2 As Object = <x xmlns:XML="http://roslyn/xml" xmlns:XMLNS="http://roslyn/xmlns"/> Private F3 As Object = <x xmlns="" xmlns:xml="" xmlns:xmlns=""/> End Module ]]></file> </compilation>, references:=XmlReferences) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC31152: XML namespace prefix 'xml' is reserved for use by XML and the namespace URI cannot be changed. Imports <xmlns:xml="http://roslyn/xml"> ~~~ BC31152: XML namespace prefix 'xmlns' is reserved for use by XML and the namespace URI cannot be changed. Imports <xmlns:xmlns="http://roslyn/xmlns"> ~~~~~ BC31152: XML namespace prefix 'xml' is reserved for use by XML and the namespace URI cannot be changed. xmlns:xml="http://roslyn/xml" ~~~ BC31152: XML namespace prefix 'xmlns' is reserved for use by XML and the namespace URI cannot be changed. xmlns:xmlns="http://roslyn/xmlns"/> ~~~~~ BC31152: XML namespace prefix 'xml' is reserved for use by XML and the namespace URI cannot be changed. xmlns:xml="" ~~~ BC31152: XML namespace prefix 'xmlns' is reserved for use by XML and the namespace URI cannot be changed. xmlns:xmlns=""/> ~~~~~ ]]></errors>) End Sub <Fact()> Public Sub BC31152ERR_ReservedXmlPrefix_1() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Imports <xmlns:xml="http://www.w3.org/XML/1998/namespace"> Imports <xmlns:xmlns="http://www.w3.org/XML/1998/namespace"> Module M Private F1 As Object = <x xmlns:xml="http://www.w3.org/2000/xmlns/" xmlns:xmlns="http://www.w3.org/2000/xmlns/"/> Private F2 As Object = <x xmlns:xml="http://www.w3.org/XML/1998/NAMESPACE"/> End Module ]]></file> </compilation>, references:=XmlReferences) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC31152: XML namespace prefix 'xmlns' is reserved for use by XML and the namespace URI cannot be changed. Imports <xmlns:xmlns="http://www.w3.org/XML/1998/namespace"> ~~~~~ BC31152: XML namespace prefix 'xml' is reserved for use by XML and the namespace URI cannot be changed. xmlns:xml="http://www.w3.org/2000/xmlns/" ~~~ BC31152: XML namespace prefix 'xmlns' is reserved for use by XML and the namespace URI cannot be changed. xmlns:xmlns="http://www.w3.org/2000/xmlns/"/> ~~~~~ BC31152: XML namespace prefix 'xml' is reserved for use by XML and the namespace URI cannot be changed. xmlns:xml="http://www.w3.org/XML/1998/NAMESPACE"/> ~~~ ]]></errors>) End Sub <Fact()> Public Sub BC31168ERR_NoXmlAxesLateBinding() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="a.vb"><![CDATA[ Module M1 Sub M() Dim a = Nothing Dim b As Object = Nothing Dim c As Object c = a.<x> c = b.@a End Sub End Module ]]></file> <file name="b.vb"><![CDATA[ Option Strict On Module M2 Sub M() Dim a As Object = Nothing Dim b = Nothing Dim c As Object c = a...<x> c = b.@<a> End Sub End Module ]]></file> </compilation>, references:=XmlReferences) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC31168: XML axis properties do not support late binding. c = a.<x> ~~~~~ BC31168: XML axis properties do not support late binding. c = b.@a ~~~~ BC31168: XML axis properties do not support late binding. c = a...<x> ~~~~~~~ BC31168: XML axis properties do not support late binding. c = b.@<a> ~~~~~~ ]]></errors>) End Sub <Fact()> Public Sub BC31172ERR_EmbeddedExpression() Dim options = TestOptions.ReleaseDll.WithGlobalImports(GlobalImport.Parse({"<xmlns:p=<%= M1.F %>>"})) Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Imports <xmlns:q=<%= M1.F %>> Module M1 Private F = "..." End Module Module M2 Public F = <x xmlns=<%= M1.F %>/> End Module ]]></file> </compilation>, references:=XmlReferences, options:=options) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC31172: Error in project-level import '<xmlns:p=<%= M1.F %>>' at '<%= M1.F %>' : An embedded expression cannot be used here. BC31172: An embedded expression cannot be used here. Imports <xmlns:q=<%= M1.F %>> ~~~~~~~~~~~ BC31172: An embedded expression cannot be used here. Public F = <x xmlns=<%= M1.F %>/> ~~~~~~~~~~~ BC30389: 'M1.F' is not accessible in this context because it is 'Private'. Public F = <x xmlns=<%= M1.F %>/> ~~~~ ]]></errors>) End Sub <Fact()> Public Sub BC31183ERR_ReservedXmlNamespace() Dim options = TestOptions.ReleaseDll.WithGlobalImports(GlobalImport.Parse({"<xmlns=""http://www.w3.org/XML/1998/namespace"">", "<xmlns:p1=""http://www.w3.org/2000/xmlns/"">"})) Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Imports <xmlns="http://www.w3.org/XML/1998/namespace"> Imports <xmlns:p2="http://www.w3.org/2000/xmlns/"> Module M Private F1 As Object = <x xmlns="http://www.w3.org/2000/xmlns/" xmlns:p3="http://www.w3.org/XML/1998/namespace"/> Private F2 As Object = <x xmlns="http://www.w3.org/2000/XMLNS/" xmlns:p4="http://www.w3.org/XML/1998/NAMESPACE"/> End Module ]]></file> </compilation>, references:=XmlReferences, options:=options) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC31183: Error in project-level import '<xmlns:p1="http://www.w3.org/2000/xmlns/">' at '"http://www.w3.org/2000/xmlns/"' : Prefix 'p1' cannot be bound to namespace name reserved for 'xmlns'. BC31183: Error in project-level import '<xmlns="http://www.w3.org/XML/1998/namespace">' at '"http://www.w3.org/XML/1998/namespace"' : Prefix '' cannot be bound to namespace name reserved for 'xml'. BC31183: Prefix '' cannot be bound to namespace name reserved for 'xml'. Imports <xmlns="http://www.w3.org/XML/1998/namespace"> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC31183: Prefix 'p2' cannot be bound to namespace name reserved for 'xmlns'. Imports <xmlns:p2="http://www.w3.org/2000/xmlns/"> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC31183: Prefix '' cannot be bound to namespace name reserved for 'xmlns'. xmlns="http://www.w3.org/2000/xmlns/" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC31183: Prefix 'p3' cannot be bound to namespace name reserved for 'xml'. xmlns:p3="http://www.w3.org/XML/1998/namespace"/> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></errors>) End Sub <Fact()> Public Sub BC31184ERR_IllegalDefaultNamespace() Dim options = TestOptions.ReleaseDll.WithGlobalImports(GlobalImport.Parse({"<xmlns="""">", "<xmlns:p="""">"})) Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Imports <xmlns=""> Imports <xmlns:q=""> Module M Private F As Object = <x xmlns="" xmlns:r=""/> End Module ]]></file> </compilation>, references:=XmlReferences, options:=options) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC31184: Namespace declaration with prefix cannot have an empty value inside an XML literal. Private F As Object = <x xmlns="" xmlns:r=""/> ~ ]]></errors>) End Sub <Fact()> Public Sub BC31189ERR_IllegalXmlnsPrefix() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Imports <xmlns:p=""> Imports <xmlns:XMLNS=""> Module M Private F1 As Object = <xmlns/> Private F2 As Object = <xmlns:x/> Private F3 As Object = <p:xmlns/> Private F4 As Object = <XMLNS:x/> Private F5 As Object = <x/>.<xmlns> Private F6 As Object = <x/>.<xmlns:y> Private F7 As Object = <x/>.<p:xmlns> Private F8 As Object = <x/>.<XMLNS:y> Private F9 As Object = <x/>.@xmlns Private F10 As Object = <x/>.@xmlns:z End Module ]]></file> </compilation>, references:=XmlReferences) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC31189: Element names cannot use the 'xmlns' prefix. Private F2 As Object = <xmlns:x/> ~~~~~ BC31189: Element names cannot use the 'xmlns' prefix. Private F6 As Object = <x/>.<xmlns:y> ~~~~~ ]]></errors>) End Sub ' No ref to system.xml.dll <Fact()> Public Sub BC31190ERR_XmlFeaturesNotAvailable() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Module M1 Sub Foo() Dim x = Function() <aoeu> <%= 5 %> <%= (Function() "five")() %> </aoeu> Dim y = Function() <aoeu val=<%= (Function() <htns></htns>)().ToString() %>/> End Sub End Module ]]></file> </compilation>) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC31190: XML literals and XML axis properties are not available. Add references to System.Xml, System.Xml.Linq, and System.Core or other assemblies declaring System.Linq.Enumerable, System.Xml.Linq.XElement, System.Xml.Linq.XName, System.Xml.Linq.XAttribute and System.Xml.Linq.XNamespace types. Dim x = Function() <aoeu> ~~~~~~~ BC31190: XML literals and XML axis properties are not available. Add references to System.Xml, System.Xml.Linq, and System.Core or other assemblies declaring System.Linq.Enumerable, System.Xml.Linq.XElement, System.Xml.Linq.XName, System.Xml.Linq.XAttribute and System.Xml.Linq.XNamespace types. Dim y = Function() <aoeu val=<%= (Function() <htns></htns>)().ToString() %>/> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></errors>) End Sub <Fact()> Public Sub BC31190ERR_XmlFeaturesNotAvailable_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports <xmlns:p="..."> Module M Private A = <a><b><%= <c/> %></b></a> Private B = <a b=<%= <c/> %>/> Private C = <a/>.<b>.<c> Private D = <%= A %> Private E = <%= <x><%= A %></x> %> Private F = <a/>.<a>.<b> Private G = <a b="c"/>.<a>.@b Private H = <a/>...<b> Private J = <!-- comment --> Private K = <?xml version="1.0"?><x/> End Module ]]></file> </compilation>) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC31190: XML literals and XML axis properties are not available. Add references to System.Xml, System.Xml.Linq, and System.Core or other assemblies declaring System.Linq.Enumerable, System.Xml.Linq.XElement, System.Xml.Linq.XName, System.Xml.Linq.XAttribute and System.Xml.Linq.XNamespace types. Private A = <a><b><%= <c/> %></b></a> ~~~~~~~~~~~~~~~~~~~~~~~~~ BC31190: XML literals and XML axis properties are not available. Add references to System.Xml, System.Xml.Linq, and System.Core or other assemblies declaring System.Linq.Enumerable, System.Xml.Linq.XElement, System.Xml.Linq.XName, System.Xml.Linq.XAttribute and System.Xml.Linq.XNamespace types. Private B = <a b=<%= <c/> %>/> ~~~~~~~~~~~~~~~~~~ BC31190: XML literals and XML axis properties are not available. Add references to System.Xml, System.Xml.Linq, and System.Core or other assemblies declaring System.Linq.Enumerable, System.Xml.Linq.XElement, System.Xml.Linq.XName, System.Xml.Linq.XAttribute and System.Xml.Linq.XNamespace types. Private C = <a/>.<b>.<c> ~~~~~~~~~~~~ BC31172: An embedded expression cannot be used here. Private D = <%= A %> ~~~~~~~~ BC31172: An embedded expression cannot be used here. Private E = <%= <x><%= A %></x> %> ~~~~~~~~~~~~~~~~~~~~~~ BC31190: XML literals and XML axis properties are not available. Add references to System.Xml, System.Xml.Linq, and System.Core or other assemblies declaring System.Linq.Enumerable, System.Xml.Linq.XElement, System.Xml.Linq.XName, System.Xml.Linq.XAttribute and System.Xml.Linq.XNamespace types. Private E = <%= <x><%= A %></x> %> ~~~~~~~~~~~~~~~ BC31190: XML literals and XML axis properties are not available. Add references to System.Xml, System.Xml.Linq, and System.Core or other assemblies declaring System.Linq.Enumerable, System.Xml.Linq.XElement, System.Xml.Linq.XName, System.Xml.Linq.XAttribute and System.Xml.Linq.XNamespace types. Private F = <a/>.<a>.<b> ~~~~~~~~~~~~ BC31190: XML literals and XML axis properties are not available. Add references to System.Xml, System.Xml.Linq, and System.Core or other assemblies declaring System.Linq.Enumerable, System.Xml.Linq.XElement, System.Xml.Linq.XName, System.Xml.Linq.XAttribute and System.Xml.Linq.XNamespace types. Private G = <a b="c"/>.<a>.@b ~~~~~~~~~~~~~~~~~ BC31190: XML literals and XML axis properties are not available. Add references to System.Xml, System.Xml.Linq, and System.Core or other assemblies declaring System.Linq.Enumerable, System.Xml.Linq.XElement, System.Xml.Linq.XName, System.Xml.Linq.XAttribute and System.Xml.Linq.XNamespace types. Private H = <a/>...<b> ~~~~~~~~~~ BC31190: XML literals and XML axis properties are not available. Add references to System.Xml, System.Xml.Linq, and System.Core or other assemblies declaring System.Linq.Enumerable, System.Xml.Linq.XElement, System.Xml.Linq.XName, System.Xml.Linq.XAttribute and System.Xml.Linq.XNamespace types. Private J = <!-- comment --> ~~~~~~~~~~~~~~~~ BC31190: XML literals and XML axis properties are not available. Add references to System.Xml, System.Xml.Linq, and System.Core or other assemblies declaring System.Linq.Enumerable, System.Xml.Linq.XElement, System.Xml.Linq.XName, System.Xml.Linq.XAttribute and System.Xml.Linq.XNamespace types. Private K = <?xml version="1.0"?><x/> ~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></errors>) End Sub <Fact()> Public Sub BC31190ERR_XmlFeaturesNotAvailable_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module M Private F1 = &lt;x&gt;&lt;![CDATA[str]]&gt;&lt;/&gt; Private F2 = &lt;![CDATA[str]]&gt; End Module </file> </compilation>) compilation.AssertTheseDiagnostics(<errors> BC31190: XML literals and XML axis properties are not available. Add references to System.Xml, System.Xml.Linq, and System.Core or other assemblies declaring System.Linq.Enumerable, System.Xml.Linq.XElement, System.Xml.Linq.XName, System.Xml.Linq.XAttribute and System.Xml.Linq.XNamespace types. Private F1 = &lt;x&gt;&lt;![CDATA[str]]&gt;&lt;/&gt; ~~~~~~~~~~~~~~~~~~~~~ BC31190: XML literals and XML axis properties are not available. Add references to System.Xml, System.Xml.Linq, and System.Core or other assemblies declaring System.Linq.Enumerable, System.Xml.Linq.XElement, System.Xml.Linq.XName, System.Xml.Linq.XAttribute and System.Xml.Linq.XNamespace types. Private F2 = &lt;![CDATA[str]]&gt; ~~~~~~~~~~~~~~~ </errors>) End Sub <Fact()> Public Sub BC31190ERR_XmlFeaturesNotAvailable_3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Module M Private F = GetXmlNamespace() End Module ]]></file> </compilation>) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC31190: XML literals and XML axis properties are not available. Add references to System.Xml, System.Xml.Linq, and System.Core or other assemblies declaring System.Linq.Enumerable, System.Xml.Linq.XElement, System.Xml.Linq.XName, System.Xml.Linq.XAttribute and System.Xml.Linq.XNamespace types. Private F = GetXmlNamespace() ~~~~~~~~~~~~~~~~~ ]]></errors>) End Sub <Fact()> Public Sub BC42361WRN_UseValueForXmlExpression3() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="a.vb"><![CDATA[ Option Strict Off Imports System.Collections.Generic Imports System.Xml.Linq Class A End Class NotInheritable Class B End Class Module M Sub M(Of T As Class)() Dim _o As Object Dim _s As String Dim _a As A Dim _b As B Dim _t As T _o = <x/>.<y> _o = CType(<x/>.<y>, Object) _o = DirectCast(<x/>.<y>, Object) _o = TryCast(<x/>.<y>, Object) _s = <x/>.<y> _s = CType(<x/>.<y>, String) _s = DirectCast(<x/>.<y>, String) _s = TryCast(<x/>.<y>, String) _a = <x/>.<y> _a = CType(<x/>.<y>, A) _a = DirectCast(<x/>.<y>, A) _a = TryCast(<x/>.<y>, A) _b = <x/>.<y> _b = CType(<x/>.<y>, B) _b = DirectCast(<x/>.<y>, B) _b = TryCast(<x/>.<y>, B) _t = <x/>.<y> _t = CType(<x/>.<y>, T) _t = DirectCast(<x/>.<y>, T) _t = TryCast(<x/>.<y>, T) End Sub End Module ]]></file> </compilation>, references:=XmlReferences) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC42361: Cannot convert 'IEnumerable(Of XElement)' to 'String'. You can use the 'Value' property to get the string value of the first element of 'IEnumerable(Of XElement)'. _s = <x/>.<y> ~~~~~~~~ BC42361: Cannot convert 'IEnumerable(Of XElement)' to 'String'. You can use the 'Value' property to get the string value of the first element of 'IEnumerable(Of XElement)'. _s = CType(<x/>.<y>, String) ~~~~~~~~ BC42361: Cannot convert 'IEnumerable(Of XElement)' to 'String'. You can use the 'Value' property to get the string value of the first element of 'IEnumerable(Of XElement)'. _s = DirectCast(<x/>.<y>, String) ~~~~~~~~ BC42361: Cannot convert 'IEnumerable(Of XElement)' to 'String'. You can use the 'Value' property to get the string value of the first element of 'IEnumerable(Of XElement)'. _s = TryCast(<x/>.<y>, String) ~~~~~~~~ BC42322: Runtime errors might occur when converting 'IEnumerable(Of XElement)' to 'B'. _b = <x/>.<y> ~~~~~~~~ BC42322: Runtime errors might occur when converting 'IEnumerable(Of XElement)' to 'B'. _b = CType(<x/>.<y>, B) ~~~~~~~~ BC42322: Runtime errors might occur when converting 'IEnumerable(Of XElement)' to 'B'. _b = DirectCast(<x/>.<y>, B) ~~~~~~~~ BC42322: Runtime errors might occur when converting 'IEnumerable(Of XElement)' to 'B'. _b = TryCast(<x/>.<y>, B) ~~~~~~~~ ]]></errors>) End Sub ' Same as above but with "Option Strict On". <Fact()> Public Sub BC42361WRN_UseValueForXmlExpression3_1() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports System.Collections.Generic Imports System.Xml.Linq Class A End Class NotInheritable Class B End Class Module M Sub M(Of T As Class)() Dim _o As Object Dim _s As String Dim _a As A Dim _b As B Dim _t As T _o = <x/>.<y> _o = CType(<x/>.<y>, Object) _o = DirectCast(<x/>.<y>, Object) _o = TryCast(<x/>.<y>, Object) _s = <x/>.<y> _s = CType(<x/>.<y>, String) _s = DirectCast(<x/>.<y>, String) _s = TryCast(<x/>.<y>, String) _a = <x/>.<y> _a = CType(<x/>.<y>, A) _a = DirectCast(<x/>.<y>, A) _a = TryCast(<x/>.<y>, A) _b = <x/>.<y> _b = CType(<x/>.<y>, B) _b = DirectCast(<x/>.<y>, B) _b = TryCast(<x/>.<y>, B) _t = <x/>.<y> _t = CType(<x/>.<y>, T) _t = DirectCast(<x/>.<y>, T) _t = TryCast(<x/>.<y>, T) End Sub End Module ]]></file> </compilation>, references:=XmlReferences) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC30512: Option Strict On disallows implicit conversions from 'IEnumerable(Of XElement)' to 'String'. _s = <x/>.<y> ~~~~~~~~ BC42361: Cannot convert 'IEnumerable(Of XElement)' to 'String'. You can use the 'Value' property to get the string value of the first element of 'IEnumerable(Of XElement)'. _s = <x/>.<y> ~~~~~~~~ BC42361: Cannot convert 'IEnumerable(Of XElement)' to 'String'. You can use the 'Value' property to get the string value of the first element of 'IEnumerable(Of XElement)'. _s = CType(<x/>.<y>, String) ~~~~~~~~ BC42361: Cannot convert 'IEnumerable(Of XElement)' to 'String'. You can use the 'Value' property to get the string value of the first element of 'IEnumerable(Of XElement)'. _s = DirectCast(<x/>.<y>, String) ~~~~~~~~ BC42361: Cannot convert 'IEnumerable(Of XElement)' to 'String'. You can use the 'Value' property to get the string value of the first element of 'IEnumerable(Of XElement)'. _s = TryCast(<x/>.<y>, String) ~~~~~~~~ BC30512: Option Strict On disallows implicit conversions from 'IEnumerable(Of XElement)' to 'A'. _a = <x/>.<y> ~~~~~~~~ BC30512: Option Strict On disallows implicit conversions from 'IEnumerable(Of XElement)' to 'B'. _b = <x/>.<y> ~~~~~~~~ BC42322: Runtime errors might occur when converting 'IEnumerable(Of XElement)' to 'B'. _b = <x/>.<y> ~~~~~~~~ BC42322: Runtime errors might occur when converting 'IEnumerable(Of XElement)' to 'B'. _b = CType(<x/>.<y>, B) ~~~~~~~~ BC42322: Runtime errors might occur when converting 'IEnumerable(Of XElement)' to 'B'. _b = DirectCast(<x/>.<y>, B) ~~~~~~~~ BC42322: Runtime errors might occur when converting 'IEnumerable(Of XElement)' to 'B'. _b = TryCast(<x/>.<y>, B) ~~~~~~~~ BC30512: Option Strict On disallows implicit conversions from 'IEnumerable(Of XElement)' to 'T'. _t = <x/>.<y> ~~~~~~~~ ]]></errors>) End Sub <Fact()> Public Sub BC42361WRN_UseValueForXmlExpression3_2() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="a.vb"><![CDATA[ Option Strict Off Imports System.Collections.Generic Imports System.Xml.Linq Class X Inherits XElement Public Sub New(name As XName) MyBase.New(name) End Sub End Class Interface IEnumerableOfXElement Inherits IEnumerable(Of XElement) End Interface Module M Sub M(Of T As XElement)(_1 As XElement, _2 As IEnumerable(Of XElement), _3 As XElement(), _4 As List(Of XElement), _5 As IEnumerable(Of XObject), _6 As IEnumerable(Of XElement)(), _7 As IEnumerableOfXElement, _8 As IEnumerable(Of X), _9 As IEnumerable(Of T)) Dim o As String o = _1 o = _2 o = _3 o = _4 o = _5 o = _6 o = _7 o = _8 o = _9 End Sub End Module ]]></file> </compilation>, references:=XmlReferences) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC42361: Cannot convert 'IEnumerable(Of XElement)' to 'String'. You can use the 'Value' property to get the string value of the first element of 'IEnumerable(Of XElement)'. o = _2 ~~ BC30311: Value of type 'XElement()' cannot be converted to 'String'. o = _3 ~~ BC30311: Value of type 'List(Of XElement)' cannot be converted to 'String'. o = _4 ~~ BC42322: Runtime errors might occur when converting 'IEnumerable(Of XObject)' to 'String'. o = _5 ~~ BC30311: Value of type 'IEnumerable(Of XElement)()' cannot be converted to 'String'. o = _6 ~~ BC42361: Cannot convert 'IEnumerableOfXElement' to 'String'. You can use the 'Value' property to get the string value of the first element of 'IEnumerableOfXElement'. o = _7 ~~ BC42361: Cannot convert 'IEnumerable(Of X)' to 'String'. You can use the 'Value' property to get the string value of the first element of 'IEnumerable(Of X)'. o = _8 ~~ BC42361: Cannot convert 'IEnumerable(Of T As XElement)' to 'String'. You can use the 'Value' property to get the string value of the first element of 'IEnumerable(Of T As XElement)'. o = _9 ~~ ]]></errors>) End Sub ' Conversions to IEnumerable(Of XElement). Dev11 reports BC31193 ' when converting NotInheritable Class to IEnumerable(Of XElement). <Fact()> Public Sub BC42361WRN_UseValueForXmlExpression3_3() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="a.vb"><![CDATA[ Option Strict Off Imports System.Collections.Generic Imports System.Xml.Linq Class A End Class NotInheritable Class B End Class Module M Sub M(Of T As Class)() Dim _i As IEnumerable(Of XElement) Dim _o As Object = Nothing Dim _s As String = Nothing Dim _a As A = Nothing Dim _b As B = Nothing Dim _t As T = Nothing _i = _o _i = _s _i = _a _i = _b _i = _t End Sub End Module ]]></file> </compilation>, references:=XmlReferences) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC42322: Runtime errors might occur when converting 'String' to 'IEnumerable(Of XElement)'. _i = _s ~~ BC42322: Runtime errors might occur when converting 'B' to 'IEnumerable(Of XElement)'. _i = _b ~~ ]]></errors>) End Sub <Fact()> Public Sub BC31194ERR_TypeMismatchForXml3() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Option Strict Off Structure S End Structure Module M Sub M() Dim _s As S _s = <x/>.<y> _s = CType(<x/>.<y>, S) _s = DirectCast(<x/>.<y>, S) End Sub End Module ]]></file> </compilation>, references:=XmlReferences) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC31194: Value of type 'IEnumerable(Of XElement)' cannot be converted to 'S'. You can use the 'Value' property to get the string value of the first element of 'IEnumerable(Of XElement)'. _s = <x/>.<y> ~~~~~~~~ BC31194: Value of type 'IEnumerable(Of XElement)' cannot be converted to 'S'. You can use the 'Value' property to get the string value of the first element of 'IEnumerable(Of XElement)'. _s = CType(<x/>.<y>, S) ~~~~~~~~ BC31194: Value of type 'IEnumerable(Of XElement)' cannot be converted to 'S'. You can use the 'Value' property to get the string value of the first element of 'IEnumerable(Of XElement)'. _s = DirectCast(<x/>.<y>, S) ~~~~~~~~ ]]></errors>) End Sub <Fact()> Public Sub BC31194ERR_TypeMismatchForXml3_1() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Option Strict Off Imports System.Collections.Generic Imports System.Xml.Linq Structure S End Structure Class X Inherits XElement Public Sub New(name As XName) MyBase.New(name) End Sub End Class Interface IEnumerableOfXElement Inherits IEnumerable(Of XElement) End Interface Module M Sub M(Of T As XElement)(_1 As XElement, _2 As IEnumerable(Of XElement), _3 As XElement(), _4 As List(Of XElement), _5 As IEnumerable(Of XObject), _6 As IEnumerable(Of XElement)(), _7 As IEnumerableOfXElement, _8 As IEnumerable(Of X), _9 As IEnumerable(Of T)) Dim o As S o = _1 o = _2 o = _3 o = _4 o = _5 o = _6 o = _7 o = _8 o = _9 End Sub End Module ]]></file> </compilation>, references:=XmlReferences) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC30311: Value of type 'XElement' cannot be converted to 'S'. o = _1 ~~ BC31194: Value of type 'IEnumerable(Of XElement)' cannot be converted to 'S'. You can use the 'Value' property to get the string value of the first element of 'IEnumerable(Of XElement)'. o = _2 ~~ BC30311: Value of type 'XElement()' cannot be converted to 'S'. o = _3 ~~ BC30311: Value of type 'List(Of XElement)' cannot be converted to 'S'. o = _4 ~~ BC30311: Value of type 'IEnumerable(Of XObject)' cannot be converted to 'S'. o = _5 ~~ BC30311: Value of type 'IEnumerable(Of XElement)()' cannot be converted to 'S'. o = _6 ~~ BC31194: Value of type 'IEnumerableOfXElement' cannot be converted to 'S'. You can use the 'Value' property to get the string value of the first element of 'IEnumerableOfXElement'. o = _7 ~~ BC31194: Value of type 'IEnumerable(Of X)' cannot be converted to 'S'. You can use the 'Value' property to get the string value of the first element of 'IEnumerable(Of X)'. o = _8 ~~ BC31194: Value of type 'IEnumerable(Of T As XElement)' cannot be converted to 'S'. You can use the 'Value' property to get the string value of the first element of 'IEnumerable(Of T As XElement)'. o = _9 ~~ ]]></errors>) End Sub <Fact()> Public Sub BC31195ERR_BinaryOperandsForXml4() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Option Strict Off Imports System.Collections.Generic Imports System.Xml.Linq Class C End Class Class X Inherits XElement Public Sub New(name As XName) MyBase.New(name) End Sub End Class Interface IEnumerableOfXElement Inherits IEnumerable(Of XElement) End Interface Module M Sub M(Of T As XElement)(o As C, _1 As XElement, _2 As IEnumerable(Of XElement), _3 As XElement(), _4 As List(Of XElement), _5 As IEnumerable(Of XObject), _6 As IEnumerable(Of XElement)(), _7 As IEnumerableOfXElement, _8 As IEnumerable(Of X), _9 As IEnumerable(Of T)) Dim b As Boolean b = (o = _1) b = (o = _2) b = (o = _3) b = (o = _4) b = (_5 = o) b = (_6 = o) b = (_7 = o) b = (_8 = o) b = (_9 = o) b = (_1 = _2) b = (_2 = _2) b = (_3 = _2) b = (_4 = _2) b = (_5 = _2) b = (_2 = _6) b = (_2 = _7) b = (_2 = _8) b = (_2 = _9) End Sub End Module ]]></file> </compilation>, references:=XmlReferences) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC30452: Operator '=' is not defined for types 'C' and 'XElement'. b = (o = _1) ~~~~~~ BC31195: Operator '=' is not defined for types 'C' and 'IEnumerable(Of XElement)'. You can use the 'Value' property to get the string value of the first element of 'IEnumerable(Of XElement)'. b = (o = _2) ~~~~~~ BC31195: Operator '=' is not defined for types 'C' and 'XElement()'. You can use the 'Value' property to get the string value of the first element of 'XElement()'. b = (o = _3) ~~~~~~ BC31195: Operator '=' is not defined for types 'C' and 'List(Of XElement)'. You can use the 'Value' property to get the string value of the first element of 'List(Of XElement)'. b = (o = _4) ~~~~~~ BC30452: Operator '=' is not defined for types 'IEnumerable(Of XObject)' and 'C'. b = (_5 = o) ~~~~~~ BC30452: Operator '=' is not defined for types 'IEnumerable(Of XElement)()' and 'C'. b = (_6 = o) ~~~~~~ BC31195: Operator '=' is not defined for types 'IEnumerableOfXElement' and 'C'. You can use the 'Value' property to get the string value of the first element of 'IEnumerableOfXElement'. b = (_7 = o) ~~~~~~ BC31195: Operator '=' is not defined for types 'IEnumerable(Of X)' and 'C'. You can use the 'Value' property to get the string value of the first element of 'IEnumerable(Of X)'. b = (_8 = o) ~~~~~~ BC31195: Operator '=' is not defined for types 'IEnumerable(Of T As XElement)' and 'C'. You can use the 'Value' property to get the string value of the first element of 'IEnumerable(Of T As XElement)'. b = (_9 = o) ~~~~~~ BC31195: Operator '=' is not defined for types 'XElement' and 'IEnumerable(Of XElement)'. You can use the 'Value' property to get the string value of the first element of 'IEnumerable(Of XElement)'. b = (_1 = _2) ~~~~~~~ BC31080: Operator '=' is not defined for types 'IEnumerable(Of XElement)' and 'IEnumerable(Of XElement)'. Use 'Is' operator to compare two reference types. b = (_2 = _2) ~~~~~~~ BC31080: Operator '=' is not defined for types 'XElement()' and 'IEnumerable(Of XElement)'. Use 'Is' operator to compare two reference types. b = (_3 = _2) ~~~~~~~ BC31195: Operator '=' is not defined for types 'List(Of XElement)' and 'IEnumerable(Of XElement)'. You can use the 'Value' property to get the string value of the first element of 'List(Of XElement)'. b = (_4 = _2) ~~~~~~~ BC31080: Operator '=' is not defined for types 'IEnumerable(Of XObject)' and 'IEnumerable(Of XElement)'. Use 'Is' operator to compare two reference types. b = (_5 = _2) ~~~~~~~ BC31080: Operator '=' is not defined for types 'IEnumerable(Of XElement)' and 'IEnumerable(Of XElement)()'. Use 'Is' operator to compare two reference types. b = (_2 = _6) ~~~~~~~ BC31080: Operator '=' is not defined for types 'IEnumerable(Of XElement)' and 'IEnumerableOfXElement'. Use 'Is' operator to compare two reference types. b = (_2 = _7) ~~~~~~~ BC31080: Operator '=' is not defined for types 'IEnumerable(Of XElement)' and 'IEnumerable(Of X)'. Use 'Is' operator to compare two reference types. b = (_2 = _8) ~~~~~~~ BC31080: Operator '=' is not defined for types 'IEnumerable(Of XElement)' and 'IEnumerable(Of T As XElement)'. Use 'Is' operator to compare two reference types. b = (_2 = _9) ~~~~~~~ ]]></errors>) End Sub <Fact()> Public Sub BC31394ERR_RestrictedConversion1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="RestrictedConversion1"> <file name="a.vb"> Class C1 Sub FOO() Dim obj As Object obj = New system.ArgIterator End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC31394: Expression of type 'ArgIterator' cannot be converted to 'Object' or 'ValueType'. obj = New system.ArgIterator ~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <WorkItem(527685, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527685")> <Fact()> Public Sub BC31394ERR_RestrictedConversion1_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="RestrictedConversion1_1"> <file name="a.vb"> Option Infer Off imports system Structure C1 Sub FOO() Dim obj = New ArgIterator Dim TypeRefInstance As TypedReference obj = TypeRefInstance End Sub End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC31394: Expression of type 'ArgIterator' cannot be converted to 'Object' or 'ValueType'. Dim obj = New ArgIterator ~~~~~~~~~~~~~~~ BC31394: Expression of type 'TypedReference' cannot be converted to 'Object' or 'ValueType'. obj = TypeRefInstance ~~~~~~~~~~~~~~~ BC42109: Variable 'TypeRefInstance' is used before it has been assigned a value. A null reference exception could result at runtime. Make sure the structure or all the reference members are initialized before use obj = TypeRefInstance ~~~~~~~~~~~~~~~ </expected>) End Sub <WorkItem(527685, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527685")> <Fact()> Public Sub BC31394ERR_RestrictedConversion1_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="RestrictedConversion1"> <file name="a.vb"> Option Infer Off imports system Structure C1 Sub FOO() Dim obj = New ArgIterator obj = New RuntimeArgumentHandle End Sub End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC31394: Expression of type 'ArgIterator' cannot be converted to 'Object' or 'ValueType'. Dim obj = New ArgIterator ~~~~~~~~~~~~~~~ BC31394: Expression of type 'RuntimeArgumentHandle' cannot be converted to 'Object' or 'ValueType'. obj = New RuntimeArgumentHandle ~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact(), WorkItem(529561, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529561")> Public Sub BC31396ERR_RestrictedType1_1() CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Module M Sub Main() Dim x As TypedReference() Dim y() As ArgIterator Dim z = {New RuntimeArgumentHandle()} End Sub End Module </file> </compilation>).AssertTheseDiagnostics( <expected> BC42024: Unused local variable: 'x'. Dim x As TypedReference() ~ BC31396: 'TypedReference' 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 As TypedReference() ~~~~~~~~~~~~~~~~ BC42024: Unused local variable: 'y'. Dim 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 ArgIterator ~~~~~~~~~~~ BC31396: 'RuntimeArgumentHandle' 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 = {New RuntimeArgumentHandle()} ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC31396: 'RuntimeArgumentHandle' 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 = {New RuntimeArgumentHandle()} ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC31396ERR_RestrictedType1_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System Class C(Of T) Shared Sub F(Of U)(o As U) End Sub Shared Sub M() Dim o As Object o = New C(Of ArgIterator) o = New C(Of RuntimeArgumentHandle) o = New C(Of TypedReference) F(Of ArgIterator)(Nothing) F(Of RuntimeArgumentHandle)(Nothing) Dim t As TypedReference = Nothing F(t) End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> 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. o = New C(Of ArgIterator) ~~~~~~~~~~~ BC31396: 'RuntimeArgumentHandle' 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. o = New C(Of RuntimeArgumentHandle) ~~~~~~~~~~~~~~~~~~~~~ BC31396: 'TypedReference' 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. o = New C(Of TypedReference) ~~~~~~~~~~~~~~ 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. F(Of ArgIterator)(Nothing) ~~~~~~~~~~~~~~~~~ BC31396: 'RuntimeArgumentHandle' 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. F(Of RuntimeArgumentHandle)(Nothing) ~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC31396: 'TypedReference' 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. F(t) ~ </expected>) End Sub <Fact()> Public Sub BC31396ERR_RestrictedType1_3() CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Class C Private F As TypedReference Private G As ArgIterator() Private H = {New RuntimeArgumentHandle()} Sub M(e As ArgIterator()) End Sub End Class Interface I ReadOnly Property P As TypedReference Function F() As ArgIterator()() Property Q As RuntimeArgumentHandle()() End Interface </file> </compilation>).AssertTheseDiagnostics( <expected> BC31396: 'TypedReference' 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. Private F As TypedReference ~~~~~~~~~~~~~~ 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. Private G As ArgIterator() ~~~~~~~~~~~~~ BC31396: 'RuntimeArgumentHandle' 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. Private H = {New RuntimeArgumentHandle()} ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 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(e As ArgIterator()) ~~~~~~~~~~~~~ BC31396: 'TypedReference' 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. ReadOnly Property P As TypedReference ~~~~~~~~~~~~~~ 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. Function F() As ArgIterator()() ~~~~~~~~~~~~~~~ BC31396: 'RuntimeArgumentHandle' 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. Property Q As RuntimeArgumentHandle()() ~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC31399ERR_NoAccessibleConstructorOnBase() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="NoAccessibleConstructorOnBase"> <file name="a.vb"> Class c1 Private Sub New() End Sub End Class Class c2 Inherits c1 End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC31399: Class 'c1' has no accessible 'Sub New' and cannot be inherited. Class c2 ~~ </expected>) End Sub <Fact()> Public Sub BC31419ERR_IsNotOpRequiresReferenceTypes1() CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class A1 Sub scen1() dim arr1 = New Integer() {1, 2, 3} dim arr2 = arr1 Dim b As Boolean b = arr1(0) IsNot arr2(0) End Sub End Class </file> </compilation>).VerifyDiagnostics( Diagnostic(ERRID.ERR_IsNotOpRequiresReferenceTypes1, "arr1(0)").WithArguments("Integer"), Diagnostic(ERRID.ERR_IsNotOpRequiresReferenceTypes1, "arr2(0)").WithArguments("Integer")) End Sub <Fact()> Public Sub BC31419ERR_IsNotOpRequiresReferenceTypes1_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class A1 Sub scen1() Dim a As E Dim b As S1 dim o = a IsNot b End Sub End Class structure S1 End structure ENUM E Dummy End ENUM </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC31419: 'IsNot' requires operands that have reference types, but this operand has the value type 'E'. dim o = a IsNot b ~ BC31419: 'IsNot' requires operands that have reference types, but this operand has the value type 'S1'. dim o = a IsNot b ~ </expected>) End Sub <Fact()> Public Sub BC31419ERR_IsNotOpRequiresReferenceTypes1_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Interface I End Interface Class A End Class Class B(Of T As Structure) End Class Class C Shared Sub M1(Of T1)(_1 As T1) If _1 IsNot Nothing Then End If If Nothing IsNot _1 Then End If End Sub Shared Sub M2(Of T2 As Class)(_2 As T2) If _2 IsNot Nothing Then End If If Nothing IsNot _2 Then End If End Sub Shared Sub M3(Of T3 As Structure)(_3 As T3) If _3 IsNot Nothing Then End If If Nothing IsNot _3 Then End If End Sub Shared Sub M4(Of T4 As New)(_4 As T4) If _4 IsNot Nothing Then End If If Nothing IsNot _4 Then End If End Sub Shared Sub M5(Of T5 As I)(_5 As T5) If _5 IsNot Nothing Then End If If Nothing IsNot _5 Then End If End Sub Shared Sub M6(Of T6 As A)(_6 As T6) If _6 IsNot Nothing Then End If If Nothing IsNot _6 Then End If End Sub Shared Sub M7(Of T7 As U, U)(_7 As T7) If _7 IsNot Nothing Then End If If Nothing IsNot _7 Then End If End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC31419: 'IsNot' requires operands that have reference types, but this operand has the value type 'T3'. If _3 IsNot Nothing Then ~~ BC31419: 'IsNot' requires operands that have reference types, but this operand has the value type 'T3'. If Nothing IsNot _3 Then ~~ </expected>) End Sub <WorkItem(542192, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542192")> <Fact()> Public Sub BC31428ERR_VoidArrayDisallowed() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="VoidArrayDisallowed"> <file name="a.vb"> Imports System Module M1 Dim y As Type = GetType(Void) Dim x As Type = GetType(Void()) End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC31428: Arrays of type 'System.Void' are not allowed in this expression. Dim x As Type = GetType(Void()) ~~~~~~ </expected>) End Sub <Fact()> Public Sub PartialMethodAndDeclareMethod() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Imports System.Runtime.InteropServices Partial Class Clazz Partial Private Declare Sub S0 Lib "abc.dll" (p As String) Partial Private Sub S1(&lt;Out> p As String) End Sub Partial Private Sub S2(&lt;Out> ByRef p As String) End Sub End Class Partial Class Clazz Private Declare Sub S1 Lib "abc.dll" (p As String) End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30244: 'Partial' is not valid on a Declare. Partial Private Declare Sub S0 Lib "abc.dll" (p As String) ~~~~~~~ BC30345: 'Private Sub S1(p As String)' and 'Private Declare Ansi Sub S1 Lib "abc.dll" (p As String)' cannot overload each other because they differ only by parameters declared 'ByRef' or 'ByVal'. Partial Private Sub S1(&lt;Out> p As String) ~~ </expected>) End Sub <Fact()> Public Sub BC31435ERR_PartialMethodMustBeEmpty() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="PartialMethodMustBeEmpty"> <file name="a.vb"> Class C1 Partial Private Sub Foo() System.Console.WriteLine() End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC31435: Partial methods must have empty method bodies. Partial Private Sub Foo() ~~~ </expected>) End Sub <Fact()> Public Sub BC31435ERR_PartialMethodMustBeEmpty2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="PartialMethodMustBeEmpty2"> <file name="a.vb"> Imports System Class C1 Partial Private Shared Sub PS(a As Integer) Console.WriteLine() End Sub Partial Private Shared Sub Ps(a As Integer) Console.WriteLine() End Sub Private Shared Sub PS(a As Integer) End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC31435: Partial methods must have empty method bodies. Partial Private Shared Sub PS(a As Integer) ~~ BC31433: Method 'Ps' cannot be declared 'Partial' because only one method 'Ps' can be marked 'Partial'. Partial Private Shared Sub Ps(a As Integer) ~~ </expected>) End Sub <Fact()> Public Sub BC31435ERR_PartialMethodMustBeEmpty3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="PartialMethodMustBeEmpty3"> <file name="a.vb"> Imports System Class C1 Partial Private Shared Sub PS(a As Integer) End Sub Partial Private Shared Sub Ps(a As Integer) Console.WriteLine() End Sub Private Shared Sub PS(a As Integer) End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC31433: Method 'Ps' cannot be declared 'Partial' because only one method 'Ps' can be marked 'Partial'. Partial Private Shared Sub Ps(a As Integer) ~~ </expected>) End Sub <Fact()> Public Sub BC31440ERR_NoPartialMethodInAddressOf1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="NoPartialMethodInAddressOf1"> <file name="a.vb"> Public Class C1 Event x() Partial Private Sub Foo() End Sub Sub MethodToAddHandlerInPrivatePartial() AddHandler Me.x, AddressOf Me.Foo End Sub Sub MethodToRemoveHandlerInPrivatePartial() RemoveHandler Me.x, AddressOf Me.Foo End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC31440: 'AddressOf' cannot be applied to 'Private Sub Foo()' because 'Private Sub Foo()' is a partial method without an implementation. AddHandler Me.x, AddressOf Me.Foo ~~~~~~ BC31440: 'AddressOf' cannot be applied to 'Private Sub Foo()' because 'Private Sub Foo()' is a partial method without an implementation. RemoveHandler Me.x, AddressOf Me.Foo ~~~~~~ </expected>) End Sub ' Roslyn extra - ERR_TypeMismatch2 * 2 <Fact()> Public Sub BC31440ERR_NoPartialMethodInAddressOf1a() CreateCompilationWithMscorlib40( <compilation name="NoPartialMethodInAddressOf1a"> <file name="a.vb"> Imports System Public Class C1 Event x() Partial Private Sub Foo() End Sub Sub MethodToAddHandlerInPrivatePartial() AddHandler Me.x, New Action(AddressOf Me.Foo) End Sub Sub MethodToRemoveHandlerInPrivatePartial() RemoveHandler Me.x, New Action(AddressOf Me.Foo) End Sub End Class </file> </compilation>).VerifyDiagnostics( Diagnostic(ERRID.ERR_NoPartialMethodInAddressOf1, "Me.Foo").WithArguments("Private Sub Foo()"), Diagnostic(ERRID.ERR_TypeMismatch2, "New Action(AddressOf Me.Foo)").WithArguments("System.Action", "C1.xEventHandler"), Diagnostic(ERRID.ERR_NoPartialMethodInAddressOf1, "Me.Foo").WithArguments("Private Sub Foo()"), Diagnostic(ERRID.ERR_TypeMismatch2, "New Action(AddressOf Me.Foo)").WithArguments("System.Action", "C1.xEventHandler")) End Sub <Fact()> Public Sub BC31440ERR_NoPartialMethodInAddressOf1b() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="NoPartialMethodInAddressOf1b"> <file name="a.vb"> Imports System Public Class C1 Sub Test() Dim a As Action = New Action(AddressOf Me.Foo) a() End Sub Partial Private Sub Foo() End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC31440: 'AddressOf' cannot be applied to 'Private Sub Foo()' because 'Private Sub Foo()' is a partial method without an implementation. Dim a As Action = New Action(AddressOf Me.Foo) ~~~~~~ </expected>) End Sub <Fact()> Public Sub BC31500ERR_BadAttributeSharedProperty1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BadAttributeSharedProperty1"> <file name="at31500.vb"><![CDATA[ Imports System <AttributeUsage(AttributeTargets.All)> Public Class MyAttribute Inherits Attribute Public Shared SharedField As String Public Const ConstField As String = "AAA" End Class <My(SharedField:="testing")> Class Foo <My(ConstField:="testing")> Public Sub S() End Sub End Class ]]></file> </compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_BadAttributeSharedProperty1, "SharedField").WithArguments("SharedField"), Diagnostic(ERRID.ERR_BadAttributeSharedProperty1, "ConstField").WithArguments("ConstField")) ' Dev10: 31510 End Sub ''' BC31510 in DEV10 but is BC31500 in Roslyn <Fact()> Public Sub BC31500ERR_BadAttributeSharedProperty1_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BadAttributeConstField1"> <file name="a.vb"> Imports System &lt;AttributeUsage(AttributeTargets.All)&gt; Class attr Inherits Attribute Public Const c As String = "A" End Class &lt;attr(c:="test")&gt; Class c8 End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC31500: 'Shared' attribute property 'c' cannot be the target of an assignment. &lt;attr(c:="test")&gt; Class c8 ~ </expected>) End Sub <Fact()> Public Sub BC31501ERR_BadAttributeReadOnlyProperty1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BadAttributeReadOnlyProperty1"> <file name="at31501.vb"><![CDATA[ Imports System <AttributeUsage(AttributeTargets.All)> Public Class MyAttribute Inherits Attribute Public ReadOnly Property RP As String Get Return "RP" End Get End Property Public WriteOnly Property WP As Integer Set(value As Integer) End Set End Property End Class <MyAttribute(WP:=123, RP:="123")> Class Test End Class ]]></file> </compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_BadAttributeReadOnlyProperty1, "RP").WithArguments("RP")) End Sub Private Shared ReadOnly s_badAttributeIl As String = <![CDATA[ .class public auto ansi beforefieldinit BaseAttribute extends [mscorlib]System.Attribute { .custom instance void [mscorlib]System.AttributeUsageAttribute::.ctor(valuetype [mscorlib]System.AttributeTargets) = ( 01 00 FF 7F 00 00 00 00 ) .method public hidebysig newslot specialname virtual instance int32 get_PROP() cil managed { // Code size 2 (0x2) .maxstack 8 IL_0000: ldc.i4.1 IL_0001: ret } // end of method BaseAttribute::get_PROP .method public hidebysig newslot specialname virtual instance void set_PROP(int32 'value') cil managed { // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method BaseAttribute::set_PROP .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Attribute::.ctor() IL_0006: ret } // end of method BaseAttribute::.ctor .property instance int32 PROP() { .get instance int32 BaseAttribute::get_PROP() .set instance void BaseAttribute::set_PROP(int32) } // end of property BaseAttribute::PROP } // end of class BaseAttribute .class public auto ansi beforefieldinit DerivedAttribute extends BaseAttribute { .method public hidebysig specialname virtual instance int32 get_PROP() cil managed { // Code size 2 (0x2) .maxstack 8 IL_0000: ldc.i4.1 IL_0001: ret } // end of method DerivedAttribute::get_PROP .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void BaseAttribute::.ctor() IL_0006: ret } // end of method DerivedAttribute::.ctor .property instance int32 PROP() { .get instance int32 DerivedAttribute::get_PROP() } // end of property DerivedAttribute::PROP } // end of class DerivedAttribute ]]>.Value.Replace(vbLf, vbNewLine) <WorkItem(528981, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528981")> <Fact()> Public Sub BC31501ERR_BadAttributeReadOnlyProperty2() Dim compilation = CompilationUtils.CreateCompilationWithCustomILSource( <compilation name="BadAttributeReadOnlyProperty2"> <file name="at31501.vb"><![CDATA[ <Derived(PROP:=1)> Class Test End Class ]]></file> </compilation>, s_badAttributeIl).VerifyDiagnostics(Diagnostic(ERRID.ERR_BadAttributeReadOnlyProperty1, "PROP").WithArguments("PROP")) End Sub <WorkItem(540627, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540627")> <Fact()> Public Sub BC31511ERR_BadAttributeNonPublicProperty1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BadAttributeNonPublicProperty1"> <file name="at31511.vb"><![CDATA[ Imports System <AttributeUsage(AttributeTargets.All)> Public Class MyAttribute Inherits Attribute Friend Field As String Friend Property Prop As Long End Class <My(Field:="testing")> Class Foo <My(Prop:=12345)> Public Sub S() End Sub End Class ]]></file> </compilation>).VerifyDiagnostics( Diagnostic(ERRID.ERR_BadAttributeNonPublicProperty1, "Field").WithArguments("Field"), Diagnostic(ERRID.ERR_BadAttributeNonPublicProperty1, "Prop").WithArguments("Prop") ) End Sub <WorkItem(539101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539101")> <Fact()> Public Sub BC32000ERR_UseOfLocalBeforeDeclaration1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="LocalVariableCannotBeReferredToBeforeItIsDeclared"> <file name="a.vb"> Imports System Module X Sub foo() Dim x as integer x = y dim y as integer = 1 End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC32000: Local variable 'y' cannot be referred to before it is declared. x = y ~ </expected>) End Sub <Fact()> Public Sub BC32001ERR_UseOfKeywordFromModule1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="UseOfKeywordFromModule1"> <file name="a.vb"> Imports System Module X Sub foo() Dim o = Me dim p = MyBase.GetType End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC32001: 'Me' is not valid within a Module. Dim o = Me ~~ BC32001: 'MyBase' is not valid within a Module. dim p = MyBase.GetType ~~~~~~ </expected>) End Sub <WorkItem(542958, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542958")> <Fact()> Public Sub BC32001ERR_UseOfKeywordFromModule1_MeAsAttributeInModule() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="UseOfKeywordFromModule1_MeAsAttributeInModule"> <file name="a.vb"> Option Strict On Imports System Imports System.Runtime.InteropServices Public Module S1 &lt;MyAttribute(Me.color1.blue)&gt; Property name As String Sub foo() End Sub Sub main() End Sub Enum color1 blue End Enum End Module Class MyAttribute Inherits Attribute Sub New(x As S1.color1) End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC32001: 'Me' is not valid within a Module. &lt;MyAttribute(Me.color1.blue)&gt; ~~ </expected>) End Sub <WorkItem(542960, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542960")> <Fact()> Public Sub BC32001ERR_UseOfKeywordFromModule1_MyBaseAsAttributeInModule() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="UseOfKeywordFromModule1_MyBaseAsAttributeInModule"> <file name="a.vb"> Option Strict On Imports System Imports System.Runtime.InteropServices Public Module S1 &lt;MyAttribute(MyBase.color1.blue)&gt; Property name As String Sub foo() End Sub Sub main() End Sub Enum color1 blue End Enum End Module Class MyAttribute Inherits Attribute Sub New(x As S1.color1) End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC32001: 'MyBase' is not valid within a Module. &lt;MyAttribute(MyBase.color1.blue)&gt; ~~~~~~ </expected>) End Sub <Fact()> Public Sub BC32006ERR_CharToIntegralTypeMismatch1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="CharToIntegralTypeMismatch1"> <file name="a.vb"> Class C1 SUB scen1() Dim char1() As Char Dim bt(2) As Byte bt(0) = CType (char1(0), Byte) Dim char2() As Char Dim sht1(2) As Short sht1(0) = char2(0) sht1(0) = CType (char2(0), Short) End SUB End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42104: Variable 'char1' is used before it has been assigned a value. A null reference exception could result at runtime. bt(0) = CType (char1(0), Byte) ~~~~~ BC32006: 'Char' values cannot be converted to 'Byte'. Use 'Microsoft.VisualBasic.AscW' to interpret a character as a Unicode value or 'Microsoft.VisualBasic.Val' to interpret it as a digit. bt(0) = CType (char1(0), Byte) ~~~~~~~~ BC42104: Variable 'char2' is used before it has been assigned a value. A null reference exception could result at runtime. sht1(0) = char2(0) ~~~~~ BC32006: 'Char' values cannot be converted to 'Short'. Use 'Microsoft.VisualBasic.AscW' to interpret a character as a Unicode value or 'Microsoft.VisualBasic.Val' to interpret it as a digit. sht1(0) = char2(0) ~~~~~~~~ BC32006: 'Char' values cannot be converted to 'Short'. Use 'Microsoft.VisualBasic.AscW' to interpret a character as a Unicode value or 'Microsoft.VisualBasic.Val' to interpret it as a digit. sht1(0) = CType (char2(0), Short) ~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC32006ERR_CharToIntegralTypeMismatch1_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndReferences( <compilation name="CharToIntegralTypeMismatch1"> <file name="a.vb"> Imports System.Linq Class C Shared Sub Main() For Each x As Integer In From c In "abc" Select c Next End Sub End Class Public Structure S End Structure </file> </compilation>, {Net40.SystemCore}) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC32006: 'Char' values cannot be converted to 'Integer'. Use 'Microsoft.VisualBasic.AscW' to interpret a character as a Unicode value or 'Microsoft.VisualBasic.Val' to interpret it as a digit. For Each x As Integer In From c In "abc" Select c ~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC32007ERR_IntegralToCharTypeMismatch1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="CharToIntegralTypeMismatch1"> <file name="a.vb"> Imports System Module X Sub Foo() Dim O As Object 'COMPILEERROR: BC32007, "CUShort(15)" O = CChar(CUShort(15)) Dim sb As UShort = CUShort(1) 'COMPILEERROR: BC32007, "sb" O = CChar(sb) End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC32007: 'UShort' values cannot be converted to 'Char'. Use 'Microsoft.VisualBasic.ChrW' to interpret a numeric value as a Unicode character or first convert it to 'String' to produce a digit. O = CChar(CUShort(15)) ~~~~~~~~~~~ BC32007: 'UShort' values cannot be converted to 'Char'. Use 'Microsoft.VisualBasic.ChrW' to interpret a numeric value as a Unicode character or first convert it to 'String' to produce a digit. O = CChar(sb) ~~ </expected>) End Sub <Fact()> Public Sub BC32008ERR_NoDirectDelegateConstruction1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="NoDirectDelegateConstruction1"> <file name="a.vb"> Class C1 Public Delegate Sub myDelegate() public shared sub mySub() end sub End Class Module M1 Sub Main() Dim d1 As C1.myDelegate d1 = New C1.myDelegate() d1 = New C1.myDelegate(C1.mySub) d1 = New C1.myDelegate(C1.mySub, 23) d1 = New C1.myDelegate(addressof C1.mySub, 23) d1 = New C1.myDelegate(,) d1 = New C1.myDelegate(,,23) End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC32008: Delegate 'C1.myDelegate' requires an 'AddressOf' expression or lambda expression as the only argument to its constructor. d1 = New C1.myDelegate() ~~ BC32008: Delegate 'C1.myDelegate' requires an 'AddressOf' expression or lambda expression as the only argument to its constructor. d1 = New C1.myDelegate(C1.mySub) ~~~~~~~~~~ BC32008: Delegate 'C1.myDelegate' requires an 'AddressOf' expression or lambda expression as the only argument to its constructor. d1 = New C1.myDelegate(C1.mySub, 23) ~~~~~~~~~~~~~~ BC32008: Delegate 'C1.myDelegate' requires an 'AddressOf' expression or lambda expression as the only argument to its constructor. d1 = New C1.myDelegate(addressof C1.mySub, 23) ~~~~~~~~~~~~~~~~~~~~~~~~ BC32008: Delegate 'C1.myDelegate' requires an 'AddressOf' expression or lambda expression as the only argument to its constructor. d1 = New C1.myDelegate(,) ~~~ BC32008: Delegate 'C1.myDelegate' requires an 'AddressOf' expression or lambda expression as the only argument to its constructor. d1 = New C1.myDelegate(,,23) ~~~~~~ </expected>) End Sub <Fact()> Public Sub BC32008ERR_NoDirectDelegateConstruction1_2() Dim source = <compilation name="NewDelegateWithAddressOf"> <file name="a.vb"> Imports System Delegate Sub D() Module Program Sub Main(args As String()) Dim x As D x = New D(AddressOf Method, 23) x = New D(AddressOf Method, foo:=23) x = New D(bar:=AddressOf Method, foo:=23) x = New D(bar:=AddressOf Method, bar:=23) x = New D() x = New D(23) x = New D(nothing) x = New D Dim y1 as New D(AddressOf Method, 23) Dim y2 as New D(AddressOf Method, foo:=23) Dim y3 as New D(bar:=AddressOf Method, foo:=23) Dim y4 as New D(bar:=AddressOf Method, bar:=23) Dim y5 as New D() Dim y6 as New D(23) Dim y7 as New D(nothing) Dim y8 as New D End Sub Public Sub Method() console.writeline("Hello.") End Sub End Module </file> </compilation> Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) CompilationUtils.AssertTheseDiagnostics(c1, <expected> BC32008: Delegate 'D' requires an 'AddressOf' expression or lambda expression as the only argument to its constructor. x = New D(AddressOf Method, 23) ~~~~~~~~~~~~~~~~~~~~~~ BC32008: Delegate 'D' requires an 'AddressOf' expression or lambda expression as the only argument to its constructor. x = New D(AddressOf Method, foo:=23) ~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC32008: Delegate 'D' requires an 'AddressOf' expression or lambda expression as the only argument to its constructor. x = New D(bar:=AddressOf Method, foo:=23) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC32008: Delegate 'D' requires an 'AddressOf' expression or lambda expression as the only argument to its constructor. x = New D(bar:=AddressOf Method, bar:=23) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC32008: Delegate 'D' requires an 'AddressOf' expression or lambda expression as the only argument to its constructor. x = New D() ~~ BC32008: Delegate 'D' requires an 'AddressOf' expression or lambda expression as the only argument to its constructor. x = New D(23) ~~~~ BC32008: Delegate 'D' requires an 'AddressOf' expression or lambda expression as the only argument to its constructor. x = New D(nothing) ~~~~~~~~~ BC32008: Delegate 'D' requires an 'AddressOf' expression or lambda expression as the only argument to its constructor. x = New D ~~~~~ BC32008: Delegate 'D' requires an 'AddressOf' expression or lambda expression as the only argument to its constructor. Dim y1 as New D(AddressOf Method, 23) ~~~~~~~~~~~~~~~~~~~~~~ BC32008: Delegate 'D' requires an 'AddressOf' expression or lambda expression as the only argument to its constructor. Dim y2 as New D(AddressOf Method, foo:=23) ~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC32008: Delegate 'D' requires an 'AddressOf' expression or lambda expression as the only argument to its constructor. Dim y3 as New D(bar:=AddressOf Method, foo:=23) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC32008: Delegate 'D' requires an 'AddressOf' expression or lambda expression as the only argument to its constructor. Dim y4 as New D(bar:=AddressOf Method, bar:=23) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC32008: Delegate 'D' requires an 'AddressOf' expression or lambda expression as the only argument to its constructor. Dim y5 as New D() ~~ BC32008: Delegate 'D' requires an 'AddressOf' expression or lambda expression as the only argument to its constructor. Dim y6 as New D(23) ~~~~ BC32008: Delegate 'D' requires an 'AddressOf' expression or lambda expression as the only argument to its constructor. Dim y7 as New D(nothing) ~~~~~~~~~ BC32008: Delegate 'D' requires an 'AddressOf' expression or lambda expression as the only argument to its constructor. Dim y8 as New D ~~~~~ </expected>) End Sub <Fact()> Public Sub BC32010ERR_AttrAssignmentNotFieldOrProp1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="AttrAssignmentNotFieldOrProp1"> <file name="at32010.vb"><![CDATA[ Imports System <AttributeUsage(AttributeTargets.All)> Public Class MyAttribute Inherits Attribute Public Enum E Zero One End Enum Public Sub S() End Sub Public Function F!() Return 0.0F End Function End Class <My(E:=E.One, S:=Nothing)> Class Foo <My(F!:=1.234F)> Public Sub S2() End Sub End Class ]]></file> </compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_NameNotDeclared1, "E").WithArguments("E"), Diagnostic(ERRID.ERR_AttrAssignmentNotFieldOrProp1, "E").WithArguments("E"), Diagnostic(ERRID.ERR_AttrAssignmentNotFieldOrProp1, "S").WithArguments("S"), Diagnostic(ERRID.ERR_AttrAssignmentNotFieldOrProp1, "F!").WithArguments("F")) End Sub <Fact()> Public Sub BC32013ERR_StrictDisallowsObjectComparison1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="StrictDisallowsObjectComparison1"> <file name="a.vb"> Option Strict On Class C1 Sub scen1() Dim Obj As Object = New Object Select Case obj Case "DFT" End Select End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC32013: Option Strict On disallows operands of type Object for operator '='. Use the 'Is' operator to test for object identity. Select Case obj ~~~ </expected>) End Sub <Fact()> Public Sub BC32013ERR_StrictDisallowsObjectComparison1_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="StrictDisallowsObjectComparison1"> <file name="a.vb"> Option Strict On Class C1 Sub scen1() Dim Obj As Object = New Object if (obj="string") End If End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC32013: Option Strict On disallows operands of type Object for operator '='. Use the 'Is' operator to test for object identity. if (obj="string") ~~~ </expected>) End Sub <Fact()> Public Sub BC32014ERR_NoConstituentArraySizes() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="NoConstituentArraySizes"> <file name="a.vb"> Option Strict On Imports System Module Module1 Sub Main() Dim arr10 As Integer(,) = New Integer(9)(5) {} ' Invalid End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30414: Value of type 'Integer()()' cannot be converted to 'Integer(*,*)' because the array types have different numbers of dimensions. Dim arr10 As Integer(,) = New Integer(9)(5) {} ' Invalid ~~~~~~~~~~~~~~~~~~~~ BC32014: Bounds can be specified only for the top-level array when initializing an array of arrays. Dim arr10 As Integer(,) = New Integer(9)(5) {} ' Invalid ~ </expected>) End Sub <WorkItem(545621, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545621")> <Fact()> Public Sub BC32014ERR_NoConstituentArraySizes1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="NoConstituentArraySizes"> <file name="a.vb"> Module M Sub Main() Dim x()(1)() End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42024: Unused local variable: 'x'. Dim x()(1)() ~ BC32014: Bounds can be specified only for the top-level array when initializing an array of arrays. Dim x()(1)() ~ </expected>) End Sub <WorkItem(528729, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528729")> <Fact()> Public Sub BC32016ERR_FunctionResultCannotBeIndexed1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="FunctionResultCannotBeIndexed1"> <file name="a.vb"> Imports Microsoft.VisualBasic.FileSystem Module M1 Sub foo() If FreeFile(1) &lt; 255 Then End If End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC32016: 'Public Function FreeFile() As Integer' has no parameters and its return type cannot be indexed. If FreeFile(1) &lt; 255 Then ~~~~~~~~ </expected>) End Sub <Fact, WorkItem(543658, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543658")> Public Sub BC32021ERR_NamedArgAlsoOmitted2() CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="NamedArgAlsoOmitted2"> <file name="a.vb"> Public Module M1 Public Sub foo(ByVal X As Byte, Optional ByVal Y As Byte = 0, _ Optional ByVal Z As Byte = 0) Call foo(6, , Y:=3) End Sub End Module </file> </compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_NamedArgAlsoOmitted2, "Y").WithArguments("Y", "Public Sub foo(X As Byte, [Y As Byte = 0], [Z As Byte = 0])")) End Sub <Fact()> Public Sub BC32022ERR_CannotCallEvent1() CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="CannotCallEvent1"> <file name="a.vb"> Public Module M1 Public Event BurnPercent(ByVal Percent As Integer) Sub foo() BurnPercent.Invoke() End Sub End Module </file> </compilation>).AssertTheseDiagnostics( <expected> BC32022: 'Public Event BurnPercent(Percent As Integer)' is an event, and cannot be called directly. Use a 'RaiseEvent' statement to raise an event. BurnPercent.Invoke() ~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC32022ERR_CannotCallEvent1_2() CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Class C Private Event E As System.EventHandler Sub M(o As Object) E() M(E()) End Sub End Class </file> </compilation>).AssertTheseDiagnostics( <expected> BC32022: 'Private Event E As EventHandler' is an event, and cannot be called directly. Use a 'RaiseEvent' statement to raise an event. E() ~ BC32022: 'Private Event E As EventHandler' is an event, and cannot be called directly. Use a 'RaiseEvent' statement to raise an event. M(E()) ~ </expected>) End Sub <Fact()> Public Sub BC32023ERR_ForEachCollectionDesignPattern1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ForEachCollectionDesignPattern1"> <file name="a.vb"> Option Infer On Public Module M1 Sub foo() Dim s As Integer For Each i In s Next End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC32023: Expression is of type 'Integer', which is not a collection type. For Each i In s ~ </expected>) End Sub <Fact()> Public Sub BC32023ERR_ForEachCollectionDesignPattern1_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="ForEachCollectionDesignPattern1"> <file name="a.vb"> Option Infer On Class C Shared Sub Main() For Each x As Integer In If(x, x, x) Next End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC32023: Expression is of type 'Integer', which is not a collection type. For Each x As Integer In If(x, x, x) ~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC32023ERR_ForEachCollectionDesignPattern1_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="ForEachCollectionDesignPattern1"> <file name="a.vb"> Option Infer On Class C Public Shared Sub Main() Dim e As New Enumerable() For Each x In e Next End Sub End Class Structure Enumerable Public i As Integer Public Sub GetEnumerator() i = i + 1 'Return New Enumerator() End Sub End Structure Structure Enumerator Private x As Integer Public ReadOnly Property Current() As Integer Get Return x End Get End Property Public Function MoveNext() As Boolean Return System.Threading.Interlocked.Increment(x) &lt; 4 End Function End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC32023: Expression is of type 'Enumerable', which is not a collection type. For Each x In e ~ </expected>) End Sub <Fact()> Public Sub BC32023ERR_ForEachCollectionDesignPattern1_3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="ForEachCollectionDesignPattern1"> <file name="a.vb"> Option Infer On Class C Public Shared Sub Main() Dim e As New Enumerable() For Each x In e Next End Sub End Class Structure Enumerable Public i As Integer private Function GetEnumerator() as Enumerator i = i + 1 Return New Enumerator() End Function End Structure Structure Enumerator Private x As Integer Public ReadOnly Property Current() As Integer Get Return x End Get End Property Public Function MoveNext() As Boolean Return System.Threading.Interlocked.Increment(x) &lt; 4 End Function End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC32023: Expression is of type 'Enumerable', which is not a collection type. For Each x In e ~ </expected>) End Sub <Fact()> Public Sub BC32023ERR_ForEachCollectionDesignPattern1_4() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="ForEachCollectionDesignPattern1"> <file name="a.vb"> Option Infer On Class C Public Shared Sub Main() Dim e As New Enumerable() For Each x In e Next End Sub End Class Structure Enumerable Public i As Integer End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC32023: Expression is of type 'Enumerable', which is not a collection type. For Each x In e ~ </expected>) End Sub <Fact()> Public Sub BC32029ERR_StrictArgumentCopyBackNarrowing3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="StrictArgumentCopyBackNarrowing3"> <file name="a.vb"> Option Strict On Class C1 Public intDataField As Integer Dim type1 As MyType Sub Main() Dim str1 As String Scen1(intDataField) Scen1(type1.intField) scen3(str1) scen3(type1) End Sub Sub Scen1(ByRef xx As Long) End Sub Sub Scen2(ByRef gg As Byte) End Sub Sub scen3(ByRef gg As Object) End Sub End Class Structure MyType Public intField As Short End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC32029: Option Strict On disallows narrowing from type 'Long' to type 'Integer' in copying the value of 'ByRef' parameter 'xx' back to the matching argument. Scen1(intDataField) ~~~~~~~~~~~~ BC32029: Option Strict On disallows narrowing from type 'Long' to type 'Short' in copying the value of 'ByRef' parameter 'xx' back to the matching argument. Scen1(type1.intField) ~~~~~~~~~~~~~~ BC32029: Option Strict On disallows narrowing from type 'Object' to type 'String' in copying the value of 'ByRef' parameter 'gg' back to the matching argument. scen3(str1) ~~~~ BC42104: Variable 'str1' is used before it has been assigned a value. A null reference exception could result at runtime. scen3(str1) ~~~~ BC32029: Option Strict On disallows narrowing from type 'Object' to type 'MyType' in copying the value of 'ByRef' parameter 'gg' back to the matching argument. scen3(type1) ~~~~~ </expected>) End Sub <Fact()> Public Sub BC32036ERR_NoUniqueConstructorOnBase2() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="NoUniqueConstructorOnBase2"> <file name="a.vb"> Class Base Sub New() End Sub Sub New(ByVal ParamArray a() As Integer) End Sub End Class Class Derived Inherits Base End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC32036: Class 'Derived' must declare a 'Sub New' because its base class 'Base' has more than one accessible 'Sub New' that can be called with no arguments. Class Derived ~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC32038ERR_RequiredNewCallTooMany2() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="RequiredNewCallTooMany2"> <file name="a.vb"> Class Base Sub New() End Sub Sub New(ByVal ParamArray a() As Integer) End Sub End Class Class Derived Inherits Base Sub New() End Sub End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC32038: First statement of this 'Sub New' must be a call to 'MyBase.New' or 'MyClass.New' because base class 'Base' of 'Derived' has more than one accessible 'Sub New' that can be called with no arguments. Sub New() ~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC32039ERR_ForCtlVarArraySizesSpecified() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="ForCtlVarArraySizesSpecified"> <file name="a.vb"> Imports System.Collections.Generic Class C1 Sub New() Dim arrayList As New List(Of Integer()) For Each listElement() As Integer In arrayList For Each listElement(1) As Integer In arrayList Next Next End Sub End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC30616: Variable 'listElement' hides a variable in an enclosing block. For Each listElement(1) As Integer In arrayList ~~~~~~~~~~~~~~ BC32039: Array declared as for loop control variable cannot be declared with an initial size. For Each listElement(1) As Integer In arrayList ~~~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC32045ERR_TypeOrMemberNotGeneric1() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="TypeOrMemberNotGeneric1"> <file name="a.vb"> Class Base(Of u) sub fun1(ByRef b1 As Integer) End sub End Class Class Derived(Of v) Inherits Base(Of v) Overloads sub fun1(Of T) (ByVal t1 As T, ByVal ParamArray t2() As UInteger) End sub End Class Friend Module M1F Sub FOO() Dim c1 As New Base(Of String) c1.fun1(Of Base(Of String)) (4.4@) End Sub End Module </file> </compilation>) Dim expectedErrors1 = <errors> BC32045: 'Public Sub fun1(ByRef b1 As Integer)' has no type parameters and so cannot have type arguments. c1.fun1(Of Base(Of String)) (4.4@) ~~~~~~~~~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC32045ERR_TypeOrMemberNotGeneric1_1() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="TypeOrMemberNotGeneric1"> <file name="a.vb"> Class Base(Of u) sub fun1(ByRef b1 As Integer) End sub End Class Class Derived(Of v) Inherits Base(Of v) Overloads sub fun1(Of T) (ByVal t1 As T, ByVal ParamArray t2() As UInteger) End sub End Class Friend Module M1F Sub FOO() Dim c1 As New Base(Of String) c1.fun1(Of Derived(Of String)) (3.3!, Nothing) End Sub End Module </file> </compilation>) Dim expectedErrors1 = <errors> BC32045: 'Public Sub fun1(ByRef b1 As Integer)' has no type parameters and so cannot have type arguments. c1.fun1(Of Derived(Of String)) (3.3!, Nothing) ~~~~~~~~~~~~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC32045ERR_TypeOrMemberNotGeneric1_2() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="TypeOrMemberNotGeneric1"> <file name="a.vb"> Class Base(Of u) sub fun1(ByRef b1 As Integer) End sub End Class Class Derived(Of v) Inherits Base(Of v) Overloads sub fun1(Of T) (ByVal t1 As T, ByVal ParamArray t2() As UInteger) End sub End Class Friend Module M1F Sub FOO() Dim c1 As New Base(Of String) c1.fun1(Of System.ValueType) (4.4@, 3US) End Sub End Module </file> </compilation>) Dim expectedErrors1 = <errors> BC32045: 'Public Sub fun1(ByRef b1 As Integer)' has no type parameters and so cannot have type arguments. c1.fun1(Of System.ValueType) (4.4@, 3US) ~~~~~~~~~~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC32045ERR_TypeOrMemberNotGeneric1_3() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="TypeOrMemberNotGeneric1"> <file name="a.vb"> Class Base(Of u) sub fun1(ByRef b1 As Integer) End sub End Class Class Derived(Of v) Inherits Base(Of v) Overloads sub fun1(Of T) (ByVal t1 As T, ByVal ParamArray t2() As UInteger) End sub End Class Friend Module M1F Sub FOO() Dim c1 As Base(Of String) = New Derived(Of String) c1.fun1(Of System.ValueType) (3@) End Sub End Module </file> </compilation>) Dim expectedErrors1 = <errors> BC32045: 'Public Sub fun1(ByRef b1 As Integer)' has no type parameters and so cannot have type arguments. c1.fun1(Of System.ValueType) (3@) ~~~~~~~~~~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC32045ERR_TypeOrMemberNotGeneric1_4() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="TypeOrMemberNotGeneric1"> <file name="a.vb"> Class Base(Of u) sub fun1(ByRef b1 As Integer) End sub End Class Class Derived(Of v) Inherits Base(Of v) Overloads sub fun1(Of T) (ByVal t1 As T, ByVal ParamArray t2() As UInteger) End sub End Class Friend Module M1F Sub FOO() Dim c1 As Base(Of String) = New Derived(Of String) c1.fun1(Of System.Delegate) ("c"c, 3@) End Sub End Module </file> </compilation>) Dim expectedErrors1 = <errors> BC32045: 'Public Sub fun1(ByRef b1 As Integer)' has no type parameters and so cannot have type arguments. c1.fun1(Of System.Delegate) ("c"c, 3@) ~~~~~~~~~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC32046ERR_NewIfNullOnGenericParam() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Structure S(Of T, U As New) Sub M(Of V)() Dim o o = New T() o = New U() o = New V() End Sub End Structure Class C(Of T1 As Structure, T2 As Class) Sub M(Of T3 As Structure, T4 As {Class, New})() Dim o o = New T1() o = New T2() o = New T3() o = New T4() End Sub End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC32046: 'New' cannot be used on a type parameter that does not have a 'New' constraint. o = New T() ~ BC32046: 'New' cannot be used on a type parameter that does not have a 'New' constraint. o = New V() ~ BC32046: 'New' cannot be used on a type parameter that does not have a 'New' constraint. o = New T2() ~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC32050ERR_UnboundTypeParam2() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="UnboundTypeParam2"> <file name="a.vb"> Option Strict Off Public Module M Sub Main() Foo(AddressOf Bar) End Sub Sub Foo(Of T)(ByVal a As System.Action(Of T)) End Sub Sub Bar(ByVal x As String) End Sub End Module </file> </compilation>) Dim expectedErrors1 = <errors> BC32050: Type parameter 'T' for 'Public Sub Foo(Of T)(a As Action(Of T))' cannot be inferred. Foo(AddressOf Bar) ~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC32052ERR_IsOperatorGenericParam1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Interface I End Interface Class A End Class Class B(Of T As Structure) End Class Class C(Of T) Shared o As Object Shared Sub M1(Of T1)(_1 As T1) If _1 Is o Then End If If o Is _1 Then End If End Sub Shared Sub M2(Of T2 As Class)(_2 As T2) If _2 Is o Then End If If o Is _2 Then End If End Sub Shared Sub M3(Of T3 As Structure)(_3 As T3) If _3 Is o Then End If If o Is _3 Then End If End Sub Shared Sub M4(Of T4 As New)(_4 As T4) If _4 Is o Then End If If o Is _4 Then End If End Sub Shared Sub M5(Of T5 As I)(_5 As T5) If _5 Is o Then End If If o Is _5 Then End If End Sub Shared Sub M6(Of T6 As A)(_6 As T6) If _6 Is o Then End If If o Is _6 Then End If End Sub Shared Sub M7(Of T7 As U, U)(_7 As T7) If _7 Is o Then End If If o Is _7 Then End If End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC32052: 'Is' operand of type 'T1' can be compared only to 'Nothing' because 'T1' is a type parameter with no class constraint. If _1 Is o Then ~~ BC32052: 'Is' operand of type 'T1' can be compared only to 'Nothing' because 'T1' is a type parameter with no class constraint. If o Is _1 Then ~~ BC30020: 'Is' operator does not accept operands of type 'T3'. Operands must be reference or nullable types. If _3 Is o Then ~~ BC30020: 'Is' operator does not accept operands of type 'T3'. Operands must be reference or nullable types. If o Is _3 Then ~~ BC32052: 'Is' operand of type 'T4' can be compared only to 'Nothing' because 'T4' is a type parameter with no class constraint. If _4 Is o Then ~~ BC32052: 'Is' operand of type 'T4' can be compared only to 'Nothing' because 'T4' is a type parameter with no class constraint. If o Is _4 Then ~~ BC32052: 'Is' operand of type 'T5' can be compared only to 'Nothing' because 'T5' is a type parameter with no class constraint. If _5 Is o Then ~~ BC32052: 'Is' operand of type 'T5' can be compared only to 'Nothing' because 'T5' is a type parameter with no class constraint. If o Is _5 Then ~~ BC32052: 'Is' operand of type 'T7' can be compared only to 'Nothing' because 'T7' is a type parameter with no class constraint. If _7 Is o Then ~~ BC32052: 'Is' operand of type 'T7' can be compared only to 'Nothing' because 'T7' is a type parameter with no class constraint. If o Is _7 Then ~~ </expected>) End Sub <Fact()> Public Sub BC32059ERR_OnlyNullLowerBound() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="IsOperatorGenericParam1"> <file name="a.vb"> Option Infer On Module M Sub Main() Dim arr1(0 To 0, 0 To -1) As Integer Dim arr3(-1 To 0, 0 To -1) As Integer 'Invalid Dim arr4(0 To 1, -1 To 0) As Integer 'Invalid Dim arr5(0D To 1, 0.0 To 0) As Integer 'Invalid Dim arr6(0! To 1, 0.0 To 0) As Integer 'Invalid End Sub End Module </file> </compilation>) Dim expectedErrors1 = <errors> BC32059: Array lower bounds can be only '0'. Dim arr3(-1 To 0, 0 To -1) As Integer 'Invalid ~~ BC32059: Array lower bounds can be only '0'. Dim arr4(0 To 1, -1 To 0) As Integer 'Invalid ~~ BC32059: Array lower bounds can be only '0'. Dim arr5(0D To 1, 0.0 To 0) As Integer 'Invalid ~~ BC32059: Array lower bounds can be only '0'. Dim arr5(0D To 1, 0.0 To 0) As Integer 'Invalid ~~~ BC32059: Array lower bounds can be only '0'. Dim arr6(0! To 1, 0.0 To 0) As Integer 'Invalid ~~ BC32059: Array lower bounds can be only '0'. Dim arr6(0! To 1, 0.0 To 0) As Integer 'Invalid ~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <WorkItem(542204, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542204")> <Fact()> Public Sub BC32079ERR_TypeParameterDisallowed() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> <![CDATA[ Imports System Class AttrCls1 Inherits Attribute Sub New(ByVal p As Type) End Sub End Class Structure S1(Of T) Dim i As Integer <AttrCls1(GetType(T))> _ Class Cls1 End Class End Structure ]]></file> </compilation>) Dim expectedErrors1 = <errors><![CDATA[ BC32079: Type parameters or types constructed with type parameters are not allowed in attribute arguments. <AttrCls1(GetType(T))> _ ~ ]]></errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <WorkItem(542204, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542204")> <Fact()> Public Sub BC32079ERR_OpenTypeDisallowed() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> <![CDATA[ Imports System Class AttrCls1 Inherits Attribute Sub New(ByVal p As Type) End Sub End Class Structure S1(Of T) Dim i As Integer <AttrCls1(GetType(S1(Of T)))> _ Class A End Class <AttrCls1(GetType(S1(Of T).A()))> _ Class B End Class End Structure ]]></file> </compilation>) Dim expectedErrors1 = <errors><![CDATA[ BC32079: Type parameters or types constructed with type parameters are not allowed in attribute arguments. <AttrCls1(GetType(S1(Of T)))> _ ~~~~~~~~ BC32079: Type parameters or types constructed with type parameters are not allowed in attribute arguments. <AttrCls1(GetType(S1(Of T).A()))> _ ~~~~~~~~~~~~ ]]></errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC32085ERR_NewArgsDisallowedForTypeParam() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="NewArgsDisallowedForTypeParam"> <file name="a.vb"> Module M1 Sub Sub1(Of T As New)(ByVal a As T) a = New T() a = New T(2) a = New T( 2, 3, 4 ) End Sub End Module </file> </compilation>) Dim expectedErrors1 = <errors> BC32085: Arguments cannot be passed to a 'New' used on a type parameter. a = New T(2) ~ BC32085: Arguments cannot be passed to a 'New' used on a type parameter. a = New T( 2, 3, ~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC32087ERR_NoTypeArgumentCountOverloadCand1() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="NoTypeArgumentCountOverloadCand1"> <file name="a.vb"> Option Strict Off Module M Sub Main() Dim x As Object = New Object() x.Equals(Of Integer)() x.Equals(Of Integer) = 1 End Sub End Module </file> </compilation>) Dim expectedErrors1 = <errors> BC32087: Overload resolution failed because no accessible 'Equals' accepts this number of type arguments. x.Equals(Of Integer)() ~~~~~~~~~~~~~~~~~~ BC32087: Overload resolution failed because no accessible 'Equals' accepts this number of type arguments. x.Equals(Of Integer) = 1 ~~~~~~~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC32096ERR_ForEachAmbiguousIEnumerable1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Option Strict On Imports System.Collections Imports System.Collections.Generic Class C1 Implements IEnumerable(Of String), IEnumerable(Of Integer) Public Function GetEnumerator_int() As IEnumerator(Of integer) Implements IEnumerable(Of integer).GetEnumerator Return Nothing End Function Public Function GetEnumerator_str() As IEnumerator(Of String) Implements IEnumerable(Of String).GetEnumerator Return Nothing End Function Public Function GetEnumerator1_str() As IEnumerator Implements IEnumerable.GetEnumerator Return Nothing End Function End Class Class C Shared Sub M(Of T1 As C1)(p As T1) For Each o As T1 In p Next End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC32096: 'For Each' on type 'T1' is ambiguous because the type implements multiple instantiations of 'System.Collections.Generic.IEnumerable(Of T)'. For Each o As T1 In p ~ </expected>) End Sub <WorkItem(3420, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub BC32095ERR_ArrayOfRawGenericInvalid() Dim code = <![CDATA[ Class C1(Of T) End Class Class C2 Public Sub Main() Dim x = GetType(C1(Of )()) End Sub End Class ]]>.Value ParseAndVerify(code, <errors> <error id="32095"/> </errors>) End Sub <WorkItem(543616, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543616")> <Fact()> Public Sub BC32096ERR_ForEachAmbiguousIEnumerable1_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="AmbiguousAcrossInterfaces3"> <file name="a.vb"> Imports System.Collections.Generic Class C Public Shared Sub Main() End Sub End Class Public Class C(Of T As {IEnumerable(Of Integer), IEnumerable(Of String)}) Public Shared Sub TestForeach(t As T) For Each i As Integer In t Next End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC32096: 'For Each' on type 'T' is ambiguous because the type implements multiple instantiations of 'System.Collections.Generic.IEnumerable(Of T)'. For Each i As Integer In t ~ </expected>) ' used to report, but this changed now ' "BC30685: 'GetEnumerator' is ambiguous across the inherited interfaces 'System.Collections.Generic.IEnumerable(Of Integer)' ' and 'System.Collections.Generic.IEnumerable(Of String)'." End Sub <Fact()> Public Sub BC32097ERR_IsNotOperatorGenericParam1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Interface I End Interface Class A End Class Class B(Of T As Structure) End Class Class C(Of T) Shared o As Object Shared Sub M1(Of T1)(_1 As T1) If _1 IsNot o Then End If If o IsNot _1 Then End If End Sub Shared Sub M2(Of T2 As Class)(_2 As T2) If _2 IsNot o Then End If If o IsNot _2 Then End If End Sub Shared Sub M3(Of T3 As Structure)(_3 As T3) If _3 IsNot o Then End If If o IsNot _3 Then End If End Sub Shared Sub M4(Of T4 As New)(_4 As T4) If _4 IsNot o Then End If If o IsNot _4 Then End If End Sub Shared Sub M5(Of T5 As I)(_5 As T5) If _5 IsNot o Then End If If o IsNot _5 Then End If End Sub Shared Sub M6(Of T6 As A)(_6 As T6) If _6 IsNot o Then End If If o IsNot _6 Then End If End Sub Shared Sub M7(Of T7 As U, U)(_7 As T7) If _7 IsNot o Then End If If o IsNot _7 Then End If End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC32097: 'IsNot' operand of type 'T1' can be compared only to 'Nothing' because 'T1' is a type parameter with no class constraint. If _1 IsNot o Then ~~ BC32097: 'IsNot' operand of type 'T1' can be compared only to 'Nothing' because 'T1' is a type parameter with no class constraint. If o IsNot _1 Then ~~ BC31419: 'IsNot' requires operands that have reference types, but this operand has the value type 'T3'. If _3 IsNot o Then ~~ BC31419: 'IsNot' requires operands that have reference types, but this operand has the value type 'T3'. If o IsNot _3 Then ~~ BC32097: 'IsNot' operand of type 'T4' can be compared only to 'Nothing' because 'T4' is a type parameter with no class constraint. If _4 IsNot o Then ~~ BC32097: 'IsNot' operand of type 'T4' can be compared only to 'Nothing' because 'T4' is a type parameter with no class constraint. If o IsNot _4 Then ~~ BC32097: 'IsNot' operand of type 'T5' can be compared only to 'Nothing' because 'T5' is a type parameter with no class constraint. If _5 IsNot o Then ~~ BC32097: 'IsNot' operand of type 'T5' can be compared only to 'Nothing' because 'T5' is a type parameter with no class constraint. If o IsNot _5 Then ~~ BC32097: 'IsNot' operand of type 'T7' can be compared only to 'Nothing' because 'T7' is a type parameter with no class constraint. If _7 IsNot o Then ~~ BC32097: 'IsNot' operand of type 'T7' can be compared only to 'Nothing' because 'T7' is a type parameter with no class constraint. If o IsNot _7 Then ~~ </expected>) End Sub <Fact()> Public Sub BC32098ERR_TypeParamQualifierDisallowed() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="TypeParamQualifierDisallowed"> <file name="a.vb"> Class C1(Of T As DataHolder) Sub Main() T.Var1 = 4 End Sub End Class Class DataHolder Public Var1 As Integer End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC32098: Type parameters cannot be used as qualifiers. T.Var1 = 4 ~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact(), WorkItem(545050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545050")> Public Sub BC32126ERR_AddressOfNullableMethod() CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="AddressOfNullableMethod"> <file name="a.vb"> Imports System Module M Sub Main() Dim x As Integer? = Nothing Dim ef1 As Func(Of Integer) = AddressOf x.GetValueOrDefault Dim ef2 As Func(Of Integer, Integer) = AddressOf x.GetValueOrDefault End Sub End Module </file> </compilation>).VerifyDiagnostics( Diagnostic(ERRID.ERR_AddressOfNullableMethod, "x.GetValueOrDefault").WithArguments("Integer?", "AddressOf"), Diagnostic(ERRID.ERR_AddressOfNullableMethod, "x.GetValueOrDefault").WithArguments("Integer?", "AddressOf")) End Sub <Fact()> Public Sub BC32127ERR_IsOperatorNullable1() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="IsOperatorNullable1"> <file name="a.vb"> Module M1 Sub FOO() Dim s1_a As S1? = New S1() Dim s1_b As S1? = New S1() Dim B = s1_a Is s1_b End Sub End Module Structure S1 End Structure </file> </compilation>) Dim expectedErrors1 = <errors> BC32127: 'Is' operand of type 'S1?' can be compared only to 'Nothing' because 'S1?' is a nullable type. Dim B = s1_a Is s1_b ~~~~ BC32127: 'Is' operand of type 'S1?' can be compared only to 'Nothing' because 'S1?' is a nullable type. Dim B = s1_a Is s1_b ~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC32128ERR_IsNotOperatorNullable1() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="IsNotOperatorNullable1"> <file name="a.vb"> Module M1 Sub FOO() Dim s1_a As S1? = New S1() Dim s1_b As S1? = New S1() Dim B = s1_a IsNot s1_b End Sub End Module Structure S1 End Structure </file> </compilation>) Dim expectedErrors1 = <errors> BC32128: 'IsNot' operand of type 'S1?' can be compared only to 'Nothing' because 'S1?' is a nullable type. Dim B = s1_a IsNot s1_b ~~~~ BC32128: 'IsNot' operand of type 'S1?' can be compared only to 'Nothing' because 'S1?' is a nullable type. Dim B = s1_a IsNot s1_b ~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <WorkItem(545669, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545669")> <Fact()> Public Sub BC32303ERR_IllegalCallOrIndex() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="IllegalCallOrIndex"> <file name="a.vb"> Class C1 Function Foo1() as Object return nothing() ' Error End Function Function Foo2() as Object Return CType(Nothing, Object)() ' Error End Function Function Foo3() as Object Return DirectCast(TryCast(CType(Nothing, Object), C1), Object)() ' No error End Function Sub FOO4() Dim testVariable As Object = Nothing(1) End Sub Sub FOO5() Nothing() ' Error, but a parsing error End Sub End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC32303: Illegal call expression or index expression. return nothing() ' Error ~~~~~~~~~ BC32303: Illegal call expression or index expression. Return CType(Nothing, Object)() ' Error ~~~~~~~~~~~~~~~~~~~~~~~~ BC32303: Illegal call expression or index expression. Dim testVariable As Object = Nothing(1) ~~~~~~~~~~ BC30035: Syntax error. Nothing() ' Error, but a parsing error ~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC33009ERR_ParamArrayIllegal1() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="UnacceptableLogicalOperator3"> <file name="a.vb"> Delegate Sub FooDel1(ParamArray p() as Integer) Delegate Function FooDel2(ParamArray p() as Integer) as Byte Module M1 Sub Main() End Sub End Module </file> </compilation>) Dim expectedErrors1 = <errors> BC33009: 'Delegate' parameters cannot be declared 'ParamArray'. Delegate Sub FooDel1(ParamArray p() as Integer) ~~~~~~~~~~ BC33009: 'Delegate' parameters cannot be declared 'ParamArray'. Delegate Function FooDel2(ParamArray p() as Integer) as Byte ~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC33034ERR_UnacceptableLogicalOperator3() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="UnacceptableLogicalOperator3"> <file name="a.vb"> Imports System Class c1 End Class Class c2 Inherits c1 Shared Operator And(ByVal x As c2, ByVal y As c1) As c2 Return New c2 End Operator Shared Operator Or(ByVal x As c2, ByVal y As c2) As c2 Return New c2 End Operator End Class Module M1 Sub Main() Dim o1 As New c2, o2 As New c2, o As Object o = o1 AndAlso o2 o = o1 OrElse o2 End Sub End Module </file> </compilation>) Dim expectedErrors1 = <errors> BC33034: Return and parameter types of 'Public Shared Operator And(x As c2, y As c1) As c2' must be 'c2' to be used in a 'AndAlso' expression. o = o1 AndAlso o2 ~~~~~~~~~~~~~ BC33035: Type 'c2' must define operator 'IsTrue' to be used in a 'OrElse' expression. o = o1 OrElse o2 ~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC33037ERR_CopyBackTypeMismatch3() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="CopyBackTypeMismatch3"> <file name="a.vb"> Class c2 Shared Widening Operator CType(ByVal x As c2) As Integer Return 9 End Operator End Class Module M1 Sub FOO() Dim o As New c2 FOO(o) End Sub Sub foo(ByRef x As Integer) x = 99 End Sub End Module </file> </compilation>) compilation1.VerifyDiagnostics(Diagnostic(ERRID.ERR_CopyBackTypeMismatch3, "o").WithArguments("x", "Integer", "c2")) End Sub ' Roslyn extra errors (last 3) <Fact()> Public Sub BC33038ERR_ForLoopOperatorRequired2() CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ForLoopOperatorRequired2"> <file name="a.vb"> Class S1 Public Shared Widening Operator CType(ByVal x As Integer) As S1 Return Nothing End Operator Sub foo() Dim v As S1 For i = 1 To v Next End Sub End Class </file> </compilation>).VerifyDiagnostics( Diagnostic(ERRID.ERR_ForLoopOperatorRequired2, "For i = 1 To v").WithArguments("S1", "+"), Diagnostic(ERRID.ERR_ForLoopOperatorRequired2, "For i = 1 To v").WithArguments("S1", "-"), Diagnostic(ERRID.ERR_ForLoopOperatorRequired2, "For i = 1 To v").WithArguments("S1", "<="), Diagnostic(ERRID.ERR_ForLoopOperatorRequired2, "For i = 1 To v").WithArguments("S1", ">="), Diagnostic(ERRID.WRN_DefAsgUseNullRef, "v").WithArguments("v")) End Sub ' Roslyn extra errors (last 2) <Fact()> Public Sub BC33039ERR_UnacceptableForLoopOperator2() CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="UnacceptableForLoopOperator2"> <file name="a.vb"> Module M1 Class C1(Of t) Shared Widening Operator CType(ByVal p1 As C1(Of t)) As Integer Return 1 End Operator Shared Widening Operator CType(ByVal p1 As Integer) As C1(Of t) Return Nothing End Operator Shared Operator -(ByVal p1 As C1(Of t), ByVal p2 As C1(Of t)) As C1(Of Short) Return Nothing End Operator Shared Operator +(ByVal p1 As C1(Of t), ByVal p2 As C1(Of t)) As C1(Of Integer) Return Nothing End Operator End Class Sub foo() For i As C1(Of Integer) = 1 To 10 Next End Sub End Module </file> </compilation>).VerifyDiagnostics( Diagnostic(ERRID.ERR_UnacceptableForLoopOperator2, "For i As C1(Of Integer) = 1 To 10").WithArguments("Public Shared Operator -(p1 As M1.C1(Of Integer), p2 As M1.C1(Of Integer)) As M1.C1(Of Short)", "M1.C1(Of Integer)"), Diagnostic(ERRID.ERR_ForLoopOperatorRequired2, "For i As C1(Of Integer) = 1 To 10").WithArguments("M1.C1(Of Integer)", "<="), Diagnostic(ERRID.ERR_ForLoopOperatorRequired2, "For i As C1(Of Integer) = 1 To 10").WithArguments("M1.C1(Of Integer)", ">=")) End Sub <Fact()> Public Sub BC33107ERR_IllegalCondTypeInIIF() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="IllegalCondTypeInIIF"> <file name="a.vb"> Option Infer On Imports System Class S1 Sub foo() Dim choice1 = 4 Dim choice2 = 5 Dim booleanVar = True Console.WriteLine(If(choice1 &lt; choice2, 1)) Console.WriteLine(If(booleanVar, "Test returns True.")) End Sub End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC33107: First operand in a binary 'If' expression must be a nullable value type, a reference type, or an unconstrained generic type. Console.WriteLine(If(choice1 &lt; choice2, 1)) ~~~~~~~~~~~~~~~~~ BC33107: First operand in a binary 'If' expression must be a nullable value type, a reference type, or an unconstrained generic type. Console.WriteLine(If(booleanVar, "Test returns True.")) ~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC33100ERR_CantSpecifyNullableOnBoth() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="CantSpecifyNullableOnBoth"> <file name="a.vb"> Class C1 Sub foo() Dim z? As Integer? End Sub End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC42024: Unused local variable: 'z'. Dim z? As Integer? ~ BC33100: Nullable modifier cannot be specified on both a variable and its type. Dim z? As Integer? ~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC36006ERR_BadAttributeConstructor2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BadAttributeConstructor2"> <file name="a.vb"><![CDATA[ Imports System Public Class MyAttr Inherits Attribute Public Sub New(ByVal i As Integer, ByRef V As Integer) End Sub End Class <MyAttr(1, 1)> Public Class MyTest End Class ]]></file> </compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_BadAttributeConstructor2, "MyAttr").WithArguments("Integer")) End Sub <Fact()> Public Sub BC36009ERR_GotoIntoUsing() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="GotoIntoUsing"> <file name="a.vb"> Imports System Class C1 Sub foo() If (True) GoTo label1 End If Using o as IDisposable = nothing label1: End Using End Sub End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC36009: 'GoTo label1' is not valid because 'label1' is inside a 'Using' statement that does not contain this statement. GoTo label1 ~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC36010ERR_UsingRequiresDisposePattern() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="UsingRequiresDisposePattern"> <file name="a.vb"> Class [IsNot] Public i As Integer End Class Class C1 Sub FOO() Dim c1 as [IsNot] = nothing, c2 As [IsNot] = nothing Using c1 IsNot c2 End Using Using new [IsNot]() End Using Using c3 As New [IsNot]() End Using Using c4 As [IsNot] = new [IsNot]() End Using End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36010: 'Using' operand of type 'Boolean' must implement 'System.IDisposable'. Using c1 IsNot c2 ~~~~~~~~~~~ BC36010: 'Using' operand of type '[IsNot]' must implement 'System.IDisposable'. Using new [IsNot]() ~~~~~~~~~~~~~ BC36010: 'Using' operand of type '[IsNot]' must implement 'System.IDisposable'. Using c3 As New [IsNot]() ~~~~~~~~~~~~~~~~~~~ BC36010: 'Using' operand of type '[IsNot]' must implement 'System.IDisposable'. Using c4 As [IsNot] = new [IsNot]() ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC36011ERR_UsingResourceVarNeedsInitializer() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="UsingResourceVarNeedsInitializer"> <file name="a.vb"> Option Strict On Option Infer Off Option Explicit Off Imports System Class MyDisposable Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub End Class Class C1 Public Shared Sub Main() Using foo As MyDisposable Console.WriteLine("Inside Using.") End Using Using foo2 As New MyDisposable() Console.WriteLine("Inside Using.") End Using End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36011: 'Using' resource variable must have an explicit initialization. Using foo As MyDisposable ~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC36012ERR_UsingResourceVarCantBeArray() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="UsingResourceVarNeedsInitializer"> <file name="a.vb"> Option Strict On Option Infer Off Option Explicit Off Imports System Structure MyDisposable Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub End Structure Class C1 Public Shared Sub Main() Using foo?() As MyDisposable = Nothing Console.WriteLine("Inside Using.") End Using End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36012: 'Using' resource variable type can not be array type. Using foo?() As MyDisposable = Nothing ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC36532ERR_LambdaBindingMismatch1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="LambdaBindingMismatch1"> <file name="a.vb"> Option Strict Off Imports System Public Module M Sub Main() Dim x As Func(Of Exception, Object) = Function(y$) y End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36532: Nested function does not have the same signature as delegate 'Func(Of Exception, Object)'. Dim x As Func(Of Exception, Object) = Function(y$) y ~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC36533ERR_CannotLiftByRefParamQuery1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="CannotLiftByRefParamQuery1"> <file name="a.vb"> Option Strict Off Imports System.Linq Imports System.Collections.Generic Public Module M Sub RunQuery(ByVal collection As List(Of Integer), _ ByRef filterValue As Integer) Dim queryResult = From num In collection _ Where num &lt; filterValue End Sub End Module </file> </compilation>, {Net40.SystemCore}) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36533: 'ByRef' parameter 'filterValue' cannot be used in a query expression. Where num &lt; filterValue ~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC36534ERR_ExpressionTreeNotSupported_NoError() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="ExpressionTreeNotSupported"> <file name="a.vb"> Imports System.Runtime.CompilerServices Imports System.Linq.Expressions Imports System Module M Sub Main() Dim x As Expression(Of Func(Of Action)) = Function() AddressOf 0.Foo End Sub &lt;Extension()&gt; Sub Foo(ByVal x As Integer) x = Nothing End Sub End Module </file> </compilation>, {Net40.SystemCore}) CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) End Sub <Fact()> Public Sub BC36534ERR_ExpressionTreeNotSupported() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="ExpressionTreeNotSupported"> <file name="a.vb"> Imports System.Runtime.CompilerServices Imports System.Linq.Expressions Imports System Module M Sub Main() Dim a As Integer Dim x As Expression(Of Func(Of Action)) = Function() Sub() a = 1 End Sub End Module </file> </compilation>, {Net40.SystemCore}) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36534: Expression cannot be converted into an expression tree. Dim x As Expression(Of Func(Of Action)) = Function() Sub() a = 1 ~~~~~ </expected>) End Sub <Fact()> Public Sub BC36535ERR_CannotLiftStructureMeQuery() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndReferences( <compilation name="CannotLiftStructureMeQuery"> <file name="a.vb"> Option Infer On Imports System.Linq Structure S1 Sub test() Dim col = New Integer() {1, 2, 3} Dim x = From i In col Let j = Me End Sub End Structure </file> </compilation>, {Net40.SystemCore}) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36535: Instance members and 'Me' cannot be used within query expressions in structures. Dim x = From i In col Let j = Me ~~ </expected>) End Sub <Fact()> Public Sub BC36535ERR_CannotLiftStructureMeQuery_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndReferences( <compilation name="CannotLiftStructureMeQuery_2"> <file name="a.vb"> Option Infer On Imports System.Linq Structure S1 Sub test() Dim col = New Integer() {1, 2, 3} Dim x = From i In col Let j = MyClass.ToString() End Sub End Structure </file> </compilation>, {Net40.SystemCore}) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36535: Instance members and 'Me' cannot be used within query expressions in structures. Dim x = From i In col Let j = MyClass.ToString() ~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC36536ERR_InferringNonArrayType1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="InferringNonArrayType1"> <file name="a.vb"> Option Strict Off Option Infer On Module M Sub Main() Dim x() = 1 End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36536: Variable cannot be initialized with non-array type 'Integer'. Dim x() = 1 ~ BC30311: Value of type 'Integer' cannot be converted to 'Object()'. Dim x() = 1 ~ </expected>) End Sub <Fact()> Public Sub BC36538ERR_ByRefParamInExpressionTree() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="ByRefParamInExpressionTree"> <file name="a.vb"> Imports System Imports System.Linq.Expressions Structure S1 Sub test() Foo(Function(ByRef x As Double, y As Integer) 1.1) End Sub End Structure Module Module1 Delegate Function MyFunc(Of T)(ByRef x As T, ByVal y As T) As T Sub Foo(Of T)(ByVal x As Expression(Of MyFunc(Of T))) End Sub End Module </file> </compilation>, references:={Net40.SystemCore}) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36538: References to 'ByRef' parameters cannot be converted to an expression tree. Foo(Function(ByRef x As Double, y As Integer) 1.1) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC36547ERR_DuplicateAnonTypeMemberName1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="DuplicateAnonTypeMemberName1"> <file name="a.vb"> Module M Sub Main() Dim at1 = New With {"".ToString} Dim at2 = New With {Key .a = 1, .GetHashCode = "A"} End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36547: Anonymous type member or property 'ToString' is already declared. Dim at1 = New With {"".ToString} ~~~~~~~~~~~ BC36547: Anonymous type member or property 'GetHashCode' is already declared. Dim at2 = New With {Key .a = 1, .GetHashCode = "A"} ~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC36548ERR_BadAnonymousTypeForExprTree() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndReferences( <compilation name="BadAnonymousTypeForExprTree"> <file name="a.vb"> Imports System Imports System.Linq.Expressions Module M Sub Main() Dim x As Expression(Of Func(Of Object)) = Function() New With {.x = 1, .y = .x} End Sub End Module </file> </compilation>, {Net40.System, Net40.SystemCore, Net40.MicrosoftVisualBasic}) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36548: Cannot convert anonymous type to an expression tree because a property of the type is used to initialize another property. Dim x As Expression(Of Func(Of Object)) = Function() New With {.x = 1, .y = .x} ~~ </expected>) End Sub <Fact()> Public Sub BC36549ERR_CannotLiftAnonymousType1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="CannotLiftAnonymousType1"> <file name="a.vb"> Imports System.Linq Module M Dim x = New With {.y = 1, .z = From y In "" Select .y} End Module </file> </compilation>, {Net40.SystemCore}) CompilationUtils.AssertTheseEmitDiagnostics(compilation, <expected> BC36549: Anonymous type property 'y' cannot be used in the definition of a lambda expression within the same initialization list. Dim x = New With {.y = 1, .z = From y In "" Select .y} ~~ </expected>) End Sub <Fact()> Public Sub BC36557ERR_NameNotMemberOfAnonymousType2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="NameNotMemberOfAnonymousType2"> <file name="a.vb"> Structure S1 Sub test() Dim x = New With {.prop1 = New With {.prop2 = .prop1}} End Sub End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36557: 'prop1' is not a member of '&lt;anonymous type&gt;'; it does not exist in the current context. Dim x = New With {.prop1 = New With {.prop2 = .prop1}} ~~~~~~ </expected>) End Sub <Fact()> Public Sub BC36558ERR_ExtensionAttributeInvalid() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Namespace System.Runtime.CompilerServices <AttributeUsage(AttributeTargets.Method Or AttributeTargets.Property Or AttributeTargets.Class)> Public Class ExtensionAttribute Inherits Attribute End Class End Namespace <System.Runtime.CompilerServices.Extension()> ' 1 Module Program <System.Runtime.CompilerServices.Extension()> ' 2 Sub boo(n As String) End Sub <System.Runtime.CompilerServices.Extension()> ' 3 Delegate Sub b() Sub Main(args As String()) End Sub End Module <System.Runtime.CompilerServices.Extension()> ' 4 Class T <System.Runtime.CompilerServices.Extension()> ' 5 Sub boo(n As String) End Sub End Class ]]> </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> <![CDATA[ BC36558: The custom-designed version of 'System.Runtime.CompilerServices.ExtensionAttribute' found by the compiler is not valid. Its attribute usage flags must be set to allow assemblies, classes, and methods. <System.Runtime.CompilerServices.Extension()> ' 1 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36558: The custom-designed version of 'System.Runtime.CompilerServices.ExtensionAttribute' found by the compiler is not valid. Its attribute usage flags must be set to allow assemblies, classes, and methods. <System.Runtime.CompilerServices.Extension()> ' 2 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30662: Attribute 'ExtensionAttribute' cannot be applied to 'b' because the attribute is not valid on this declaration type. <System.Runtime.CompilerServices.Extension()> ' 3 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36558: The custom-designed version of 'System.Runtime.CompilerServices.ExtensionAttribute' found by the compiler is not valid. Its attribute usage flags must be set to allow assemblies, classes, and methods. <System.Runtime.CompilerServices.Extension()> ' 4 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36550: 'Extension' attribute can be applied only to 'Module', 'Sub', or 'Function' declarations. Class T ~ BC36551: Extension methods can be defined only in modules. <System.Runtime.CompilerServices.Extension()> ' 5 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36558: The custom-designed version of 'System.Runtime.CompilerServices.ExtensionAttribute' found by the compiler is not valid. Its attribute usage flags must be set to allow assemblies, classes, and methods. <System.Runtime.CompilerServices.Extension()> ' 5 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]> </expected>) End Sub <Fact()> Public Sub BC36559ERR_AnonymousTypePropertyOutOfOrder1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="AnonymousTypePropertyOutOfOrder1"> <file name="a.vb"> Imports System.Runtime.CompilerServices Module M Sub Foo() Dim x = New With {.X = .X} End Sub &lt;Extension()&gt; Function X(ByVal y As Object) As Object Return Nothing End Function End Module </file> </compilation>, {Net40.SystemCore}) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36559: Anonymous type member property 'X' cannot be used to infer the type of another member property because the type of 'X' is not yet established. Dim x = New With {.X = .X} ~~ </expected>) End Sub <Fact()> Public Sub BC36560ERR_AnonymousTypeDisallowsTypeChar() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="AnonymousTypeDisallowsTypeChar"> <file name="a.vb"> Imports System.Runtime.CompilerServices Module M Sub Foo() Dim anon1 = New With {.ID$ = "abc"} Dim anon2 = New With {.ID$ = 42} End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36560: Type characters cannot be used in anonymous type declarations. Dim anon1 = New With {.ID$ = "abc"} ~~~~~~~~~~~~ BC36560: Type characters cannot be used in anonymous type declarations. Dim anon2 = New With {.ID$ = 42} ~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC36564ERR_DelegateBindingTypeInferenceFails() CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="DelegateBindingTypeInferenceFails"> <file name="a.vb"> Option Strict Off Imports System Public Module M Sub Main() Dim k = {Sub() Console.WriteLine(), AddressOf Foo} End Sub Sub Foo(Of T)() End Sub End Module </file> </compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_DelegateBindingTypeInferenceFails, "Foo")) End Sub <Fact()> Public Sub BC36574ERR_AnonymousTypeNeedField() CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="AnonymousTypeNeedField"> <file name="a.vb"> Public Module M Sub Main() Dim anonInstance = New With {} End Sub End Module </file> </compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_AnonymousTypeNeedField, "{")) End Sub <Fact()> Public Sub BC36582ERR_TooManyArgs2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="TooManyArgs2"> <file name="a.vb"> Module M1 Function IntegerExtension(ByVal a As Integer) As Integer Dim x1 As Integer x1.FooGeneric01(1) return nothing End Function End Module Module Extension01 &lt;System.Runtime.CompilerServices.Extension()&gt; Sub FooGeneric01(Of T1)(ByVal o As T1) End Sub End Module </file> </compilation>, {Net40.SystemCore}) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36582: Too many arguments to extension method 'Public Sub FooGeneric01()' defined in 'Extension01'. x1.FooGeneric01(1) ~ </expected>) End Sub <Fact(), WorkItem(543658, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543658")> Public Sub BC36583ERR_NamedArgAlsoOmitted3() CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="NamedArgAlsoOmitted3"> <file name="a.vb"> Imports System.Runtime.CompilerServices Public Module M &lt;Extension()&gt; _ Public Sub ABC(ByVal X As Integer, Optional ByVal Y As Byte = 0, _ Optional ByVal Z As Byte = 0) End Sub Sub FOO() Dim number As Integer number.ABC(, 4, Y:=5) End Sub End Module </file> </compilation>, {Net40.SystemCore}).VerifyDiagnostics(Diagnostic(ERRID.ERR_NamedArgAlsoOmitted3, "Y").WithArguments("Y", "Public Sub ABC([Y As Byte = 0], [Z As Byte = 0])", "M")) End Sub <Fact()> Public Sub BC36584ERR_NamedArgUsedTwice3() CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="NamedArgUsedTwice3"> <file name="a.vb"> Imports System.Runtime.CompilerServices Public Module M &lt;Extension()&gt; _ Public Sub ABC(ByVal X As Integer, ByVal Y As Byte, _ Optional ByVal Z As Byte = 0) End Sub Sub FOO() Dim number As Integer number.ABC(1, Y:=4, Y:=5) End Sub End Module </file> </compilation>, {Net40.SystemCore}).VerifyDiagnostics(Diagnostic(ERRID.ERR_NamedArgUsedTwice3, "Y").WithArguments("Y", "Public Sub ABC(Y As Byte, [Z As Byte = 0])", "M"), Diagnostic(ERRID.ERR_NamedArgUsedTwice3, "Y").WithArguments("Y", "Public Sub ABC(Y As Byte, [Z As Byte = 0])", "M")) End Sub <Fact()> Public Sub BC36589ERR_UnboundTypeParam3() CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="UnboundTypeParam3"> <file name="a.vb"> Delegate Function Func1(Of T0, S)(ByVal arg1 As T0) As S Delegate Sub Func2s(Of T0, T1, S)(ByVal arg1 As T0, ByVal arg2 As T1) Class C1 Function [Select](ByVal sel As Func1(Of Integer, Integer)) As C1 Return Me End Function End Class Module M1 &lt;System.Runtime.CompilerServices.Extension()&gt; _ Function GroupJoin(Of TKey, TResult)(ByVal col As C1, ByVal coll2 As C1, ByVal key As Func1(Of Integer, TKey), ByVal key2 As Func1(Of Integer, TKey), ByVal resultSelector As Func2s(Of Integer, System.Collections.Generic.IEnumerable(Of Integer), TResult)) As System.Collections.Generic.IEnumerable(Of TResult) Return Nothing End Function End Module Module M2 Sub foo() Dim x = New C1 Dim y = From i In x Select i Group Join j In x On i Equals j Into G = Group, Count() End Sub End Module </file> </compilation>, {Net40.SystemCore}).VerifyDiagnostics(Diagnostic(ERRID.ERR_QueryOperatorNotFound, "Group Join").WithArguments("GroupJoin")) End Sub <Fact()> Public Sub BC36590ERR_TooFewGenericArguments2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="TooFewGenericArguments2"> <file name="a.vb"> Module M1 Sub foo() Dim x As cLSIfooClass(Of Integer) x.foo(Of String)("RR") End Sub End Module Module Extension01 &lt;System.Runtime.CompilerServices.Extension()&gt; Sub foo(Of T1, t2, t3)(ByVal o As T1, ByVal p As t2, ByVal q As t3) End Sub End Module Public Interface Ifoo(Of t) End Interface Class cLSIfooClass(Of T) Implements Ifoo(Of T) End Class </file> </compilation>, {Net40.SystemCore}) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42104: Variable 'x' is used before it has been assigned a value. A null reference exception could result at runtime. x.foo(Of String)("RR") ~ BC36590: Too few type arguments to extension method 'Public Sub foo(Of t2, t3)(p As t2, q As t3)' defined in 'Extension01'. x.foo(Of String)("RR") ~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC36591ERR_TooManyGenericArguments2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="TooManyGenericArguments2"> <file name="a.vb"> Module M1 Sub foo() Dim x As cLSIfooClass(Of Integer) x.foo(Of Integer, String)("RR") End Sub End Module Module Extension01 &lt;System.Runtime.CompilerServices.Extension()&gt; Sub foo(Of T1, t2)(ByVal o As Ifoo(Of T1), ByVal p As t2) End Sub End Module Public Interface Ifoo(Of t) End Interface Class cLSIfooClass(Of T) Implements Ifoo(Of T) End Class </file> </compilation>, {Net40.SystemCore}) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42104: Variable 'x' is used before it has been assigned a value. A null reference exception could result at runtime. x.foo(Of Integer, String)("RR") ~ BC36591: Too many type arguments to extension method 'Public Sub foo(Of t2)(p As t2)' defined in 'Extension01'. x.foo(Of Integer, String)("RR") ~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC36593ERR_ExpectedQueryableSource() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="ExpectedQueryableSource"> <file name="a.vb"> Structure S1 Public Sub GetData() Dim query = From number In Me End Sub End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36593: Expression of type 'S1' is not queryable. Make sure you are not missing an assembly reference and/or namespace import for the LINQ provider. Dim query = From number In Me ~~ </expected>) End Sub <Fact()> Public Sub BC36594ERR_QueryOperatorNotFound() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="QueryOperatorNotFound"> <file name="a.vb"> Imports System Imports System.Collections.Generic Imports System.Linq Module M Sub Main() Dim x = (Aggregate y In {Function(e) 1} Into y()) End Sub End Module </file> </compilation>, {Net40.SystemCore}) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36594: Definition of method 'y' is not accessible in this context. Dim x = (Aggregate y In {Function(e) 1} Into y()) ~ </expected>) End Sub <Fact()> Public Sub BC36597ERR_CannotGotoNonScopeBlocksWithClosure() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="CannotGotoNonScopeBlocksWithClosure"> <file name="a.vb"> Module M Sub BadGoto() Dim x = 0 If x > 5 Then Label1: Dim y = 5 Dim f = Function() y End If GoTo Label1 End Sub End Module </file> </compilation>) AssertTheseEmitDiagnostics(compilation, <expected> BC36597: 'Goto Label1' is not valid because 'Label1' is inside a scope that defines a variable that is used in a lambda or query expression. GoTo Label1 ~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC36599ERR_QueryAnonymousTypeFieldNameInference() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="QueryAnonymousTypeFieldNameInference"> <file name="a.vb"> Option Strict On Imports System.Linq Module M Sub Foo() From x In {""} Select x, Nothing End Sub End Module </file> </compilation>, {Net40.SystemCore}) compilation.VerifyDiagnostics( Diagnostic(ERRID.ERR_QueryAnonymousTypeFieldNameInference, "Nothing"), Diagnostic(ERRID.ERR_ExpectedProcedure, "From x In {""""} Select x, Nothing")) ' Extra in Roslyn & NOT in vbc End Sub <Fact()> Public Sub BC36600ERR_QueryDuplicateAnonTypeMemberName1() CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="QueryDuplicateAnonTypeMemberName1"> <file name="a.vb"> Option Strict On Imports System Imports System.Runtime.CompilerServices Imports System.Linq Module M Sub Foo() Dim y = From x In "" Group By x Into Bar(), Bar(1) End Sub &lt;Extension()&gt; Function Bar(ByVal x As Object, ByVal y As Func(Of Char, Object)) As String Return Nothing End Function &lt;Extension()&gt; Function Bar(ByVal x As Object) As String Return Nothing End Function End Module </file> </compilation>, {Net40.SystemCore}).VerifyDiagnostics( Diagnostic(ERRID.ERR_QueryDuplicateAnonTypeMemberName1, "Bar").WithArguments("Bar")) End Sub <Fact()> Public Sub BC36601ERR_QueryAnonymousTypeDisallowsTypeChar() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="QueryAnonymousTypeDisallowsTypeChar"> <file name="a.vb"> Option Infer On Imports System.Linq Module M Dim q = From x% In New Integer() {1} End Module </file> </compilation>, {Net40.SystemCore}) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36601: Type characters cannot be used in range variable declarations. Dim q = From x% In New Integer() {1} ~~ </expected>) End Sub <Fact()> Public Sub BC36602ERR_ReadOnlyInClosure() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="ReadOnlyInClosure"> <file name="a.vb"> Class Class1 ReadOnly m As Integer Sub New() Dim f = Function() Test(m) End Sub Function Test(ByRef n As Integer) As String Return Nothing End Function End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36602: 'ReadOnly' variable cannot be the target of an assignment in a lambda expression inside a constructor. Dim f = Function() Test(m) ~ </expected>) End Sub <Fact()> Public Sub BC36602ERR_ReadOnlyInClosure1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="ReadOnlyInClosure"> <file name="a.vb"> Class Class1 ReadOnly property m As Integer Sub New() Dim f = Function() Test(m) End Sub Function Test(ByRef n As Integer) As String Return Nothing End Function End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36602: 'ReadOnly' variable cannot be the target of an assignment in a lambda expression inside a constructor. Dim f = Function() Test(m) ~ </expected>) End Sub <Fact()> Public Sub BC36603ERR_ExprTreeNoMultiDimArrayCreation() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="ExprTreeNoMultiDimArrayCreation"> <file name="a.vb"> Imports System Imports System.Linq.Expressions Module M Sub Main() Dim ex As Expression(Of Func(Of Object)) = Function() {{1}} End Sub End Module </file> </compilation>, {Net40.SystemCore}) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36603: Multi-dimensional array cannot be converted to an expression tree. Dim ex As Expression(Of Func(Of Object)) = Function() {{1}} ~~~~~ </expected>) End Sub <Fact()> Public Sub BC36604ERR_ExprTreeNoLateBind() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="ExprTreeNoLateBind"> <file name="a.vb"> Imports System Imports System.Linq.Expressions Module M Sub Main() Dim ex As Expression(Of Func(Of Object, Object)) = Function(x) x.Foo End Sub End Module </file> </compilation>, {Net40.SystemCore}) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36604: Late binding operations cannot be converted to an expression tree. Dim ex As Expression(Of Func(Of Object, Object)) = Function(x) x.Foo ~~~~~ </expected>) End Sub <Fact()> Public Sub BC36606ERR_QueryInvalidControlVariableName1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndReferences( <compilation name="QueryInvalidControlVariableName1"> <file name="a.vb"> Option Infer On Imports System.Linq Class M Dim x = From y In "" Select ToString() End Class </file> </compilation>, {Net40.SystemCore}) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36606: Range variable name cannot match the name of a member of the 'Object' class. Dim x = From y In "" Select ToString() ~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC36610ERR_QueryNameNotDeclared() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(references:={Net40.SystemCore}, source:= <compilation name="QueryNameNotDeclared"> <file name="a.vb"> Imports System Imports System.Linq Module M Sub Main() Dim c = From x In {1} Group By y = 0, z = y Into Count() End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36610: Name 'y' is either not declared or not in the current scope. Dim c = From x In {1} Group By y = 0, z = y Into Count() ~ </expected>) End Sub <Fact()> Public Sub BC36614ERR_QueryAnonTypeFieldXMLNameInference() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Imports System.Xml.Linq Imports System.Collections.Generic Imports System.Linq Imports <xmlns:ns="5"> Imports <xmlns:n-s="b"> Module M1 Sub foo() Dim x = From i In (<ns:e <%= <ns:e><%= "hello" %></ns:e> %>></ns:e>.<ns:e>) _ Where i.Value <> (<<%= <ns:e></ns:e>.Name %>></>.Value) _ Select <e><%= i %></e>.<ns:e-e>, i End Sub End Module ]]></file> </compilation>, references:=XmlReferences) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC36614: Range variable name cannot be inferred from an XML identifier that is not a valid Visual Basic identifier. Select <e><%= i %></e>.<ns:e-e>, i ~~~ ]]></errors>) End Sub <Fact()> Public Sub BC36617ERR_TypeCharOnAggregation() CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="TypeCharOnAggregation"> <file name="a.vb"> Option Strict On Imports System.Runtime.CompilerServices Imports System Imports System.Linq Module M Sub Foo() Dim y = From x In "" Group By x Into Bar$(1) End Sub &lt;Extension()&gt; Function Bar$(ByVal x As Object, ByVal y As Func(Of Char, Object)) Return Nothing End Function End Module </file> </compilation>, {Net40.SystemCore}).VerifyDiagnostics(Diagnostic(ERRID.ERR_TypeCharOnAggregation, "Bar$"), Diagnostic(ERRID.ERR_QueryAnonymousTypeDisallowsTypeChar, "Bar$")) End Sub <Fact()> Public Sub BC36625ERR_LambdaNotDelegate1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="LambdaNotDelegate1"> <file name="a.vb"> Module LambdaSyntax Sub LambdaSyntax() If Function() True Then ElseIf Function(x As Boolean) x Then End If End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36625: Lambda expression cannot be converted to 'Boolean' because 'Boolean' is not a delegate type. If Function() True Then ~~~~~~~~~~~~~~~ BC36625: Lambda expression cannot be converted to 'Boolean' because 'Boolean' is not a delegate type. ElseIf Function(x As Boolean) x Then ~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC36628ERR_CannotInferNullableForVariable1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="CannotInferNullableForVariable1"> <file name="a.vb"> Option Infer on Imports System Module M Sub Foo() Dim except? = New Exception Dim obj? = New Object Dim stringVar? = "Open the application." End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36628: A nullable type cannot be inferred for variable 'except'. Dim except? = New Exception ~~~~~~ BC36628: A nullable type cannot be inferred for variable 'obj'. Dim obj? = New Object ~~~ BC36628: A nullable type cannot be inferred for variable 'stringVar'. Dim stringVar? = "Open the application." ~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC36633ERR_IterationVariableShadowLocal2() CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="IterationVariableShadowLocal2"> <file name="a.vb"> Option Explicit Off Imports System Imports System.Linq Imports System.Collections.Generic Module M1 &lt;System.Runtime.CompilerServices.Extension()&gt; _ Sub Show(Of T)(ByVal collection As IEnumerable(Of T)) For Each element In collection Console.WriteLine(element) Next End Sub Sub Scen1() implicit = 1 'COMPILEERROR : BC36633, "implicit" Dim x = From implicit In New Integer() {1, 2, 3} Let implicit = jj Select implicit 'COMPILEERROR : BC36633, "implicit" Dim y = From i In New Integer() {1, 2, 3} Let implicit = i Select implicit 'COMPILEERROR : BC36633, "implicit" Dim z = From i In New Integer() {1, 2, 3} Let j = implicit Select implicit 'COMPILEERROR : BC36633, "implicit" Dim u = From i In New Integer() {1, 2, 3} Let j = implicit Group i By i Into implicit = Group 'COMPILEERROR : BC36633, "implicit" Dim v = From i In New Integer() {1, 2, 3} Let j = implicit Group implicit By i Into implicit() 'COMPILEERROR : BC36633, "implicit" Dim w = From i In New Integer() {1, 2, 3} Let j = implicit Group i By implicit Into implicit() 'COMPILEERROR : BC36633, "implicit", BC36633, "implicit" Dim a = From i In New Integer() {1, 2, 3} Let j = implicit Group implicit By implicit Into implicit() 'COMPILEERROR : BC36633, "implicit" Dim b = From i In New Integer() {1, 2, 3}, j In New Integer() {1, 2, 3} Let k = implicit Group Join implicit In New Integer() {1, 2, 3} On i Equals implicit Into implicit() 'COMPILEERROR : BC36633, "implicit" Dim c = From i In New Integer() {1, 2, 3}, j In New Integer() {1, 2, 3} Let k = implicit Group Join l In New Integer() {1, 2, 3} On i Equals l Into implicit = Group End Sub Sub Scen2() 'COMPILEERROR : BC36633, "implicit", BC36633, "implicit" Dim x = From implicit In New Integer() {1, 2, 3} Let implicit = jj Select implicit 'COMPILEERROR : BC36633, "implicit", BC36633, "implicit" Dim y = From i In New Integer() {1, 2, 3} Let implicit = i Select implicit 'COMPILEERROR : BC36633, "implicit" Dim z = From i In New Integer() {1, 2, 3} Let j = implicit Select implicit 'COMPILEERROR : BC36633, "implicit" Dim u = From i In New Integer() {1, 2, 3} Let j = implicit Group i By i Into implicit = Group 'COMPILEERROR : BC36633, "implicit" Dim v = From i In New Integer() {1, 2, 3} Let j = implicit Group implicit By i Into implicit() 'COMPILEERROR : BC36633, "implicit" Dim w = From i In New Integer() {1, 2, 3} Let j = implicit Group i By implicit Into implicit() 'COMPILEERROR : BC36633, "implicit", BC36633, "implicit" Dim a = From i In New Integer() {1, 2, 3} Let j = implicit Group implicit By implicit Into implicit() 'COMPILEERROR : BC36633, "implicit" Dim b = From i In New Integer() {1, 2, 3}, j In New Integer() {1, 2, 3} Let k = implicit Group Join implicit In New Integer() {1, 2, 3} On i Equals implicit Into implicit() 'COMPILEERROR : BC36633, "implicit" Dim c = From i In New Integer() {1, 2, 3}, j In New Integer() {1, 2, 3} Let k = implicit Group Join l In New Integer() {1, 2, 3} On i Equals l Into implicit = Group implicit = 1 End Sub End Module </file> </compilation>, {Net40.SystemCore}).VerifyDiagnostics(Diagnostic(ERRID.ERR_IterationVariableShadowLocal2, "implicit").WithArguments("implicit"), Diagnostic(ERRID.ERR_IterationVariableShadowLocal2, "implicit").WithArguments("implicit"), Diagnostic(ERRID.ERR_IterationVariableShadowLocal2, "implicit").WithArguments("implicit"), Diagnostic(ERRID.ERR_IterationVariableShadowLocal2, "implicit").WithArguments("implicit"), Diagnostic(ERRID.ERR_IterationVariableShadowLocal2, "implicit").WithArguments("implicit"), Diagnostic(ERRID.ERR_IterationVariableShadowLocal2, "implicit").WithArguments("implicit"), Diagnostic(ERRID.ERR_IterationVariableShadowLocal2, "implicit").WithArguments("implicit"), Diagnostic(ERRID.ERR_IterationVariableShadowLocal2, "implicit").WithArguments("implicit"), Diagnostic(ERRID.ERR_QueryOperatorNotFound, "implicit").WithArguments("implicit"), Diagnostic(ERRID.ERR_IterationVariableShadowLocal2, "implicit").WithArguments("implicit"), Diagnostic(ERRID.ERR_IterationVariableShadowLocal2, "implicit").WithArguments("implicit"), Diagnostic(ERRID.ERR_QueryOperatorNotFound, "implicit").WithArguments("implicit"), Diagnostic(ERRID.ERR_QueryDuplicateAnonTypeMemberName1, "implicit").WithArguments("implicit"), Diagnostic(ERRID.ERR_IterationVariableShadowLocal2, "implicit").WithArguments("implicit"), Diagnostic(ERRID.ERR_IterationVariableShadowLocal2, "implicit").WithArguments("implicit"), Diagnostic(ERRID.ERR_QueryOperatorNotFound, "implicit").WithArguments("implicit"), Diagnostic(ERRID.ERR_QueryDuplicateAnonTypeMemberName1, "implicit").WithArguments("implicit"), Diagnostic(ERRID.ERR_IterationVariableShadowLocal2, "implicit").WithArguments("implicit"), Diagnostic(ERRID.ERR_QueryOperatorNotFound, "implicit").WithArguments("implicit"), Diagnostic(ERRID.ERR_IterationVariableShadowLocal2, "implicit").WithArguments("implicit"), Diagnostic(ERRID.ERR_IterationVariableShadowLocal2, "implicit").WithArguments("implicit"), Diagnostic(ERRID.WRN_DefAsgUseNullRef, "jj").WithArguments("jj"), Diagnostic(ERRID.ERR_IterationVariableShadowLocal2, "implicit").WithArguments("implicit"), Diagnostic(ERRID.ERR_IterationVariableShadowLocal2, "implicit").WithArguments("implicit"), Diagnostic(ERRID.ERR_IterationVariableShadowLocal2, "implicit").WithArguments("implicit"), Diagnostic(ERRID.ERR_IterationVariableShadowLocal2, "implicit").WithArguments("implicit"), Diagnostic(ERRID.ERR_IterationVariableShadowLocal2, "implicit").WithArguments("implicit"), Diagnostic(ERRID.ERR_IterationVariableShadowLocal2, "implicit").WithArguments("implicit"), Diagnostic(ERRID.ERR_IterationVariableShadowLocal2, "implicit").WithArguments("implicit"), Diagnostic(ERRID.ERR_IterationVariableShadowLocal2, "implicit").WithArguments("implicit"), Diagnostic(ERRID.ERR_QueryOperatorNotFound, "implicit").WithArguments("implicit"), Diagnostic(ERRID.ERR_IterationVariableShadowLocal2, "implicit").WithArguments("implicit"), Diagnostic(ERRID.ERR_IterationVariableShadowLocal2, "implicit").WithArguments("implicit"), Diagnostic(ERRID.ERR_QueryOperatorNotFound, "implicit").WithArguments("implicit"), Diagnostic(ERRID.ERR_QueryDuplicateAnonTypeMemberName1, "implicit").WithArguments("implicit"), Diagnostic(ERRID.ERR_IterationVariableShadowLocal2, "implicit").WithArguments("implicit"), Diagnostic(ERRID.ERR_IterationVariableShadowLocal2, "implicit").WithArguments("implicit"), Diagnostic(ERRID.ERR_QueryOperatorNotFound, "implicit").WithArguments("implicit"), Diagnostic(ERRID.ERR_QueryDuplicateAnonTypeMemberName1, "implicit").WithArguments("implicit"), Diagnostic(ERRID.ERR_IterationVariableShadowLocal2, "implicit").WithArguments("implicit"), Diagnostic(ERRID.ERR_QueryOperatorNotFound, "implicit").WithArguments("implicit"), Diagnostic(ERRID.ERR_IterationVariableShadowLocal2, "implicit").WithArguments("implicit"), Diagnostic(ERRID.ERR_IterationVariableShadowLocal2, "implicit").WithArguments("implicit"), Diagnostic(ERRID.WRN_DefAsgUseNullRef, "jj").WithArguments("jj"), Diagnostic(ERRID.WRN_DefAsgUseNullRef, "implicit").WithArguments("implicit")) End Sub <Fact()> Public Sub BC36635ERR_LambdaInSelectCaseExpr() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="LambdaInSelectCaseExpr"> <file name="a.vb"> Public Module M Sub LambdaAttribute() Select Case (Function(arg) arg Is Nothing) End Select End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36635: Lambda expressions are not valid in the first expression of a 'Select Case' statement. Select Case (Function(arg) arg Is Nothing) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC36638ERR_CannotLiftStructureMeLambda() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="CannotLiftStructureMeLambda"> <file name="a.vb"> Imports System Imports System.Collections.Generic Imports System.Linq Imports System.Linq.Expressions Structure S Sub New(ByVal x As S) Dim a As Expression(Of Action) = Sub() ToString() Dim b As Expression(Of Action) = Sub() Console.WriteLine(Me) End Sub End Structure </file> </compilation>, references:={Net40.SystemCore}) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36638: Instance members and 'Me' cannot be used within a lambda expression in structures. Dim a As Expression(Of Action) = Sub() ToString() ~~~~~~~~ BC36638: Instance members and 'Me' cannot be used within a lambda expression in structures. Dim b As Expression(Of Action) = Sub() Console.WriteLine(Me) ~~ </expected>) End Sub <Fact()> Public Sub BC36638ERR_CannotLiftStructureMeLambda_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="CannotLiftStructureMeLambda_2"> <file name="a.vb"> Imports System Structure S Sub New(ByVal x As S) Dim a As Action = Sub() ToString() Dim b As Action = Sub() Console.WriteLine(Me) End Sub End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36638: Instance members and 'Me' cannot be used within a lambda expression in structures. Dim a As Action = Sub() ToString() ~~~~~~~~ BC36638: Instance members and 'Me' cannot be used within a lambda expression in structures. Dim b As Action = Sub() Console.WriteLine(Me) ~~ </expected>) End Sub <Fact()> Public Sub BC36638ERR_CannotLiftStructureMeLambda_3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="CannotLiftStructureMeLambda_3"> <file name="a.vb"> Imports System Structure S Sub New(ByVal x As S) Dim a As Action = Sub() MyClass.ToString() Dim b As Action = Sub() Console.WriteLine(MyClass.ToString()) End Sub End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36638: Instance members and 'Me' cannot be used within a lambda expression in structures. Dim a As Action = Sub() MyClass.ToString() ~~~~~~~ BC36638: Instance members and 'Me' cannot be used within a lambda expression in structures. Dim b As Action = Sub() Console.WriteLine(MyClass.ToString()) ~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC36639ERR_CannotLiftByRefParamLambda1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="CannotLiftByRefParamLambda1"> <file name="a.vb"> Imports System Public Module M Sub Foo(ByRef x As String) Dim a As Action = Sub() Console.WriteLine(x) End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36639: 'ByRef' parameter 'x' cannot be used in a lambda expression. Dim a As Action = Sub() Console.WriteLine(x) ~ </expected>) End Sub <Fact()> Public Sub BC36640ERR_CannotLiftRestrictedTypeLambda() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="CannotLiftRestrictedTypeLambda"> <file name="a.vb"> Imports System Public Module M Sub LiftRestrictedType() Dim x As ArgIterator = Nothing Dim f As Action = Sub() x.GetNextArgType().GetModuleHandle() End Sub End Module </file> </compilation>) compilation.VerifyEmitDiagnostics( Diagnostic(ERRID.ERR_CannotLiftRestrictedTypeLambda, "x").WithArguments("System.ArgIterator")) End Sub <Fact()> Public Sub BC36641ERR_LambdaParamShadowLocal1() ' Roslyn - extra warning CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="LambdaParamShadowLocal1"> <file name="a.vb"> Module M1 Class Class1 Function FOO() Dim x = Function() As Object Dim z = Function() Sub(FOO) FOO = FOO End Function ' 1 End Function ' 2 End Class End Module </file> </compilation>).AssertTheseDiagnostics(<expected><![CDATA[ BC36641: Lambda parameter 'FOO' hides a variable in an enclosing block, a previously defined range variable, or an implicitly declared variable in a query expression. Dim z = Function() Sub(FOO) FOO = FOO ~~~ BC42105: Function '<anonymous method>' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used. End Function ' 1 ~~~~~~~~~~~~ BC42105: Function 'FOO' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used. End Function ' 2 ~~~~~~~~~~~~ ]]></expected>) End Sub <Fact()> Public Sub BC36641ERR_LambdaParamShadowLocal1_2() CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="LambdaParamShadowLocal1"> <file name="a.vb"> Option Infer Off Module Program Sub Main(args As String()) Dim X = 1 Dim Y = 1 Dim S = If(True, _ Function(x As Integer) As Integer Return 0 End Function, Y = Y + 1) End Sub End Module </file> </compilation>).VerifyDiagnostics( Diagnostic(ERRID.ERR_LambdaParamShadowLocal1, "x").WithArguments("x") ) End Sub <Fact()> Public Sub BC36642ERR_StrictDisallowImplicitObjectLambda() CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="StrictDisallowImplicitObjectLambda"> <file name="a.vb"> Option Strict On Module M Sub Main() Dim x = Function(y) 1 End Sub End Module </file> </compilation>).VerifyDiagnostics( Diagnostic(ERRID.ERR_StrictDisallowImplicitObjectLambda, "y") ) End Sub <Fact> Public Sub BC36645ERR_TypeInferenceFailureAddressOfLateBound() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="TypeInferenceFailure2"> <file name="a.vb"> Option Strict Off Imports System Class Module1 Sub Foo(Of T As Structure, S As Structure)(ByVal x As T, ByVal f As Func(Of T?, S?)) End Sub Class Class2 Function Bar(ByVal x As Integer) As Integer? Return Nothing End Function End Class Shared Sub Main() Dim o As Object = New Class2 Foo(1, AddressOf o.Bar) Dim qo As IQueryable(Of Integer) Dim r = qo.Select(AddressOf o.Fee) End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36645: Data type(s) of the type parameter(s) in method 'Public Sub Foo(Of T As Structure, S As Structure)(x As T, f As Func(Of T?, S?))' cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error. Foo(1, AddressOf o.Bar) ~~~ BC30002: Type 'IQueryable' is not defined. Dim qo As IQueryable(Of Integer) ~~~~~~~~~~~~~~~~~~~~~~ BC42104: Variable 'qo' is used before it has been assigned a value. A null reference exception could result at runtime. Dim r = qo.Select(AddressOf o.Fee) ~~ </expected>) End Sub <Fact()> Public Sub BC36657ERR_TypeInferenceFailureNoBest2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="TypeInferenceFailureNoBest2"> <file name="a.vb"> Option Strict On Imports System Public Module M Sub Main() Dim x As Action(Of String()) Dim y As Action(Of Object()) Foo(x, y) End Sub Sub Foo(Of T)(ByVal x As Action(Of T()), ByVal y As Action(Of T())) End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36657: Data type(s) of the type parameter(s) in method 'Public Sub Foo(Of T)(x As Action(Of T()), y As Action(Of 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. Foo(x, y) ~~~ BC42104: Variable 'x' is used before it has been assigned a value. A null reference exception could result at runtime. Foo(x, y) ~ BC42104: Variable 'y' is used before it has been assigned a value. A null reference exception could result at runtime. Foo(x, y) ~ </expected>) End Sub <Fact()> Public Sub BC36663ERR_DelegateBindingMismatchStrictOff2() CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="DelegateBindingMismatchStrictOff2"> <file name="a.vb"> Option Strict On Public Module M Sub Main() Dim k = {Function() "", AddressOf System.Console.Read} End Sub End Module </file> </compilation>).VerifyDiagnostics( Diagnostic(ERRID.ERR_DelegateBindingMismatchStrictOff2, "System.Console.Read").WithArguments("Public Shared Overloads Function Read() As Integer", "AnonymousType Function <generated method>() As String")) End Sub <WorkItem(528732, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528732")> <Fact()> Public Sub BC36666ERR_InaccessibleReturnTypeOfMember2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="InaccessibleReturnTypeOfMember2"> <file name="a.vb"> Option Infer On Imports System Class TestClass Dim pt As PrivateType Public name As PrivateType Property prop As PrivateType Protected Class PrivateType End Class Function foo() As PrivateType Return pt End Function End Class Module Module1 Sub Main() Dim tc As TestClass = New TestClass() Console.WriteLine(tc.name) Console.WriteLine(tc.foo) Console.WriteLine(tc.prop) End Sub End Module </file> </compilation>).VerifyDiagnostics( Diagnostic(ERRID.ERR_AccessMismatch6, "PrivateType").WithArguments("name", "TestClass.PrivateType", "namespace", "<Default>", "class", "TestClass"), Diagnostic(ERRID.ERR_AccessMismatch6, "PrivateType").WithArguments("prop", "TestClass.PrivateType", "namespace", "<Default>", "class", "TestClass"), Diagnostic(ERRID.ERR_AccessMismatch6, "PrivateType").WithArguments("foo", "TestClass.PrivateType", "namespace", "<Default>", "class", "TestClass"), Diagnostic(ERRID.ERR_InaccessibleReturnTypeOfMember2, "tc.name").WithArguments("Public TestClass.name As TestClass.PrivateType"), Diagnostic(ERRID.ERR_InaccessibleReturnTypeOfMember2, "tc.foo").WithArguments("Public Function TestClass.foo() As TestClass.PrivateType"), Diagnostic(ERRID.ERR_InaccessibleReturnTypeOfMember2, "tc.prop").WithArguments("Public Property TestClass.prop As TestClass.PrivateType")) End Sub <Fact()> Public Sub BC36667ERR_LocalNamedSameAsParamInLambda1() CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="LocalNamedSameAsParamInLambda1"> <file name="a.vb"> Module M1 Sub Fun() Dim x = Sub(y) Dim y = 5 End Sub End Sub End Module </file> </compilation>).VerifyDiagnostics( Diagnostic(ERRID.ERR_LocalNamedSameAsParamInLambda1, "y").WithArguments("y") ) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:="https://github.com/dotnet/roslyn/issues/29568")> Public Sub BC36670ERR_LambdaBindingMismatch2() CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="LambdaBindingMismatch2"> <file name="a.vb"> Imports System Module M1 Sub Action() End Sub Sub [Sub](ByRef x As Action) x = Sub() Action() x() End Sub Sub Fun() [Sub]((Sub(x As Integer(,)) Action() End Sub)) End Sub End Module </file> </compilation>, {Net40.SystemCore}).VerifyDiagnostics(Diagnostic(ERRID.ERR_LambdaBindingMismatch2, <![CDATA[Sub(x As Integer(,)) Action() End Sub]]>.Value.Replace(vbLf, Environment.NewLine)).WithArguments("System.Action") ) End Sub ' Different error <ConditionalFact(GetType(WindowsOnly), Reason:="https://github.com/dotnet/roslyn/issues/29531")> Public Sub BC36675ERR_StatementLambdaInExpressionTree() CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="StatementLambdaInExpressionTree"> <file name="a.vb"> Imports System Module M1 Sub Fun() Dim x = 1 Dim y As System.Linq.Expressions.Expression(Of func(Of Integer)) = Function() Return x End Function End Sub End Module </file> </compilation>, {Net40.SystemCore}).VerifyDiagnostics( Diagnostic(ERRID.ERR_StatementLambdaInExpressionTree, <![CDATA[Function() Return x End Function]]>.Value.Replace(vbLf, Environment.NewLine))) End Sub <Fact()> Public Sub BC36709ERR_DelegateBindingMismatchStrictOff3() CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="DelegateBindingMismatchStrictOff3"> <file name="a.vb"> Option Strict On Module M Delegate Function del1g(Of g)(ByVal x As g) As String Sub foo() Dim o As New cls1 Dim x As New del1g(Of String)(AddressOf o.moo(Of Integer)) End Sub End Module Class cls1 Public Function foo(Of G)(ByVal y As G) As String Return "Instance" End Function End Class Module m1 &lt;System.Runtime.CompilerServices.Extension()&gt; _ Public Function moo(Of G)(ByVal this As cls1, ByVal y As G) As String Return "Extension" End Function End Module </file> </compilation>, {Net40.SystemCore}).VerifyDiagnostics( Diagnostic(ERRID.ERR_DelegateBindingMismatchStrictOff3, "o.moo(Of Integer)").WithArguments("Public Function moo(Of Integer)(y As Integer) As String", "Delegate Function M.del1g(Of String)(x As String) As String", "m1")) End Sub <Fact()> Public Sub BC36710ERR_DelegateBindingIncompatible3() Dim compilation = CreateCompilation( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports System.Runtime.CompilerServices Imports System.Xml.Linq Delegate Function D() As Object Module M Private F1 As New D(AddressOf <x/>.E1) Private F2 As New D(AddressOf <x/>.E2) <Extension()> Function E1(x As XElement) As Object Return Nothing End Function <Extension()> Function E2(x As XElement, y As Object) As Object Return Nothing End Function End Module ]]></file> </compilation>, targetFramework:=TargetFramework.Mscorlib45AndVBRuntime, references:=Net451XmlReferences) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC36710: Extension Method 'Public Function E2(y As Object) As Object' defined in 'M' does not have a signature compatible with delegate 'Delegate Function D() As Object'. Private F2 As New D(AddressOf <x/>.E2) ~~~~~~~ ]]></errors>) End Sub <Fact()> Public Sub BC36718ERR_NotACollection1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="NotACollection1"> <file name="a.vb"> Module M1 Dim a As New Object() From {} End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36718: Cannot initialize the type 'Object' with a collection initializer because it is not a collection type. Dim a As New Object() From {} ~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC36719ERR_NoAddMethod1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="NoAddMethod1"> <file name="a.vb"> Imports System.Collections.Generic Module M1 Dim x As UDCollection1(Of Integer) = New UDCollection1(Of Integer) From {1, 2, 3} End Module Class UDCollection1(Of t) Implements IEnumerable(Of t) Public Function GetEnumerator() As System.Collections.Generic.IEnumerator(Of t) Implements System.Collections.Generic.IEnumerable(Of t).GetEnumerator Return Nothing End Function Public Function GetEnumerator1() As System.Collections.IEnumerator Implements System.Collections.IEnumerable.GetEnumerator Return Nothing End Function End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36719: Cannot initialize the type 'UDCollection1(Of Integer)' with a collection initializer because it does not have an accessible 'Add' method. Dim x As UDCollection1(Of Integer) = New UDCollection1(Of Integer) From {1, 2, 3} ~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC36721ERR_EmptyAggregateInitializer() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="NoAddMethod1"> <file name="a.vb"> Option Strict On Imports System.Collections.Generic Public Module X Sub Foo(ByVal x As Boolean) Dim y As New List(Of Integer) From {1, 2, {}} End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36721: An aggregate collection initializer entry must contain at least one element. Dim y As New List(Of Integer) From {1, 2, {}} ~~ </expected>) End Sub <Fact()> Public Sub BC36734ERR_LambdaTooManyTypesObjectDisallowed() CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="LambdaTooManyTypesObjectDisallowed"> <file name="a.vb"> Option Strict On Imports System Module M1 Dim y As Action(Of Integer) = Function(a As Integer) Return 1 Return "" End Function End Module </file> </compilation>).VerifyDiagnostics( Diagnostic(ERRID.ERR_LambdaTooManyTypesObjectDisallowed, "Function(a As Integer)") ) End Sub <Fact()> Public Sub BC36751ERR_LambdaNoType() CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="LambdaNoType"> <file name="a.vb"> Module M1 Dim x = Function() Return AddressOf System.Console.WriteLine End Function End Module </file> </compilation>).VerifyDiagnostics( Diagnostic(ERRID.ERR_LambdaNoType, "Function()")) End Sub ' Different error <Fact()> Public Sub BC36754ERR_VarianceConversionFailedOut6() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="VarianceConversionFailedOut6"> <file name="a.vb"> Option Strict On Interface IVariance(Of Out T) : Function Foo() As T : End Interface Interface IVariance2(Of In T) : Sub Foo(ByVal s As T) : End Interface Class Variance(Of T) : Implements IVariance(Of T), IVariance2(Of T) Public Function Foo() As T Implements IVariance(Of T).Foo End Function Public Sub Foo1(ByVal s As T) Implements IVariance2(Of T).Foo End Sub End Class Module M1 Dim x As IVariance(Of Double) = New Variance(Of Short) End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36754: 'Variance(Of Short)' cannot be converted to 'IVariance(Of Double)' because 'Short' is not derived from 'Double', as required for the 'Out' generic parameter 'T' in 'Interface IVariance(Of Out T)'. Dim x As IVariance(Of Double) = New Variance(Of Short) ~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub ' Different error <Fact()> Public Sub BC36755ERR_VarianceConversionFailedIn6() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="VarianceConversionFailedIn6"> <file name="a.vb"> Option Strict On Interface IVariance(Of Out T) : Function Foo() As T : End Interface Interface IVariance2(Of In T) : Sub Foo(ByVal s As T) : End Interface Class Variance(Of T) : Implements IVariance(Of T), IVariance2(Of T) Public Function Foo() As T Implements IVariance(Of T).Foo End Function Public Sub Foo1(ByVal s As T) Implements IVariance2(Of T).Foo End Sub End Class Module M1 Dim x As IVariance2(Of Short) = New Variance(Of Double) End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36755: 'Variance(Of Double)' cannot be converted to 'IVariance2(Of Short)' because 'Short' is not derived from 'Double', as required for the 'In' generic parameter 'T' in 'Interface IVariance2(Of In T)'. Dim x As IVariance2(Of Short) = New Variance(Of Double) ~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub ' Different error <Fact()> Public Sub BC36756ERR_VarianceIEnumerableSuggestion3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="VarianceIEnumerableSuggestion3"> <file name="a.vb"> Imports System.Collections.Generic Public Class Animals : End Class Public Class Cheetah : Inherits Animals : End Class Module M1 Dim x As List(Of Animals) = New List(Of Cheetah) End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36756: 'List(Of Cheetah)' cannot be converted to 'List(Of Animals)'. Consider using 'IEnumerable(Of Animals)' instead. Dim x As List(Of Animals) = New List(Of Cheetah) ~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC36757ERR_VarianceConversionFailedTryOut4() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="VarianceConversionFailedTryOut4"> <file name="a.vb"> Option Strict On Public Class Animals : End Class Public Class Cheetah : Inherits Animals : End Class Interface IFoo(Of T) : End Interface Class MyFoo(Of T) Implements IFoo(Of T) End Class Module M1 Dim x As IFoo(Of Animals) = New MyFoo(Of Cheetah) End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36757: 'MyFoo(Of Cheetah)' cannot be converted to 'IFoo(Of Animals)'. Consider changing the 'T' in the definition of 'Interface IFoo(Of T)' to an Out type parameter, 'Out T'. Dim x As IFoo(Of Animals) = New MyFoo(Of Cheetah) ~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub ' Different error <Fact()> Public Sub BC36758ERR_VarianceConversionFailedTryIn4() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="VarianceConversionFailedTryIn4"> <file name="a.vb"> Option Strict On Public Class Animals : End Class Public Class Vertebrates : Inherits Animals : End Class Public Class Mammals : Inherits Vertebrates : End Class Public Class Carnivora : Inherits Mammals : End Class Class Variance(Of T) Interface IVariance(Of In S, Out R) End Interface End Class Class Variance2(Of T, R As New) Implements Variance(Of T).IVariance(Of T, R) End Class Module M1 Dim x As Variance(Of Mammals).IVariance(Of Mammals, Mammals) = New Variance2(Of Animals, Carnivora) End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36758: 'Variance2(Of Animals, Carnivora)' cannot be converted to 'Variance(Of Mammals).IVariance(Of Mammals, Mammals)'. Consider changing the 'T' in the definition of 'Class Variance(Of T)' to an In type parameter, 'In T'. Dim x As Variance(Of Mammals).IVariance(Of Mammals, Mammals) = New Variance2(Of Animals, Carnivora) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC36760ERR_IdentityDirectCastForFloat() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="LambdaParamShadowLocal1"> <file name="a.vb"> Module Test Sub Main() Dim a As Double = 1 Dim b As Integer = DirectCast(a, Double) * 1000 End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36760: Using DirectCast operator to cast a floating-point value to the same type is not supported. Dim b As Integer = DirectCast(a, Double) * 1000 ~ </expected>) End Sub <Fact()> Public Sub BC36807ERR_TypeDisallowsElements() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports System.Collections.Generic Imports System.Xml.Linq Class MyElement Inherits XElement Public Sub New(name As XName) MyBase.New(name) End Sub End Class Module M Function F(Of T)() As T Return Nothing End Function Sub M() Dim x As Object x = F(Of Object).<x> x = F(Of XObject).<x> x = F(Of XContainer).<x> x = F(Of XElement).<x> x = F(Of XDocument).<x> x = F(Of XAttribute).<x> x = F(Of MyElement).<x> x = F(Of Object()).<x> x = F(Of XObject()).<x> x = F(Of XContainer()).<x> x = F(Of XElement()).<x> x = F(Of XDocument()).<x> x = F(Of XAttribute()).<x> x = F(Of MyElement()).<x> x = F(Of IEnumerable(Of Object)).<x> x = F(Of IEnumerable(Of XObject)).<x> x = F(Of IEnumerable(Of XContainer)).<x> x = F(Of IEnumerable(Of XElement)).<x> x = F(Of IEnumerable(Of XDocument)).<x> x = F(Of IEnumerable(Of XAttribute)).<x> x = F(Of IEnumerable(Of MyElement)).<x> End Sub End Module ]]></file> </compilation>, references:=XmlReferences) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC31168: XML axis properties do not support late binding. x = F(Of Object).<x> ~~~~~~~~~~~~~~~~ BC36807: XML elements cannot be selected from type 'XObject'. x = F(Of XObject).<x> ~~~~~~~~~~~~~~~~~ BC36807: XML elements cannot be selected from type 'XAttribute'. x = F(Of XAttribute).<x> ~~~~~~~~~~~~~~~~~~~~ BC36807: XML elements cannot be selected from type 'Object()'. x = F(Of Object()).<x> ~~~~~~~~~~~~~~~~~~ BC36807: XML elements cannot be selected from type 'XObject()'. x = F(Of XObject()).<x> ~~~~~~~~~~~~~~~~~~~ BC36807: XML elements cannot be selected from type 'XAttribute()'. x = F(Of XAttribute()).<x> ~~~~~~~~~~~~~~~~~~~~~~ BC36807: XML elements cannot be selected from type 'IEnumerable(Of Object)'. x = F(Of IEnumerable(Of Object)).<x> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36807: XML elements cannot be selected from type 'IEnumerable(Of XObject)'. x = F(Of IEnumerable(Of XObject)).<x> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36807: XML elements cannot be selected from type 'IEnumerable(Of XAttribute)'. x = F(Of IEnumerable(Of XAttribute)).<x> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></errors>) End Sub <Fact()> Public Sub BC36808ERR_TypeDisallowsAttributes() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports System.Collections.Generic Imports System.Xml.Linq Class MyElement Inherits XElement Public Sub New(name As XName) MyBase.New(name) End Sub End Class Module M Function F(Of T)() As T Return Nothing End Function Sub M() Dim x As Object x = F(Of Object).@a x = F(Of XObject).@a x = F(Of XContainer).@a x = F(Of XElement).@a x = F(Of XDocument).@a x = F(Of XAttribute).@a x = F(Of MyElement).@a x = F(Of Object()).@a x = F(Of XObject()).@a x = F(Of XContainer()).@a x = F(Of XElement()).@a x = F(Of XDocument()).@a x = F(Of XAttribute()).@a x = F(Of MyElement()).@a x = F(Of IEnumerable(Of Object)).@a x = F(Of IEnumerable(Of XObject)).@a x = F(Of IEnumerable(Of XContainer)).@a x = F(Of IEnumerable(Of XElement)).@a x = F(Of IEnumerable(Of XDocument)).@a x = F(Of IEnumerable(Of XAttribute)).@a x = F(Of IEnumerable(Of MyElement)).@a End Sub End Module ]]></file> </compilation>, references:=XmlReferences) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC31168: XML axis properties do not support late binding. x = F(Of Object).@a ~~~~~~~~~~~~~~~ BC36808: XML attributes cannot be selected from type 'XObject'. x = F(Of XObject).@a ~~~~~~~~~~~~~~~~ BC36808: XML attributes cannot be selected from type 'XContainer'. x = F(Of XContainer).@a ~~~~~~~~~~~~~~~~~~~ BC36808: XML attributes cannot be selected from type 'XDocument'. x = F(Of XDocument).@a ~~~~~~~~~~~~~~~~~~ BC36808: XML attributes cannot be selected from type 'XAttribute'. x = F(Of XAttribute).@a ~~~~~~~~~~~~~~~~~~~ BC36808: XML attributes cannot be selected from type 'Object()'. x = F(Of Object()).@a ~~~~~~~~~~~~~~~~~ BC36808: XML attributes cannot be selected from type 'XObject()'. x = F(Of XObject()).@a ~~~~~~~~~~~~~~~~~~ BC36808: XML attributes cannot be selected from type 'XContainer()'. x = F(Of XContainer()).@a ~~~~~~~~~~~~~~~~~~~~~ BC36808: XML attributes cannot be selected from type 'XDocument()'. x = F(Of XDocument()).@a ~~~~~~~~~~~~~~~~~~~~ BC36808: XML attributes cannot be selected from type 'XAttribute()'. x = F(Of XAttribute()).@a ~~~~~~~~~~~~~~~~~~~~~ BC36808: XML attributes cannot be selected from type 'IEnumerable(Of Object)'. x = F(Of IEnumerable(Of Object)).@a ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36808: XML attributes cannot be selected from type 'IEnumerable(Of XObject)'. x = F(Of IEnumerable(Of XObject)).@a ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36808: XML attributes cannot be selected from type 'IEnumerable(Of XContainer)'. x = F(Of IEnumerable(Of XContainer)).@a ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36808: XML attributes cannot be selected from type 'IEnumerable(Of XDocument)'. x = F(Of IEnumerable(Of XDocument)).@a ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36808: XML attributes cannot be selected from type 'IEnumerable(Of XAttribute)'. x = F(Of IEnumerable(Of XAttribute)).@a ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></errors>) ' Note: The last error above ("BC30518: Overload resolution failed ...") ' should not be generated after variance conversions are supported. End Sub <Fact()> Public Sub BC36809ERR_TypeDisallowsDescendants() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports System.Collections.Generic Imports System.Xml.Linq Class MyElement Inherits XElement Public Sub New(name As XName) MyBase.New(name) End Sub End Class Module M Function F(Of T)() As T Return Nothing End Function Sub M() Dim x As Object x = F(Of Object)...<x> x = F(Of XObject)...<x> x = F(Of XContainer)...<x> x = F(Of XElement)...<x> x = F(Of XDocument)...<x> x = F(Of XAttribute)...<x> x = F(Of MyElement)...<x> x = F(Of Object())...<x> x = F(Of XObject())...<x> x = F(Of XContainer())...<x> x = F(Of XElement())...<x> x = F(Of XDocument())...<x> x = F(Of XAttribute())...<x> x = F(Of MyElement())...<x> x = F(Of IEnumerable(Of Object))...<x> x = F(Of IEnumerable(Of XObject))...<x> x = F(Of IEnumerable(Of XContainer))...<x> x = F(Of IEnumerable(Of XElement))...<x> x = F(Of IEnumerable(Of XDocument))...<x> x = F(Of IEnumerable(Of XAttribute))...<x> x = F(Of IEnumerable(Of MyElement))...<x> End Sub End Module ]]></file> </compilation>, references:=XmlReferences) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC31168: XML axis properties do not support late binding. x = F(Of Object)...<x> ~~~~~~~~~~~~~~~~~~ BC36809: XML descendant elements cannot be selected from type 'XObject'. x = F(Of XObject)...<x> ~~~~~~~~~~~~~~~~~~~ BC36809: XML descendant elements cannot be selected from type 'XAttribute'. x = F(Of XAttribute)...<x> ~~~~~~~~~~~~~~~~~~~~~~ BC36809: XML descendant elements cannot be selected from type 'Object()'. x = F(Of Object())...<x> ~~~~~~~~~~~~~~~~~~~~ BC36809: XML descendant elements cannot be selected from type 'XObject()'. x = F(Of XObject())...<x> ~~~~~~~~~~~~~~~~~~~~~ BC36809: XML descendant elements cannot be selected from type 'XAttribute()'. x = F(Of XAttribute())...<x> ~~~~~~~~~~~~~~~~~~~~~~~~ BC36809: XML descendant elements cannot be selected from type 'IEnumerable(Of Object)'. x = F(Of IEnumerable(Of Object))...<x> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36809: XML descendant elements cannot be selected from type 'IEnumerable(Of XObject)'. x = F(Of IEnumerable(Of XObject))...<x> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36809: XML descendant elements cannot be selected from type 'IEnumerable(Of XAttribute)'. x = F(Of IEnumerable(Of XAttribute))...<x> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></errors>) End Sub <Fact()> Public Sub BC36907ERR_TypeOrMemberNotGeneric2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="TypeOrMemberNotGeneric2"> <file name="a.vb"> Option Strict On Imports System Module M1 Sub FOO() Dim x1 As Integer x1.FooGeneric01(Of Integer)() End Sub End Module Module Extension01 &lt;System.Runtime.CompilerServices.Extension()&gt; Sub FooGeneric01(Of T1)(ByVal o As T1) End Sub End Module </file> </compilation>, {Net40.SystemCore}) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36907: Extension method 'Public Sub FooGeneric01()' defined in 'Extension01' is not generic (or has no free type parameters) and so cannot have type arguments. x1.FooGeneric01(Of Integer)() ~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC36913ERR_IfTooManyTypesObjectDisallowed() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict On Public Module X Sub Foo(ByVal x As Boolean) Dim f = If(x, Function() 1, Function() "") End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36913: Cannot infer a common type because more than one type is possible. Dim f = If(x, Function() 1, Function() "") ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC36916ERR_LambdaNoTypeObjectDisallowed() CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="LambdaNoTypeObjectDisallowed"> <file name="a.vb"> Option Strict On Imports System Module M1 Dim x As Action = Function() Dim a = 2 End Function End Module </file> </compilation>).VerifyDiagnostics( Diagnostic(ERRID.ERR_LambdaNoTypeObjectDisallowed, "Function()"), Diagnostic(ERRID.WRN_DefAsgNoRetValFuncRef1, "End Function").WithArguments("<anonymous method>") ) End Sub #End Region #Region "Targeted Warning Tests" <Fact()> Public Sub BC40052WRN_SelectCaseInvalidRange() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="SelectCaseInvalidRange"> <file name="a.vb"> Module M1 Sub foo() Select Case #1/2/0003# Case Date.MaxValue To Date.MinValue End Select Select Case 1 Case 1 To 0 End Select End Sub End Module </file> </compilation>, TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.Custom)) Dim expectedErrors1 = <errors> BC40052: Range specified for 'Case' statement is not valid. Make sure that the lower bound is less than or equal to the upper bound. Case 1 To 0 ~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC40052WRN_SelectCaseInvalidRange_02() ' Dev10 doesn't report WRN_SelectCaseInvalidRange for each invalid case range. ' It is performed only if bounds for all clauses in the Select are integer constants and ' all clauses are either range clauses or equality clause. ' Doing this differently will produce warnings in more scenarios - breaking change, ' hence we maintain compatibility with Dev10. Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="SelectCaseInvalidRange"> <file name="a.vb"> Module M1 Sub foo() ' NO WARNING CASES ' with relational clause Select Case 1 Case 1 To 0 Case Is > 10 End Select ' with relational clause in different order Select Case 1 Case Is > 10 Case 1 To 0 End Select ' with non constant integer clause Dim number As Integer = 10 Select Case 1 Case 1 To 0 Case number End Select ' with non integer clause Dim obj As Object = 10 Select Case 1 Case 1 To 0 Case obj End Select ' WARNING CASES ' with all integer constant equality clauses Select Case 1 Case 1 To 0 Case Is = 2 Case 1, 2, 3 End Select ' with all integer constant equality clauses in different order Select Case 1 Case Is = 2 Case 1, 2, 3 Case 1 To 0 End Select End Sub End Module </file> </compilation>) Dim expectedErrors1 = <errors> BC40052: Range specified for 'Case' statement is not valid. Make sure that the lower bound is less than or equal to the upper bound. Case 1 To 0 ~~~~~~ BC40052: Range specified for 'Case' statement is not valid. Make sure that the lower bound is less than or equal to the upper bound. Case 1 To 0 ~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact> <WorkItem(759127, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/759127")> Public Sub BC41000WRN_AttributeSpecifiedMultipleTimes() ' No warnings Expected - Previously would generate a BC41000. The signature of Attribute ' determined From attribute used in original bug. ' We want to verify that the diagnostics do not appear and that the attributes are both added. ' No values provided for attribute Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="Class1"> <file name="a.vb"> Imports System &lt;System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1019:DefineAccessorsForAttributeArguments")&gt; &lt;AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class, AllowMultiple:=True)&gt; Public Class ESAttribute Inherits System.Attribute Public Sub New(assemblyGUID As String) If (assemblyGUID Is Nothing) Then Throw New System.ArgumentNullException("assemblyGuid") End If End Sub Public Sub New() End Sub End Class </file> <file name="b.vb"> &lt;Assembly:ESAttribute()&gt; Class Class1 Sub Blah() End Sub End Class </file> <file name="c.vb"> &lt;Assembly:ESAttribute()&gt; Module Module1 Sub Main() End Sub End Module </file> </compilation>) Dim expectedErrors1 = <errors> </errors> CompilationUtils.AssertTheseDiagnostics(compilation, expectedErrors1) ' One value provided for attribute, the other does not have argument compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="Class1"> <file name="a.vb"> Imports System &lt;System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1019:DefineAccessorsForAttributeArguments")&gt; &lt;AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class, AllowMultiple:=True)&gt; Public Class ESAttribute Inherits System.Attribute Public Sub New(assemblyGUID As String) If (assemblyGUID Is Nothing) Then Throw New System.ArgumentNullException("assemblyGuid") End If End Sub Public Sub New() End Sub End Class </file> <file name="b.vb"> &lt;Assembly:ESAttribute()&gt; Class Class1 Sub Blah() End Sub End Class </file> <file name="c.vb"> &lt;Assembly:ESAttribute("Test")&gt; Module Module1 Sub Main() End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, expectedErrors1) ' Different values for argument provided for attribute usage compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="Class1"> <file name="a.vb"> Imports System &lt;System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1019:DefineAccessorsForAttributeArguments")&gt; &lt;AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class, AllowMultiple:=True)&gt; Public Class ESAttribute Inherits System.Attribute Public Sub New(assemblyGUID As String) If (assemblyGUID Is Nothing) Then Throw New System.ArgumentNullException("assemblyGuid") End If End Sub Public Sub New() End Sub End Class </file> <file name="b.vb"> &lt;Assembly:ESAttribute("test2")&gt; Class Class1 Sub Blah() End Sub End Class </file> <file name="c.vb"> &lt;Assembly:ESAttribute("Test")&gt; Module Module1 Sub Main() End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, expectedErrors1) Assert.Equal(2, compilation.Assembly.GetAttributes.Count) Assert.Equal("ESAttribute(""test2"")", compilation.Assembly.GetAttributes.Item(0).ToString) Assert.Equal("ESAttribute(""Test"")", compilation.Assembly.GetAttributes.Item(1).ToString) ' Different values for argument provided for attribute usage - Different Order To check the order is ' not sorted but merely the order it was located in compilation compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="Class1"> <file name="a.vb"> Imports System &lt;System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1019:DefineAccessorsForAttributeArguments")&gt; &lt;AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class, AllowMultiple:=True)&gt; Public Class ESAttribute Inherits System.Attribute Public Sub New(assemblyGUID As String) If (assemblyGUID Is Nothing) Then Throw New System.ArgumentNullException("assemblyGuid") End If End Sub Public Sub New() End Sub End Class </file> <file name="b.vb"> &lt;Assembly:ESAttribute("Test")&gt; Class Class1 Sub Blah() End Sub End Class </file> <file name="c.vb"> &lt;Assembly:ESAttribute("Test2")&gt; Module Module1 Sub Main() End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, expectedErrors1) Assert.Equal(2, compilation.Assembly.GetAttributes.Count) Assert.Equal("ESAttribute(""Test"")", compilation.Assembly.GetAttributes.Item(0).ToString) Assert.Equal("ESAttribute(""Test2"")", compilation.Assembly.GetAttributes.Item(1).ToString) End Sub <Fact> Public Sub BC41001WRN_NoNonObsoleteConstructorOnBase3() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="NoNonObsoleteConstructorOnBase4"> <file name="a.vb"> Imports System Class C1 &lt;Obsolete&gt; Sub New() End Sub End Class Class C2 Inherits C1 End Class </file> </compilation>, TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.Custom)) Dim expectedErrors1 = <errors> BC41001: Class 'C2' should declare a 'Sub New' because the 'Public Sub New()' in its base class 'C1' is marked obsolete. Class C2 ~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact> Public Sub BC41002WRN_NoNonObsoleteConstructorOnBase4() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="NoNonObsoleteConstructorOnBase4"> <file name="a.vb"> Imports System Class C1 &lt;Obsolete("hello", False)&gt; Sub New() End Sub End Class Class C2 Inherits C1 End Class </file> </compilation>, TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.Custom)) Dim expectedErrors1 = <errors> BC41002: Class 'C2' should declare a 'Sub New' because the 'Public Sub New()' in its base class 'C1' is marked obsolete: 'hello'. Class C2 ~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact> Public Sub BC41003WRN_RequiredNonObsoleteNewCall3() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="RequiredNonObsoleteNewCall4"> <file name="a.vb"> Imports System Class C1 &lt;Obsolete&gt; Sub New() End Sub End Class Class C2 Inherits C1 Sub New() End Sub End Class </file> </compilation>, TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.Custom)) Dim expectedErrors1 = <errors> BC41003: First statement of this 'Sub New' should be an explicit call to 'MyBase.New' or 'MyClass.New' because the 'Public Sub New()' in the base class 'C1' of 'C2' is marked obsolete. Sub New() ~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact> Public Sub BC41004WRN_RequiredNonObsoleteNewCall4() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="RequiredNonObsoleteNewCall4"> <file name="a.vb"> Imports System Class C1 &lt;Obsolete("hello", False)&gt; Sub New() End Sub End Class Class C2 Inherits C1 Sub New() End Sub End Class </file> </compilation>, TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.Custom)) Dim expectedErrors1 = <errors> BC41004: First statement of this 'Sub New' should be an explicit call to 'MyBase.New' or 'MyClass.New' because the 'Public Sub New()' in the base class 'C1' of 'C2' is marked obsolete: 'hello' Sub New() ~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact> Public Sub BC41007WRN_ConditionalNotValidOnFunction() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ConditionalNotValidOnFunction"> <file name="a.vb"> Imports System.Diagnostics Public Structure S1 &lt;Conditional("hello")&gt; Public Shared Operator +(ByVal v As S1, ByVal w As S1) As Object Return Nothing End Operator End Structure </file> </compilation>, TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.Custom)) Dim expectedErrors1 = <errors> BC41007: Attribute 'Conditional' is only valid on 'Sub' declarations. Public Shared Operator +(ByVal v As S1, ByVal w As S1) As Object ~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> <CompilerTrait(CompilerFeature.IOperation)> <WorkItem(23282, "https://github.com/dotnet/roslyn/issues/23282")> Public Sub BC41998WRN_RecursiveAddHandlerCall() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="RecursiveAddHandlerCall"> <file name="a.vb"> Module M1 Public Delegate Sub test_x() Sub test_d1() End Sub Public Custom Event t As test_x AddHandler(ByVal value As test_x) AddHandler t, AddressOf test_d1 End AddHandler RemoveHandler(ByVal value As test_x) RemoveHandler t, AddressOf test_d1 End RemoveHandler RaiseEvent() RaiseEvent t() End RaiseEvent End Event End Module </file> </compilation>, TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.Custom)) Dim expectedErrors1 = <errors> BC41998: Statement recursively calls the containing 'AddHandler' for event 't'. AddHandler t, AddressOf test_d1 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC41998: Statement recursively calls the containing 'RemoveHandler' for event 't'. RemoveHandler t, AddressOf test_d1 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC41998: Statement recursively calls the containing 'RaiseEvent' for event 't'. RaiseEvent t() ~~~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation, expectedErrors1) Dim tree = compilation.SyntaxTrees.Single() Dim model = compilation.GetSemanticModel(tree) Dim add = tree.GetRoot().DescendantNodes().OfType(Of AddRemoveHandlerStatementSyntax)().First() Assert.Equal("AddHandler t, AddressOf test_d1", add.ToString()) compilation.VerifyOperationTree(add, expectedOperationTree:= <![CDATA[ IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'AddHandler ... sOf test_d1') Expression: IEventAssignmentOperation (EventAdd) (OperationKind.EventAssignment, Type: null, IsImplicit) (Syntax: 'AddHandler ... sOf test_d1') Event Reference: IEventReferenceOperation: Event M1.t As M1.test_x (Static) (OperationKind.EventReference, Type: M1.test_x) (Syntax: 't') Instance Receiver: null Handler: IDelegateCreationOperation (OperationKind.DelegateCreation, Type: M1.test_x, IsImplicit) (Syntax: 'AddressOf test_d1') Target: IMethodReferenceOperation: Sub M1.test_d1() (Static) (OperationKind.MethodReference, Type: null) (Syntax: 'AddressOf test_d1') Instance Receiver: null ]]>.Value) Assert.Equal("Event M1.t As M1.test_x", model.GetSymbolInfo(add.EventExpression).Symbol.ToTestDisplayString()) Dim remove = tree.GetRoot().DescendantNodes().OfType(Of AddRemoveHandlerStatementSyntax)().Last() Assert.Equal("RemoveHandler t, AddressOf test_d1", remove.ToString()) compilation.VerifyOperationTree(remove, expectedOperationTree:= <![CDATA[ IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'RemoveHandl ... sOf test_d1') Expression: IEventAssignmentOperation (EventRemove) (OperationKind.EventAssignment, Type: null, IsImplicit) (Syntax: 'RemoveHandl ... sOf test_d1') Event Reference: IEventReferenceOperation: Event M1.t As M1.test_x (Static) (OperationKind.EventReference, Type: M1.test_x) (Syntax: 't') Instance Receiver: null Handler: IDelegateCreationOperation (OperationKind.DelegateCreation, Type: M1.test_x, IsImplicit) (Syntax: 'AddressOf test_d1') Target: IMethodReferenceOperation: Sub M1.test_d1() (Static) (OperationKind.MethodReference, Type: null) (Syntax: 'AddressOf test_d1') Instance Receiver: null ]]>.Value) Assert.Equal("Event M1.t As M1.test_x", model.GetSymbolInfo(remove.EventExpression).Symbol.ToTestDisplayString()) Dim raise = tree.GetRoot().DescendantNodes().OfType(Of RaiseEventStatementSyntax)().Single() Assert.Equal("RaiseEvent t()", raise.ToString()) compilation.VerifyOperationTree(raise, expectedOperationTree:= <![CDATA[ IRaiseEventOperation (OperationKind.RaiseEvent, Type: null) (Syntax: 'RaiseEvent t()') Event Reference: IEventReferenceOperation: Event M1.t As M1.test_x (Static) (OperationKind.EventReference, Type: M1.test_x) (Syntax: 't') Instance Receiver: null Arguments(0) ]]>.Value) Assert.Equal("Event M1.t As M1.test_x", model.GetSymbolInfo(raise.Name).Symbol.ToTestDisplayString()) End Sub <Fact()> Public Sub BC41999WRN_ImplicitConversionCopyBack() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ImplicitConversionCopyBack"> <file name="a.vb"> Namespace ns1 Module M1 Sub foo(ByRef x As Object) End Sub Sub FOO1() Dim o As New System.Exception foo(o) End Sub End Module End Namespace </file> </compilation>, TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.Custom)) Dim expectedErrors1 = <errors> BC41999: Implicit conversion from 'Object' to 'Exception' in copying the value of 'ByRef' parameter 'x' back to the matching argument. foo(o) ~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC42016WRN_ImplicitConversionSubst1() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ImplicitConversionSubst1"> <file name="a.vb"> Module Module1 Sub Main() Dim a As Integer = 2 Dim b As Integer = 2 Dim c As Integer = a / b a = c End Sub End Module </file> </compilation>, TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.Custom)) Dim expectedErrors1 = <errors> BC42016: Implicit conversion from 'Double' to 'Integer'. Dim c As Integer = a / b ~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC42018WRN_ObjectMath1() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ObjectMath1"> <file name="a.vb"> Module Module1 Sub Main() Dim o As New Object o = o = 1 End Sub End Module </file> </compilation>, TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.Custom)) Dim expectedErrors1 = <errors> BC42018: Operands of type Object used for operator '='; use the 'Is' operator to test object identity. o = o = 1 ~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC42019WRN_ObjectMath2_1() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ObjectMath2"> <file name="a.vb"> Module Module1 Sub Main() Dim o As New Object o = o + 1 End Sub End Module </file> </compilation>, TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.Custom)) Dim expectedErrors1 = <errors> BC42019: Operands of type Object used for operator '+'; runtime errors could occur. o = o + 1 ~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC42019WRN_ObjectMath2_2() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ObjectMath2"> <file name="a.vb"> Module Module1 function Main() Dim o As New Object return o * o End function End Module </file> </compilation>, TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.Custom)) Dim expectedErrors1 = <errors> BC42021: Function without an 'As' clause; return type of Object assumed. function Main() ~~~~ BC42019: Operands of type Object used for operator '*'; runtime errors could occur. return o * o ~ BC42019: Operands of type Object used for operator '*'; runtime errors could occur. return o * o ~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC42024WRN_UnusedLocal() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="UnusedLocal"> <file name="a.vb"> Public Module Module1 Public Sub Main() Dim c1 As Class1 End Sub Class Class1 End Class End Module </file> </compilation>) Dim expectedErrors1 = <errors> BC42024: Unused local variable: 'c1'. Dim c1 As Class1 ~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC42025WRN_SharedMemberThroughInstance_1() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module Module1 Structure S1 Structure S1 Public Shared strTemp As String End Structure End Structure Sub Main() Dim obj As New S1.S1 obj.strTemp = "S" End Sub End Module </file> </compilation>) Dim expectedErrors1 = <errors> BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. obj.strTemp = "S" ~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC42025WRN_SharedMemberThroughInstance_2() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C Shared Property P Get Return Nothing End Get Set(ByVal value) End Set End Property Sub M() Dim o = Me.P Me.P = o End Sub End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. Dim o = Me.P ~~~~ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. Me.P = o ~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <WorkItem(528718, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528718")> <Fact()> Public Sub BC42025WRN_SharedMemberThroughInstance_3() CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="a.vb"> Option Infer On Imports System.Runtime.CompilerServices Module M Sub Main() For Each y In 1 Next End Sub &lt;Extension()&gt; Function GetEnumerator(x As Integer) As E Return New E End Function End Module Class E Function MoveNext() As Boolean Return True End Function Shared Property Current As Boolean Get Return True End Get Set(ByVal value As Boolean) End Set End Property End Class </file> </compilation>, {Net40.SystemCore}).VerifyDiagnostics( Diagnostic(ERRID.WRN_SharedMemberThroughInstance, "1")) End Sub <Fact()> Public Sub BC42025WRN_SharedMemberThroughInstance_4() Dim comp = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Enum E A B = B.A + 1 End Enum </file> </compilation>) comp.AssertTheseDiagnostics(<errors> BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. B = B.A + 1 ~~~ </errors>) End Sub <Fact(), WorkItem(528734, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528734")> Public Sub BC42026WRN_RecursivePropertyCall() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="RecursivePropertyCall"> <file name="a.vb"> Module Module1 Class c1 ReadOnly Property Name() As String Get Return Me.Name End Get End Property End Class End Module Module Program Sub PassByRef(ByRef x As Integer) End Sub Sub PassByVal(x As Integer) End Sub Property P1 As Integer Get If Date.Now.Day = 2 Then Return P1() + 1 ' 1 ElseIf Date.Now.Day = 3 Then P1() += 1 ' 2 Mid(P1(), 1) = 2 ' 3 PassByRef(P1()) '4 PassByVal(P1()) '5 Else P1() = 2 End If Return 0 End Get Set(value As Integer) If Date.Now.Day = 2 Then P1() = value '6 ElseIf Date.Now.Day = 3 Then P1() += 1 '7 Mid(P1(), 1) = 2 '8 PassByRef(P1()) '9 PassByVal(P1()) Else Dim x = P1() End If End Set End Property Property P2(a As Integer) As Integer Get If Date.Now.Day = 2 Then Return P2(a) + 1 ElseIf Date.Now.Day = 3 Then P2(a) += 2 Mid(P2(a), 1) = 2 PassByRef(P2(a)) PassByVal(P2(a)) Else P2(a) = 2 End If Return 0 End Get Set(value As Integer) If Date.Now.Day = 2 Then P2(a) = value ElseIf Date.Now.Day = 3 Then P2(a) += 2 Mid(P2(a), 1) = 2 PassByRef(P2(a)) PassByVal(P2(a)) Else Dim x = P2(a) End If End Set End Property End Module Class Class1 Property P3 As Integer Get If Date.Now.Day = 2 Then Return P3() + 1 '10 ElseIf Date.Now.Day = 3 Then P3() += 2 ' 11 Mid(P3(), 1) = 2 ' 12 PassByRef(P3()) ' 13 PassByVal(P3()) ' 14 Else P3() = 2 End If Return 0 End Get Set(value As Integer) If Date.Now.Day = 2 Then P3() = value ' 15 ElseIf Date.Now.Day = 3 Then P3() += 2 ' 16 Mid(P3(), 1) = 2 ' 17 PassByRef(P3()) ' 18 PassByVal(P3()) Else Dim x = P3() End If End Set End Property Property P4 As Integer Get If Date.Now.Day = 2 Then Return P4 + 1 ElseIf Date.Now.Day = 3 Then P4 += 2 Mid(P4, 1) = 2 PassByRef(P4) PassByVal(P4) Else P4 = 2 End If Return 0 End Get Set(value As Integer) If Date.Now.Day = 2 Then P4 = value ' 19 ElseIf Date.Now.Day = 3 Then P4 += 2 ' 20 Mid(P4, 1) = 2 ' 21 PassByRef(P4) ' 22 PassByVal(P4) Else Dim x = P4 End If End Set End Property Property P5 As Integer Get If Date.Now.Day = 2 Then Return Me.P5 + 1 ' 23 ElseIf Date.Now.Day = 3 Then Me.P5 += 2 ' 24 Mid(Me.P5, 1) = 2 ' 25 PassByRef(Me.P5) ' 26 PassByVal(Me.P5) ' 27 Else Me.P5 = 2 End If Return 0 End Get Set(value As Integer) If Date.Now.Day = 2 Then Me.P5 = value ' 28 ElseIf Date.Now.Day = 3 Then Me.P5 += 2 ' 29 Mid(Me.P5, 1) = 2 ' 30 PassByRef(Me.P5) ' 31 PassByVal(Me.P5) Else Dim x = Me.P5 End If End Set End Property Property P6(a As Integer) As Integer Get If Date.Now.Day = 2 Then Return P6(a) + 1 ElseIf Date.Now.Day = 3 Then P6(a) += 2 Mid(P6(a), 1) = 2 PassByRef(P6(a)) PassByVal(P6(a)) Else P6(a) = 2 End If Return 0 End Get Set(value As Integer) If Date.Now.Day = 2 Then P6(a) = value ElseIf Date.Now.Day = 3 Then P6(a) += 2 Mid(P6(a), 1) = 2 PassByRef(P6(a)) PassByVal(P6(a)) Else Dim x = P6(a) End If End Set End Property Property P7 As Integer Get Dim x = Me If Date.Now.Day = 2 Then Return x.P7() + 1 ElseIf Date.Now.Day = 3 Then x.P7() += 2 Mid(x.P7(), 1) = 2 PassByRef(x.P7()) PassByVal(x.P7()) Else x.P7() = 2 End If Return 0 End Get Set(value As Integer) Dim x = Me If Date.Now.Day = 2 Then x.P7() = value ElseIf Date.Now.Day = 3 Then x.P7() += 2 Mid(x.P7(), 1) = 2 PassByRef(x.P7()) PassByVal(x.P7()) Else Dim y = x.P7() End If End Set End Property End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC42026: Expression recursively calls the containing property 'Public ReadOnly Property Name As String'. Return Me.Name ~~~~~~~ BC42026: Expression recursively calls the containing property 'Public Property P1 As Integer'. Return P1() + 1 ' 1 ~~~~ BC42026: Expression recursively calls the containing property 'Public Property P1 As Integer'. P1() += 1 ' 2 ~~~~ BC42026: Expression recursively calls the containing property 'Public Property P1 As Integer'. Mid(P1(), 1) = 2 ' 3 ~~~~ BC42026: Expression recursively calls the containing property 'Public Property P1 As Integer'. PassByRef(P1()) '4 ~~~~ BC42026: Expression recursively calls the containing property 'Public Property P1 As Integer'. PassByVal(P1()) '5 ~~~~ BC42026: Expression recursively calls the containing property 'Public Property P1 As Integer'. P1() = value '6 ~~~~ BC42026: Expression recursively calls the containing property 'Public Property P1 As Integer'. P1() += 1 '7 ~~~~ BC42026: Expression recursively calls the containing property 'Public Property P1 As Integer'. Mid(P1(), 1) = 2 '8 ~~~~ BC42026: Expression recursively calls the containing property 'Public Property P1 As Integer'. PassByRef(P1()) '9 ~~~~ BC42026: Expression recursively calls the containing property 'Public Property P3 As Integer'. Return P3() + 1 '10 ~~~~ BC42026: Expression recursively calls the containing property 'Public Property P3 As Integer'. P3() += 2 ' 11 ~~~~ BC42026: Expression recursively calls the containing property 'Public Property P3 As Integer'. Mid(P3(), 1) = 2 ' 12 ~~~~ BC42026: Expression recursively calls the containing property 'Public Property P3 As Integer'. PassByRef(P3()) ' 13 ~~~~ BC42026: Expression recursively calls the containing property 'Public Property P3 As Integer'. PassByVal(P3()) ' 14 ~~~~ BC42026: Expression recursively calls the containing property 'Public Property P3 As Integer'. P3() = value ' 15 ~~~~ BC42026: Expression recursively calls the containing property 'Public Property P3 As Integer'. P3() += 2 ' 16 ~~~~ BC42026: Expression recursively calls the containing property 'Public Property P3 As Integer'. Mid(P3(), 1) = 2 ' 17 ~~~~ BC42026: Expression recursively calls the containing property 'Public Property P3 As Integer'. PassByRef(P3()) ' 18 ~~~~ BC42026: Expression recursively calls the containing property 'Public Property P4 As Integer'. P4 = value ' 19 ~~ BC42026: Expression recursively calls the containing property 'Public Property P4 As Integer'. P4 += 2 ' 20 ~~ BC42026: Expression recursively calls the containing property 'Public Property P4 As Integer'. Mid(P4, 1) = 2 ' 21 ~~ BC42026: Expression recursively calls the containing property 'Public Property P4 As Integer'. PassByRef(P4) ' 22 ~~ BC42026: Expression recursively calls the containing property 'Public Property P5 As Integer'. Return Me.P5 + 1 ' 23 ~~~~~ BC42026: Expression recursively calls the containing property 'Public Property P5 As Integer'. Me.P5 += 2 ' 24 ~~~~~ BC42026: Expression recursively calls the containing property 'Public Property P5 As Integer'. Mid(Me.P5, 1) = 2 ' 25 ~~~~~ BC42026: Expression recursively calls the containing property 'Public Property P5 As Integer'. PassByRef(Me.P5) ' 26 ~~~~~ BC42026: Expression recursively calls the containing property 'Public Property P5 As Integer'. PassByVal(Me.P5) ' 27 ~~~~~ BC42026: Expression recursively calls the containing property 'Public Property P5 As Integer'. Me.P5 = value ' 28 ~~~~~ BC42026: Expression recursively calls the containing property 'Public Property P5 As Integer'. Me.P5 += 2 ' 29 ~~~~~ BC42026: Expression recursively calls the containing property 'Public Property P5 As Integer'. Mid(Me.P5, 1) = 2 ' 30 ~~~~~ BC42026: Expression recursively calls the containing property 'Public Property P5 As Integer'. PassByRef(Me.P5) ' 31 ~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC42029WRN_OverlappingCatch() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Module Module1 Sub foo1() Try Catch ex As Exception Catch ex As SystemException Console.WriteLine(ex) End Try End Sub End Module </file> </compilation>) Dim expectedErrors1 = <errors> BC42029: 'Catch' block never reached, because 'SystemException' inherits from 'Exception'. Catch ex As SystemException ~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC42030WRN_DefAsgUseNullRefByRef1() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C Shared Sub M() Dim o As Object M(o) End Sub Shared Sub M(ByRef o As Object) End Sub End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC42030: Variable 'o' is passed by reference before it has been assigned a value. A null reference exception could result at runtime. M(o) ~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC42030WRN_DefAsgUseNullRefByRef2() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="DefAsgUseNullRefByRef"> <file name="a.vb"> Module M1 Sub foo(ByRef x As Object) End Sub Structure S1 Dim o As Object Dim e As Object End Structure Sub Main() Dim x1 As S1 x1.o = Nothing foo(x1.e) End Sub End Module </file> </compilation>) Dim expectedErrors1 = <errors> BC42030: Variable 'e' is passed by reference before it has been assigned a value. A null reference exception could result at runtime. foo(x1.e) ~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC42031WRN_DuplicateCatch() CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="DuplicateCatch"> <file name="a.vb"> Imports System Module Module1 Sub foo() Try Catch ex As Exception Catch ex As Exception End Try End Sub End Module </file> </compilation>).VerifyDiagnostics( Diagnostic(ERRID.WRN_DuplicateCatch, "Catch ex As Exception").WithArguments("System.Exception")) End Sub <Fact()> Public Sub BC42032WRN_ObjectMath1Not() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ObjectMath1Not"> <file name="a.vb"> Module Module1 Sub Main() Dim Result Dim X If Result &lt;&gt; 13 Or X &lt;&gt; Nothing Then End If End Sub End Module </file> </compilation>, TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.Custom)) Dim expectedErrors1 = <errors> BC42020: Variable declaration without an 'As' clause; type of Object assumed. Dim Result ~~~~~~ BC42020: Variable declaration without an 'As' clause; type of Object assumed. Dim X ~ BC42032: Operands of type Object used for operator '&lt;&gt;'; use the 'IsNot' operator to test object identity. If Result &lt;&gt; 13 Or X &lt;&gt; Nothing Then ~~~~~~ BC42104: Variable 'Result' is used before it has been assigned a value. A null reference exception could result at runtime. If Result &lt;&gt; 13 Or X &lt;&gt; Nothing Then ~~~~~~ BC42019: Operands of type Object used for operator 'Or'; runtime errors could occur. If Result &lt;&gt; 13 Or X &lt;&gt; Nothing Then ~~~~~~~~~~~~ BC42016: Implicit conversion from 'Object' to 'Boolean'. If Result &lt;&gt; 13 Or X &lt;&gt; Nothing Then ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42032: Operands of type Object used for operator '&lt;&gt;'; use the 'IsNot' operator to test object identity. If Result &lt;&gt; 13 Or X &lt;&gt; Nothing Then ~ BC42104: Variable 'X' is used before it has been assigned a value. A null reference exception could result at runtime. If Result &lt;&gt; 13 Or X &lt;&gt; Nothing Then ~ BC42019: Operands of type Object used for operator 'Or'; runtime errors could occur. If Result &lt;&gt; 13 Or X &lt;&gt; Nothing Then ~~~~~~~~~~~~ BC42032: Operands of type Object used for operator '&lt;&gt;'; use the 'IsNot' operator to test object identity. If Result &lt;&gt; 13 Or X &lt;&gt; Nothing Then ~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub 'vbc module1.vb /target:library /noconfig /optionstrict:custom <Fact()> Public Sub BC42036WRN_ObjectMathSelectCase() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ObjectMathSelectCase"> <file name="a.vb"> Module M1 Sub Main() Dim o As Object = 1 Select Case o Case 1 End Select End Sub End Module </file> </compilation>, New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptionStrict(OptionStrict.Custom)) Dim expectedErrors1 = <errors> BC42036: Operands of type Object used in expressions for 'Select', 'Case' statements; runtime errors could occur. Select Case o ~ BC42016: Implicit conversion from 'Object' to 'Boolean'. Case 1 ~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC42036WRN_ObjectMathSelectCase_02() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ObjectMathSelectCase"> <file name="a.vb"> Module M1 Sub Main() Dim o As Object = 1 Select Case 1 Case 2, o End Select End Sub End Module </file> </compilation>, New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptionStrict(OptionStrict.Custom)) Dim expectedErrors1 = <errors> BC42016: Implicit conversion from 'Object' to 'Boolean'. Case 2, o ~~~~~~~~~ BC42036: Operands of type Object used in expressions for 'Select', 'Case' statements; runtime errors could occur. Case 2, o ~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC42037WRN_EqualToLiteralNothing() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="EqualToLiteralNothing"> <file name="a.vb"> Module M Sub F(o As Integer?) Dim b As Boolean b = (o = Nothing) b = (Nothing = o) End Sub End Module </file> </compilation>) Dim expectedErrors1 = <errors> BC42037: This expression will always evaluate to Nothing (due to null propagation from the equals operator). To check if the value is null consider using 'Is Nothing'. b = (o = Nothing) ~~~~~~~~~~~ BC42037: This expression will always evaluate to Nothing (due to null propagation from the equals operator). To check if the value is null consider using 'Is Nothing'. b = (Nothing = o) ~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC42038WRN_NotEqualToLiteralNothing() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> <![CDATA[ Module M Sub F(o As Integer?) Dim b As Boolean b = (o <> Nothing) b = (Nothing <> o) End Sub End Module ]]> </file> </compilation>) Dim expectedErrors1 = <errors> <![CDATA[ BC42038: This expression will always evaluate to Nothing (due to null propagation from the equals operator). To check if the value is not null consider using 'IsNot Nothing'. b = (o <> Nothing) ~~~~~~~~~~~~ BC42038: This expression will always evaluate to Nothing (due to null propagation from the equals operator). To check if the value is not null consider using 'IsNot Nothing'. b = (Nothing <> o) ~~~~~~~~~~~~ ]]> </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC42104WRN_DefAsgUseNullRef() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C Shared Function F() Dim v As String Return v End Function End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC42104: Variable 'v' is used before it has been assigned a value. A null reference exception could result at runtime. Return v ~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <WorkItem(546820, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546820")> <Fact()> Public Sub BC42104WRN_DefAsgUseNullRef_StaticLocal() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Module Program Sub Main() Static TypeCharacterTable As System.Collections.Generic.Dictionary(Of String, String) If TypeCharacterTable Is Nothing Then TypeCharacterTable = New System.Collections.Generic.Dictionary(Of String, String) End If End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors></errors>) End Sub <WorkItem(542080, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542080")> <Fact()> Public Sub BC42104WRN_DefAsgUseNullRef_1() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System Class C Public Shared Sub Main() Dim x As Action For Each x In New Action() {} x.Invoke() Next x.Invoke() End Sub End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC42104: Variable 'x' is used before it has been assigned a value. A null reference exception could result at runtime. x.Invoke() ~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC42104WRN_DefAsgUseNullRef_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C Public Shared Sub Main() Dim S As String For Each x As String In "abc" For Each S In "abc" If S = "B"c Then Continue For End If Next S Next x System.Console.WriteLine(S) End Sub End Class </file> </compilation>) AssertTheseEmitDiagnostics(compilation, <errors> BC35000: Requested operation is not available because the runtime library function 'Microsoft.VisualBasic.CompilerServices.Conversions.ToString' is not defined. For Each x As String In "abc" ~~~~~ BC35000: Requested operation is not available because the runtime library function 'Microsoft.VisualBasic.CompilerServices.Conversions.ToString' is not defined. For Each S In "abc" ~~~~~ BC35000: Requested operation is not available because the runtime library function 'Microsoft.VisualBasic.CompilerServices.Operators.CompareString' is not defined. If S = "B"c Then ~~~~~~~~ BC42104: Variable 'S' is used before it has been assigned a value. A null reference exception could result at runtime. System.Console.WriteLine(S) ~ </errors>) End Sub <WorkItem(542080, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542080")> <Fact()> Public Sub BC42104WRN_DefAsgUseNullRef_3() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Class C Public Shared Sub Main() For Each x As String In "abc" Dim S As String For Each S In "abc" If S = "B"c Then Continue For End If Next S System.Console.WriteLine(S) Next x End Sub End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC42104: Variable 'S' is used before it has been assigned a value. A null reference exception could result at runtime. System.Console.WriteLine(S) ~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <WorkItem(542080, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542080")> <Fact()> Public Sub BC42104WRN_DefAsgUseNullRef_4() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Structure S Public X As Integer Public Y As String End Structure Public Module Program2 Public Sub Main(args() As String) Dim a, b As New S() With {.Y = b.Y} Dim c, d As New S() With {.Y = c.Y} Dim e, f As New S() With {.Y = .Y} End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC42104: Variable 'Y' is used before it has been assigned a value. A null reference exception could result at runtime. Dim a, b As New S() With {.Y = b.Y} ~~~ </errors>) End Sub <WorkItem(542080, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542080")> <Fact()> Public Sub BC42104WRN_DefAsgUseNullRef_5() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Structure S Public X As String Public Y As Object End Structure Public Module Program2 Public Sub Main(args() As String) Dim a, b, c As New S() With {.Y = b.X, .X = c.Y} End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC42104: Variable 'X' is used before it has been assigned a value. A null reference exception could result at runtime. Dim a, b, c As New S() With {.Y = b.X, .X = c.Y} ~~~ BC42104: Variable 'Y' is used before it has been assigned a value. A null reference exception could result at runtime. Dim a, b, c As New S() With {.Y = b.X, .X = c.Y} ~~~ </errors>) End Sub ''' <summary> ''' No warning reported for expression that will not be evaluated. ''' </summary> <Fact()> Public Sub BC42104WRN_DefAsgUseNullRef_ConstantUnevaluatedReceiver() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class A Const F As Object = Nothing Shared Function M() As Object Dim o As A Return (o).F End Function End Class </file> </compilation>) compilation.AssertTheseDiagnostics(<errors> BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. Return (o).F ~~~~~ </errors>) End Sub ''' <summary> ''' No warning reported for expression that will not be evaluated. ''' </summary> <Fact()> Public Sub BC42104WRN_DefAsgUseNullRef_CallUnevaluatedReceiver() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class A Shared Function F() As Object Return Nothing End Function Shared Function M() As Object Dim o As A Return o.F() End Function End Class </file> </compilation>) compilation.AssertTheseDiagnostics(<errors> BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. Return o.F() ~~~ </errors>) End Sub ''' <summary> ''' No warning reported for expression that will not be evaluated. ''' </summary> <Fact()> Public Sub BC42104WRN_DefAsgUseNullRef_AddressOfUnevaluatedReceiver() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class A Shared Sub M() End Sub Shared Function F() As System.Action Dim o As A Return AddressOf (o).M End Function End Class </file> </compilation>) compilation.AssertTheseDiagnostics(<errors> BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. Return AddressOf (o).M ~~~~~~~~~~~~~~~ </errors>) End Sub ''' <summary> ''' No warning reported for expression that will not be evaluated. ''' </summary> <Fact()> Public Sub BC42104WRN_DefAsgUseNullRef_TypeExpressionUnevaluatedReceiver() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class A Class B Friend Const F As Object = Nothing End Class Shared Function M() As Object Dim o As A Return o.B.F End Function End Class </file> </compilation>) compilation.AssertTheseDiagnostics(<errors> BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. Return o.B.F ~~~ </errors>) End Sub <WorkItem(528735, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528735")> <Fact()> Public Sub BC42105WRN_DefAsgNoRetValFuncRef1() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BC42105WRN_DefAsgNoRetValFuncRef1"> <file name="a.vb"> Interface I End Interface Class A End Class Class C(Of T1, T2 As Class, T3 As Structure, T4 As New, T5 As I, T6 As A, T7 As U, U) Function F0() As Object End Function ' F0 Function F1() As T1 End Function ' F1 Function F2() As T2 End Function ' F2 Function F3() As T3 End Function ' F3 Function F4() As T4 End Function ' F4 Function F5() As T5 End Function ' F5 Function F6() As T6 End Function ' F6 Function F7() As T7 End Function ' F7 End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC42105: Function 'F0' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used. End Function ' F0 ~~~~~~~~~~~~ BC42105: Function 'F2' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used. End Function ' F2 ~~~~~~~~~~~~ BC42105: Function 'F6' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used. End Function ' F6 ~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <WorkItem(545313, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545313")> <Fact()> Public Sub BC42105WRN_DefAsgNoRetValFuncRef1b() ' Make sure initializers are analyzed for errors/warnings Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="BC42105WRN_DefAsgNoRetValFuncRef1b"> <file name="a.vb"> Option Strict On Imports System Module Module1 Dim f As Func(Of String) = Function() As String End Function Sub S() Dim l As Func(Of String) = Function() As String End Function End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors><![CDATA[ BC42105: Function '<anonymous method>' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used. End Function ~~~~~~~~~~~~ BC42105: Function '<anonymous method>' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used. End Function ~~~~~~~~~~~~ ]]> </errors>) End Sub <WorkItem(837973, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/837973")> <Fact()> Public Sub Bug837973() Dim compilation1 = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation> <file name="a.vb"> Imports System Imports System.Runtime.CompilerServices Imports System.Runtime.InteropServices Imports System.Threading.Tasks 'COMPILEERRORTOTAL: 2 Public Module Async_Regress134668 Public Function MethodFunction(x As Func(Of Object)) As Integer Return 1 End Function Public Async Sub Async_Regress134668_Test() Await Task.Yield Dim i1 = MethodFunction(Async Function() As Task Await Task.Yield End Function) Dim i2 = MethodFunction(Function() As Task 'COMPILEWARNING: BC42105, "End Function" End Function) ' 1 Dim i4 = MethodFunction(Function() As Task return Nothing End Function) ' 1 Dim i3 = MethodFunction(Async Function() As Task(Of Integer) Await Task.Delay(10) 'COMPILEWARNING: BC42105, "End Function" End Function) ' 2 End Sub Public Function Async_Regress134668_Test2() As Object Async_Regress134668_Test2 = Nothing Dim i2 = MethodFunction(Function() As Task End Function) ' 3 End Function ' 4 Public Function Async_Regress134668_Test3() As Object Dim i2 = MethodFunction(Function() As Task Return Nothing End Function) End Function ' 5 End Module </file> </compilation>, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseDll) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors><![CDATA[ BC42105: Function '<anonymous method>' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used. End Function) ' 1 ~~~~~~~~~~~~ BC42105: Function '<anonymous method>' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used. End Function) ' 2 ~~~~~~~~~~~~ BC42105: Function '<anonymous method>' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used. End Function) ' 3 ~~~~~~~~~~~~ BC42105: Function 'Async_Regress134668_Test3' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used. End Function ' 5 ~~~~~~~~~~~~ ]]></errors>) End Sub <WorkItem(545313, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545313")> <Fact()> Public Sub BC42105WRN_DefAsgNoRetValFuncRef1c() ' Make sure initializers are analyzed for errors/warnings ONLY ONCE Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="BC42105WRN_DefAsgNoRetValFuncRef1c"> <file name="a.vb"> Option Strict On Imports System Class C1 Private s As Func(Of String) = Function() As String End Function Public Sub New() End Sub Public Sub New(i As Integer) MyClass.New() End Sub Public Sub New(i As Long) End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> <![CDATA[ BC42105: Function '<anonymous method>' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used. End Function ~~~~~~~~~~~~ ]]> </errors>) End Sub <Fact()> Public Sub BC42106WRN_DefAsgNoRetValOpRef1() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="DefAsgNoRetValOpSubst1"> <file name="a.vb"> Interface I End Interface Class A End Class Class C(Of T1, T2 As Class, T3 As Structure, T4 As New, T5 As I, T6 As A, T7 As U, U) Class C0 Shared Operator -(o As C0) As Object End Operator ' C0 End Class Class C1 Shared Operator -(o As C1) As T1 End Operator ' C1 End Class Class C2 Shared Operator -(o As C2) As T2 End Operator ' C2 End Class Class C3 Shared Operator -(o As C3) As T3 End Operator ' C3 End Class Class C4 Shared Operator -(o As C4) As T4 End Operator ' C4 End Class Class C5 Shared Operator -(o As C5) As T5 End Operator ' C5 End Class Class C6 Shared Operator -(o As C6) As T6 End Operator ' C6 End Class Class C7 Shared Operator -(o As C7) As T7 End Operator ' C7 End Class End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC42106: Operator '-' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used. End Operator ' C0 ~~~~~~~~~~~~ BC42106: Operator '-' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used. End Operator ' C2 ~~~~~~~~~~~~ BC42106: Operator '-' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used. End Operator ' C6 ~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC42107WRN_DefAsgNoRetValPropRef1() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="DefAsgNoRetValPropSubst1"> <file name="a.vb"> Interface I End Interface Class A End Class Class C(Of T1, T2 As Class, T3 As Structure, T4 As New, T5 As I, T6 As A, T7 As U, U) ReadOnly Property P0 As Object Get End Get ' P0 End Property ReadOnly Property P1 As T1 Get End Get ' P1 End Property ReadOnly Property P2 As T2 Get End Get ' P2 End Property ReadOnly Property P3 As T3 Get End Get ' P3 End Property ReadOnly Property P4 As T4 Get End Get ' P4 End Property ReadOnly Property P5 As T5 Get End Get ' P5 End Property ReadOnly Property P6 As T6 Get End Get ' P6 End Property ReadOnly Property P7 As T7 Get End Get ' P7 End Property End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC42107: Property 'P0' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used. End Get ' P0 ~~~~~~~ BC42107: Property 'P2' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used. End Get ' P2 ~~~~~~~ BC42107: Property 'P6' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used. End Get ' P6 ~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <WorkItem(540421, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540421")> <Fact()> Public Sub BC42108WRN_DefAsgUseNullRefByRefStr() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Structure S Public Fld As String End Structure Class C Shared Sub M(p1 As String, ByRef p2 As String) Dim s1 As S Dim s2 As S Dim l1 As String Dim a1 As String() = New String(3) {} a1(2) = "abc" M(s1) M(s2.Fld) M(l1) M(p1) M(p2) M(a1(2)) End Sub Shared Sub M(ByRef o As Object) End Sub End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC42108: Variable 's1' is passed by reference before it has been assigned a value. A null reference exception could result at runtime. Make sure the structure or all the reference members are initialized before use M(s1) ~~ BC42030: Variable 'Fld' is passed by reference before it has been assigned a value. A null reference exception could result at runtime. M(s2.Fld) ~~~~~~ BC42030: Variable 'l1' is passed by reference before it has been assigned a value. A null reference exception could result at runtime. M(l1) ~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC42108_NoWarningForOutParameter() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Structure SSS Public F As String End Structure Module Program Sub Main(args As String()) Dim s As SSS Call (New Dictionary(Of Integer, SSS)).TryGetValue(1, s) End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC42108: Variable 's' is passed by reference before it has been assigned a value. A null reference exception could result at runtime. Make sure the structure or all the reference members are initialized before use Call (New Dictionary(Of Integer, SSS)).TryGetValue(1, s) ~ </errors>) End Sub <Fact()> Public Sub BC42108_StillWarningForLateBinding() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Structure SSS Public F As String End Structure Module Program Sub Main(args As String()) Dim s As SSS Dim o As Object = New Dictionary(Of Integer, SSS) o.TryGetValue(1, s) End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC42108: Variable 's' is passed by reference before it has been assigned a value. A null reference exception could result at runtime. Make sure the structure or all the reference members are initialized before use o.TryGetValue(1, s) ~ </errors>) End Sub <WorkItem(540421, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540421")> <Fact()> Public Sub BC42108WRN_DefAsgUseNullRefByRefStr2() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Class C Public Fld As String End Class Class CC Public FldC As C Public FldS As S End Class Structure S Public Fld As String End Structure Structure SS Public FldC As C Public FldS As S End Structure Class Main Shared Sub M(p1 As String, ByRef p2 As String) Dim s1 As S Dim s2 As SS Dim s3 As SS Dim c1 As C Dim c2 As CC Dim c3 As CC M(s1.Fld) M(s2.FldS.Fld) M(s3.FldC.Fld) M(c1.Fld) M(c2.FldS.Fld) M(c3.FldC.Fld) End Sub Shared Sub M(ByRef o As Object) End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC42030: Variable 'Fld' is passed by reference before it has been assigned a value. A null reference exception could result at runtime. M(s1.Fld) ~~~~~~ BC42030: Variable 'Fld' is passed by reference before it has been assigned a value. A null reference exception could result at runtime. M(s2.FldS.Fld) ~~~~~~~~~~~ BC42104: Variable 'FldC' is used before it has been assigned a value. A null reference exception could result at runtime. M(s3.FldC.Fld) ~~~~~~~ BC42104: Variable 'c1' is used before it has been assigned a value. A null reference exception could result at runtime. M(c1.Fld) ~~ BC42104: Variable 'c2' is used before it has been assigned a value. A null reference exception could result at runtime. M(c2.FldS.Fld) ~~ BC42104: Variable 'c3' is used before it has been assigned a value. A null reference exception could result at runtime. M(c3.FldC.Fld) ~~ </errors>) End Sub <Fact()> Public Sub BC42109WRN_DefAsgUseNullRefStr() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Structure S Public F As Object End Structure Class C Shared Sub M() Dim s As S M(s) End Sub Shared Sub M(o As Object) End Sub End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC42109: Variable 's' is used before it has been assigned a value. A null reference exception could result at runtime. Make sure the structure or all the reference members are initialized before use M(s) ~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <WorkItem(546818, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546818")> <Fact()> Public Sub BC42109WRN_DefAsgUseNullRefStr_NoError() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System Public Structure AccObjFromWindow Public hwnd As IntPtr Public ppvObject As Object End Structure Class SSS Public Sub S() Dim input As AccObjFromWindow input.hwnd = IntPtr.Zero input.ppvObject = Nothing Dim a = input End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors></errors>) End Sub <WorkItem(547098, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547098")> <Fact()> Public Sub BC42109WRN_DefAsgUseNullRefStr_NoError2() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Module Module1 Sub Main() Dim s As str1 Dim sTmp As String = "" AddHandler s.e1, AddressOf s.sub1 Call s.revent(True, sTmp) AddHandler s.e1, AddressOf s.sub2 sTmp = "" Call s.revent(True, sTmp) ' place BP here End Sub End Module Structure str1 Dim i As Integer Public Event e1(ByVal b As Boolean, ByRef s As String) Sub revent(ByVal b As Boolean, ByRef s As String) RaiseEvent e1(b, s) End Sub Sub sub1(ByVal b As Boolean, ByRef s As String) s = s &amp; "1" End Sub Sub sub2(ByVal b As Boolean, ByRef s As String) s = s &amp; "2" End Sub End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors></errors>) End Sub <WorkItem(546377, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546377")> <WorkItem(546423, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546423")> <WorkItem(546420, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546420")> <Fact()> Public Sub Bug15747() Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Module Program Sub Main() Dim hscr As IntPtr Try hscr = New IntPtr Catch ex As Exception If Not hscr.Equals(IntPtr.Zero) Then End If End Try End Sub End Module </file> </compilation>).VerifyDiagnostics() End Sub <WorkItem(546377, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546377")> <WorkItem(546423, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546423")> <WorkItem(546420, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546420")> <Fact()> Public Sub Bug15747b() Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Module Program Sub Main() Dim hscr As UIntPtr Try hscr = New UIntPtr Catch ex As Exception If Not hscr.Equals(UIntPtr.Zero) Then End If End Try End Sub End Module </file> </compilation>).VerifyDiagnostics() End Sub <WorkItem(546175, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546175")> <Fact()> Public Sub BC42109WRN_DefAsgUseNullRefStr_Dev11Compat() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Public Structure NonGenericReference Private s As String Public Structure GenericReference(Of T) Private s As String End Structure End Structure Public Structure GenericReference(Of T) Private s As String Public Structure NonGenericReference Private s As String End Structure End Structure Public Structure GenericReference2(Of T) Private s2 As Integer End Structure </file> </compilation>) Dim reference1 = compilation1.EmitToImageReference() Dim reference2 = CreateReferenceFromIlCode(<![CDATA[ .class public sequential ansi sealed beforefieldinit GenericWithPtr`1<T> extends [mscorlib]System.ValueType { //.field private int32* aa } // end of class GenericWithPtr`1 ]]>.Value) Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim a As NonGenericReference Dim b As GenericReference(Of Integer) Dim c As GenericReference(Of String) Dim d As NonGenericReference.GenericReference(Of Integer) Dim e As NonGenericReference.GenericReference(Of String) Dim f As GenericReference(Of Integer).NonGenericReference Dim g As GenericReference(Of String).NonGenericReference Dim i As GenericReference2(Of Integer) Dim j As GenericReference2(Of String) Dim k As GenericWithPtr(Of Integer) Dim z1 = a ' No Warning Dim z2 = b Dim z3 = c Dim z4 = d Dim z5 = e Dim z6 = f Dim z7 = g Dim z8 = i ' No Warning Dim z9 = j ' No Warning Dim za = k ' No Warning End Sub End Module </file> </compilation>, references:={reference1, reference2}). VerifyDiagnostics(Diagnostic(ERRID.WRN_DefAsgUseNullRefStr, "b").WithArguments("b"), Diagnostic(ERRID.WRN_DefAsgUseNullRefStr, "c").WithArguments("c"), Diagnostic(ERRID.WRN_DefAsgUseNullRefStr, "d").WithArguments("d"), Diagnostic(ERRID.WRN_DefAsgUseNullRefStr, "e").WithArguments("e"), Diagnostic(ERRID.WRN_DefAsgUseNullRefStr, "f").WithArguments("f"), Diagnostic(ERRID.WRN_DefAsgUseNullRefStr, "g").WithArguments("g")) End Sub <WorkItem(546175, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546175")> <Fact()> Public Sub BC42109WRN_DefAsgUseNullRefStr_Dev11Compat2() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Public Structure NonGenericReference Private s As String Public Structure GenericReference(Of T) Private s As String End Structure End Structure Public Structure GenericReference(Of T) Private s As String Public Structure NonGenericReference Private s As String End Structure End Structure Public Structure GenericReference2(Of T) Private s2 As Integer End Structure </file> </compilation>) Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim a As NonGenericReference Dim b As GenericReference(Of Integer) Dim c As GenericReference(Of String) Dim d As NonGenericReference.GenericReference(Of Integer) Dim e As NonGenericReference.GenericReference(Of String) Dim f As GenericReference(Of Integer).NonGenericReference Dim g As GenericReference(Of String).NonGenericReference Dim i As GenericReference2(Of Integer) Dim j As GenericReference2(Of String) Dim z1 = a ' Warning!!! Dim z2 = b Dim z3 = c Dim z4 = d Dim z5 = e Dim z6 = f Dim z7 = g Dim z8 = i ' No Warning Dim z9 = j ' No Warning End Sub End Module </file> </compilation>, references:={New VisualBasicCompilationReference(compilation1)}). VerifyDiagnostics(Diagnostic(ERRID.WRN_DefAsgUseNullRefStr, "a").WithArguments("a"), Diagnostic(ERRID.WRN_DefAsgUseNullRefStr, "b").WithArguments("b"), Diagnostic(ERRID.WRN_DefAsgUseNullRefStr, "c").WithArguments("c"), Diagnostic(ERRID.WRN_DefAsgUseNullRefStr, "d").WithArguments("d"), Diagnostic(ERRID.WRN_DefAsgUseNullRefStr, "e").WithArguments("e"), Diagnostic(ERRID.WRN_DefAsgUseNullRefStr, "f").WithArguments("f"), Diagnostic(ERRID.WRN_DefAsgUseNullRefStr, "g").WithArguments("g")) End Sub <WorkItem(652008, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/652008")> <Fact()> Public Sub BC42110WRN_FieldInForNotExplicit_DiagnosticRemoved() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="FieldInForNotExplicit"> <file name="a.vb"> Class Customer Private Index As Integer Sub Main() For Index = 1 To 10 Next End Sub End Class </file> </compilation>) Dim expectedErrors1 = <errors></errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC42322WRN_InterfaceConversion2() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim xx As System.Collections.Generic.IEnumerator(Of Integer) = "hello" End Sub End Module </file> </compilation>) Dim expectedErrors1 = <errors> BC42322: Runtime errors might occur when converting 'String' to 'IEnumerator(Of Integer)'. Dim xx As System.Collections.Generic.IEnumerator(Of Integer) = "hello" ~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <WorkItem(545479, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545479")> <Fact()> Public Sub BC42322WRN_InterfaceConversion2_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="c.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Public Interface I End Interface <C(DirectCast(New C(""), I))> <ComImport()> NotInheritable Class C Inherits Attribute Public Sub New(s As String) End Sub End Class ]]></file> </compilation>) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC30934: Conversion from 'I' to 'String' cannot occur in a constant expression used as an argument to an attribute. <C(DirectCast(New C(""), I))> ~~~~~~~~~~~~~~~~~~~~~~~~ BC42322: Runtime errors might occur when converting 'I' to 'String'. <C(DirectCast(New C(""), I))> ~~~~~~~~~~~~~~~~~~~~~~~~ ]]></errors>) End Sub <Fact()> Public Sub BC42324WRN_LiftControlVariableLambda() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="LiftControlVariableLambda"> <file name="a.vb"> Imports System Class Customer Sub Main() For i As Integer = 1 To (function() i + 10)() Dim exampleFunc1 As Func(Of Integer) = Function() i Next ' since Dev11 the scope for foreach loops has been changed; no warnings here For each j as integer in (function(){1+j, 2+j})() Dim exampleFunc2 As Func(Of Integer) = Function() j Next End Sub End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC42324: Using the iteration variable in a lambda expression may have unexpected results. Instead, create a local variable within the loop and assign it the value of the iteration variable. For i As Integer = 1 To (function() i + 10)() ~ BC42324: Using the iteration variable in a lambda expression may have unexpected results. Instead, create a local variable within the loop and assign it the value of the iteration variable. Dim exampleFunc1 As Func(Of Integer) = Function() i ~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC42326WRN_LambdaPassedToRemoveHandler() CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="LambdaPassedToRemoveHandler"> <file name="a.vb"> Module Module1 Event ProcessInteger(ByVal x As Integer) Sub Main() AddHandler ProcessInteger, Function(m As Integer) m RemoveHandler ProcessInteger, Function(m As Integer) m End Sub End Module </file> </compilation>).VerifyDiagnostics(Diagnostic(ERRID.WRN_LambdaPassedToRemoveHandler, "Function(m As Integer) m")) End Sub <WorkItem(545252, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545252")> <Fact()> Public Sub BC30413ERR_WithEventsIsDelegate() CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="LambdaPassedToRemoveHandler"> <file name="a.vb"> Imports System Class Derived WithEvents e As Action = Sub() Exit Sub WithEvents e1, e2 As New Integer() End Class </file> </compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_WithEventsAsStruct, "e"), Diagnostic(ERRID.ERR_WithEventsAsStruct, "e1"), Diagnostic(ERRID.ERR_WithEventsAsStruct, "e2")) End Sub <WorkItem(545195, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545195")> <Fact()> Public Sub BC42328WRN_RelDelegatePassedToRemoveHandler() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="RelDelegatePassedToRemoveHandler"> <file name="a.vb"> Class A Public Val As Integer Sub New(ByVal i As Integer) Val = i End Sub End Class Class B Inherits A Sub New(ByVal i As Integer) MyBase.New(i) End Sub End Class Class C1 Delegate Sub HandlerNum(ByVal i As Integer) Delegate Sub HandlerCls(ByVal a As B) Dim WithEvents inner As C1 Event evtNum As HandlerNum Event evtCls As HandlerCls Sub HandleLong1(ByVal l As Long) End Sub Sub HandlesWithNum(ByVal l As Long) Handles inner.evtNum End Sub Sub foo() RemoveHandler evtNum, AddressOf HandleLong1 inner = New C1() RemoveHandler inner.evtNum, AddressOf HandlesWithNum End Sub End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC42328: The 'AddressOf' expression has no effect in this context because the method argument to 'AddressOf' requires a relaxed conversion to the delegate type of the event. Assign the 'AddressOf' expression to a variable, and use the variable to add or remove the method as the handler. RemoveHandler evtNum, AddressOf HandleLong1 ~~~~~~~~~~~ BC42328: The 'AddressOf' expression has no effect in this context because the method argument to 'AddressOf' requires a relaxed conversion to the delegate type of the event. Assign the 'AddressOf' expression to a variable, and use the variable to add or remove the method as the handler. RemoveHandler inner.evtNum, AddressOf HandlesWithNum ~~~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC42335WRN_TypeInferenceAssumed3() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="TypeInferenceAssumed3"> <file name="a.vb"> Option Strict On Imports System.Collections.Generic Module M1 Sub foo() foo1({}) foo1({Nothing}) Foo2({}, {}) Foo2({Nothing}, {Nothing}) Foo2({Nothing}, {}) End Sub Sub foo1(Of t)(ByVal x As t()) End Sub Sub Foo2(Of t)(ByVal x As t, ByVal y As t) End Sub End Module </file> </compilation>) Dim expectedErrors1 = <errors> BC42335: Data type of 't' in 'Public Sub foo1(Of t)(x As t())' could not be inferred. 'Object' assumed. foo1({}) ~~ BC42335: Data type of 't' in 'Public Sub foo1(Of t)(x As t())' could not be inferred. 'Object' assumed. foo1({Nothing}) ~~~~~~~~~ BC42335: Data type of 't' in 'Public Sub Foo2(Of t)(x As t, y As t)' could not be inferred. 'Object()' assumed. Foo2({}, {}) ~~ BC42335: Data type of 't' in 'Public Sub Foo2(Of t)(x As t, y As t)' could not be inferred. 'Object()' assumed. Foo2({Nothing}, {Nothing}) ~~~~~~~~~ BC42335: Data type of 't' in 'Public Sub Foo2(Of t)(x As t, y As t)' could not be inferred. 'Object()' assumed. Foo2({Nothing}, {}) ~~~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC42349WRN_ObsoleteIdentityDirectCastForValueType() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="ObsoleteIdentityDirectCastForValueType"> <file name="a.vb"> Class cls Sub test() Dim l1 = DirectCast(1L, Long) End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42349: Using DirectCast operator to cast a value-type to the same type is obsolete. Dim l1 = DirectCast(1L, Long) ~~ </expected>) End Sub <Fact()> Public Sub BC42349WRN_ObsoleteIdentityDirectCastForValueType_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="ObsoleteIdentityDirectCastForValueType"> <file name="a.vb"> Class C1 function test() return DirectCast(True, Boolean) End function End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42349: Using DirectCast operator to cast a value-type to the same type is obsolete. return DirectCast(True, Boolean) ~~~~ </expected>) End Sub <Fact()> Public Sub BC42351WRN_MutableStructureInUsing() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="MutableStructureInUsing"> <file name="a.vb"> Imports System Structure MutableStructure Implements IDisposable Dim dummy As Integer ' this field triggers the warning Public Sub Dispose() Implements System.IDisposable.Dispose End Sub End Structure Structure ImmutableStructure Implements IDisposable Public Shared disposed As Integer Public Sub Dispose() Implements System.IDisposable.Dispose disposed = disposed + 1 End Sub End Structure Class ReferenceType Implements IDisposable Dim dummy As Integer Public Sub Dispose() Implements System.IDisposable.Dispose End Sub End Class Module M1 Sub foo() ' resource type is a concrete structure + immutable (OK) Using a As New ImmutableStructure() End Using Using New ImmutableStructure() ' ok End Using ' resource type is a concrete structure + mutable (Warning) Using b As New MutableStructure() End Using Using New MutableStructure() ' as expression also ok. End Using ' reference types + mutable (OK) Using c As New ReferenceType() End Using Using New ReferenceType() ' ok End Using End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42351: Local variable 'b' is read-only and its type is a structure. Invoking its members or passing it ByRef does not change its content and might lead to unexpected results. Consider declaring this variable outside of the 'Using' block. Using b As New MutableStructure() ~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC42351WRN_MutableStructureInUsingGenericConstraints() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="BC42351WRN_MutableStructureInUsingGenericConstraints"> <file name="a.vb"> Imports System Structure MutableStructure Implements IDisposable Dim dummy As Integer ' this field triggers the warning Public Sub Dispose() Implements System.IDisposable.Dispose End Sub End Structure Structure ImmutableStructure Implements IDisposable Public Shared disposed As Integer Public Sub Dispose() Implements System.IDisposable.Dispose disposed = disposed + 1 End Sub End Structure Class ReferenceType Implements IDisposable Dim dummy As Integer Public Sub Dispose() Implements System.IDisposable.Dispose End Sub End Class Module M1 Sub foo(Of T as {Structure, IDisposable}, U as {ReferenceType, New, IDisposable}, V as {Structure})() ' resource type is a type parameter with a structure constraint (Warning, always) Using a As T = Directcast(new MutableStructure(), IDisposable) End Using ' resource type is a type parameter with a reference type constraint (OK) Using b As U = TryCast(new ReferenceType(), U) End Using ' resource type is a type parameter with a structure constraint (Warning, always) Using c As V = DirectCast(new ImmutableStructure(), IDisposable) End Using End Sub End Module ' Getting a concrete structure as a class constraint through overridden generic methods Class BaseGeneric(Of S) Public Overridable Sub MySub(Of T As S)(param As T) End Sub End Class Class DerivedImmutable Inherits BaseGeneric(Of ImmutableStructure) Public Overrides Sub MySub(Of T As ImmutableStructure)(param As T) Using immutable As T = New ImmutableStructure() ' OK End Using End Sub End Class Class DerivedMutable Inherits BaseGeneric(Of MutableStructure) Public Overrides Sub MySub(Of T As MutableStructure)(param As T) Using mutable As T = New MutableStructure() ' shows warning End Using End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42351: Local variable 'a' is read-only and its type is a structure. Invoking its members or passing it ByRef does not change its content and might lead to unexpected results. Consider declaring this variable outside of the 'Using' block. Using a As T = Directcast(new MutableStructure(), IDisposable) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36010: 'Using' operand of type 'V' must implement 'System.IDisposable'. Using c As V = DirectCast(new ImmutableStructure(), IDisposable) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42351: Local variable 'c' is read-only and its type is a structure. Invoking its members or passing it ByRef does not change its content and might lead to unexpected results. Consider declaring this variable outside of the 'Using' block. Using c As V = DirectCast(new ImmutableStructure(), IDisposable) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42351: Local variable 'mutable' is read-only and its type is a structure. Invoking its members or passing it ByRef does not change its content and might lead to unexpected results. Consider declaring this variable outside of the 'Using' block. Using mutable As T = New MutableStructure() ' shows warning ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC42352WRN_MutableGenericStructureInUsing() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="MutableGenericStructureInUsing"> <file name="a.vb"> Imports System Module M1 Class ReferenceType Implements IDisposable Dim dummy As Integer Public Sub Dispose() Implements System.IDisposable.Dispose End Sub End Class Sub Foo(Of T As {New, IDisposable}, U As {New, IDisposable})(ByVal x As T) 'COMPILEWARNING: BC42352, "a", BC42352, "b" Using a as T = DirectCast(New ReferenceType(), IDisposable), b As New U() End Using End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42352: Local variable 'a' is read-only. When its type is a structure, invoking its members or passing it ByRef does not change its content and might lead to unexpected results. Consider declaring this variable outside of the 'Using' block. Using a as T = DirectCast(New ReferenceType(), IDisposable), b As New U() ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42352: Local variable 'b' is read-only. When its type is a structure, invoking its members or passing it ByRef does not change its content and might lead to unexpected results. Consider declaring this variable outside of the 'Using' block. Using a as T = DirectCast(New ReferenceType(), IDisposable), b As New U() ~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC42353WRN_DefAsgNoRetValFuncVal1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Structure gStr1(Of T) Function Fun1(ByVal t1 As T) As Boolean End Function End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42353: Function 'Fun1' doesn't return a value on all code paths. Are you missing a 'Return' statement? End Function ~~~~~~~~~~~~ </expected>) End Sub <WorkItem(542802, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542802")> <Fact()> Public Sub BC42353WRN_DefAsgNoRetValFuncVal1_Lambda() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="a.vb"> Imports System.Linq Class BaseClass Sub Method() Dim x = New Integer() {} x.Where(Function(y) Exit Function Return y = "" End Function) End Sub End Class Class DerivedClass Inherits BaseClass Shared Sub Main() End Sub End Class </file> </compilation>, {Net40.SystemCore}) VerifyDiagnostics(compilation, Diagnostic(ERRID.WRN_DefAsgNoRetValFuncVal1, "End Function").WithArguments("<anonymous method>")) End Sub <WorkItem(542816, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542816")> <Fact()> Public Sub BC42353WRN_DefAsgNoRetValFuncVal1_Lambda_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="a.vb"> Imports System.Linq Class BaseClass Function Method() Dim x = New Integer() {} x.Where(Function(y) Exit Function ' 0 Return y = "" End Function) ' 1 End Function ' 2 End Class Class DerivedClass Inherits BaseClass Shared Sub Main() End Sub End Class </file> </compilation>, {Net40.SystemCore}) AssertTheseDiagnostics(compilation, <expected><![CDATA[ BC42353: Function '<anonymous method>' doesn't return a value on all code paths. Are you missing a 'Return' statement? End Function) ' 1 ~~~~~~~~~~~~ BC42105: Function 'Method' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used. End Function ' 2 ~~~~~~~~~~~~ ]]></expected>) End Sub <Fact()> Public Sub BC42353WRN_DefAsgNoRetValFuncVal1_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Structure gStr1 Function Fun1(y As Integer) As Boolean Exit Function 'Return y = "" End Function End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42353: Function 'Fun1' doesn't return a value on all code paths. Are you missing a 'Return' statement? End Function ~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC42353WRN_DefAsgNoRetValFuncVal1_Query_Lambda() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="a.vb"> Imports System Imports System.Linq Imports System.Runtime.CompilerServices Class BaseClass Sub Method() Dim x = New Integer() {} x.Where(Function(y) Exit Function Return y = "" End Function) End Sub End Class Class DerivedClass Inherits BaseClass Shared Sub Main() End Sub End Class </file> </compilation>, {Net40.SystemCore}) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42353: Function '&lt;anonymous method&gt;' doesn't return a value on all code paths. Are you missing a 'Return' statement? End Function) ~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC42354WRN_DefAsgNoRetValOpVal1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C Shared Operator -(x As C) As Integer End Operator End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42354: Operator '-' doesn't return a value on all code paths. Are you missing a 'Return' statement? End Operator ~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC42355WRN_DefAsgNoRetValPropVal1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C Shared F As Boolean Shared ReadOnly Property P As Integer Get If F Then Return 0 End If End Get End Property End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42355: Property 'P' doesn't return a value on all code paths. Are you missing a 'Return' statement? End Get ~~~~~~~ </expected>) End Sub <Fact()> Public Sub BC42356WRN_UnreachableCode_MethodBody() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Module M1 Sub Main() dim x as integer = 0 goto l1 if x > 0 then l1: Console.WriteLine("hello 1.") end if goto l2 Console.WriteLine("hello 2.") Console.WriteLine("hello 3.") l2: End Sub End Module </file> </compilation>) Dim expectedErrors1 = <errors> </errors> CompilationUtils.AssertTheseDiagnostics(compilation, expectedErrors1) End Sub <Fact()> Public Sub BC42356WRN_UnreachableCode_LambdaBody() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Module M1 Sub Main() dim y as Action = sub() dim x as integer = 0 goto l1 if x > 0 then l1: Console.WriteLine("hello 1.") end if goto l2 Console.WriteLine("hello 2.") Console.WriteLine("hello 3.") l2: End Sub End Sub End Module </file> </compilation>) Dim expectedErrors1 = <errors> </errors> CompilationUtils.AssertTheseDiagnostics(compilation, expectedErrors1) End Sub <Fact()> Public Sub BC42359WRN_EmptyPrefixAndXmlnsLocalName() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports <xmlns:empty=""> Module M Private F As Object = <x empty:xmlns="http://roslyn"/> End Module ]]></file> </compilation>, references:=XmlReferences) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC42368: The xmlns attribute has special meaning and should not be written with a prefix. Private F As Object = <x empty:xmlns="http://roslyn"/> ~~~~~~~~~~~ ]]></errors>) End Sub <Fact()> Public Sub BC42360WRN_PrefixAndXmlnsLocalName() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports <xmlns:p1="http://roslyn/"> Module M Private F1 As Object = <x p1:xmlns="http://roslyn/1"/> Private F2 As Object = <x p2:xmlns="http://roslyn/2"/> Private F3 As Object = <x xmlns:p3="http://roslyn/3a" p3:xmlns="http://roslyn/3b"/> End Module ]]></file> </compilation>, references:=XmlReferences) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC42360: It is not recommended to have attributes named xmlns. Did you mean to write 'xmlns:p1' to define a prefix named 'p1'? Private F1 As Object = <x p1:xmlns="http://roslyn/1"/> ~~~~~~~~ BC31148: XML namespace prefix 'p2' is not defined. Private F2 As Object = <x p2:xmlns="http://roslyn/2"/> ~~ BC42360: It is not recommended to have attributes named xmlns. Did you mean to write 'xmlns:p2' to define a prefix named 'p2'? Private F2 As Object = <x p2:xmlns="http://roslyn/2"/> ~~~~~~~~ BC42360: It is not recommended to have attributes named xmlns. Did you mean to write 'xmlns:p3' to define a prefix named 'p3'? Private F3 As Object = <x xmlns:p3="http://roslyn/3a" p3:xmlns="http://roslyn/3b"/> ~~~~~~~~ ]]></errors>) End Sub #End Region <Fact> Public Sub Bug17315_CompilationUnit() Dim c = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation name="C"> <file> End Class </file> </compilation>, Enumerable.Empty(Of MetadataReference)()) c.AssertTheseDiagnostics( <errors> BC30002: Type 'System.Void' is not defined. End Class ~~~~~~~~~ BC30460: 'End Class' must be preceded by a matching 'Class'. End Class ~~~~~~~~~ BC31091: Import of type 'Object' from assembly or module 'C.dll' failed. End Class ~~~~~~~~~ </errors>) End Sub <WorkItem(938459, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/938459")> <Fact> Public Sub UnimplementedMethodsIncorrectSquiggleLocationInterfaceInheritanceOrdering() Dim c = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="C"> <file> Module Module1 Sub Main() End Sub End Module Interface IBase Sub method1() End Interface Interface IBase2 Sub method2() End Interface Interface IDerived Inherits IBase Sub method3() End Interface Interface IDerived2 Inherits IDerived Sub method4() End Interface Class foo Implements IDerived2, IDerived, IBase, IBase2 Public Sub method1() Implements IBase.method1 End Sub Public Sub method2() Implements IBase2.method2 End Sub Public Sub method4() Implements IDerived2.method4 End Sub End Class </file> </compilation>) c.AssertTheseDiagnostics( <errors> BC30149: Class 'foo' must implement 'Sub method3()' for interface 'IDerived'. Implements IDerived2, IDerived, IBase, IBase2 ~~~~~~~~ </errors>) ' Change order so interfaces are defined in a completely different order. ' The bug related to order of interfaces. c = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="C"> <file> Module Module1 Sub Main() End Sub End Module Interface IBase Sub method1() End Interface Interface IBase2 Sub method2() End Interface Interface IDerived Inherits IBase Sub method3() End Interface Interface IDerived2 Inherits IDerived Sub method4() End Interface Class foo Implements IBase, IBase2, IDerived2, IDerived Public Sub method4() Implements IDerived2.method4 End Sub Public Sub method1() Implements IBase.method1 End Sub Public Sub method2() Implements IBase2.method2 End Sub End Class </file> </compilation>) c.AssertTheseDiagnostics( <errors> BC30149: Class 'foo' must implement 'Sub method3()' for interface 'IDerived'. Implements IBase, IBase2, IDerived2, IDerived ~~~~~~~~ </errors>) End Sub <Fact> Public Sub Bug17315_Namespace() Dim c = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation name="C"> <file> Namespace N Sub Foo End Sub End Namespace </file> </compilation>, Enumerable.Empty(Of MetadataReference)()) c.AssertTheseDiagnostics( <errors> BC30002: Type 'System.Void' is not defined. Namespace N ~~~~~~~~~~~~ BC31091: Import of type 'Object' from assembly or module 'C.dll' failed. Namespace N ~~~~~~~~~~~~ BC30001: Statement is not valid in a namespace. Sub Foo ~~~~~~~ BC30002: Type 'System.Void' is not defined. Sub Foo ~~~~~~~~ </errors>) End Sub <Fact(), WorkItem(530126, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530126")> Public Sub Bug_15314_Class() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="NotYetImplementedInRoslyn"> <file name="a.vb"> Public Class C Public Sub New() Protected Class D Public Sub New() End Class End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC30026: 'End Sub' expected. Public Sub New() ~~~~~~~~~~~~~~~~ BC30289: Statement cannot appear within a method body. End of method assumed. Protected Class D ~~~~~~~~~~~~~~~~~ BC30026: 'End Sub' expected. Public Sub New() ~~~~~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact(), WorkItem(530126, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530126")> Public Sub Bug_15314_Interface() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="NotYetImplementedInRoslyn"> <file name="a.vb"> Public Class C Public Sub New() Protected Interface D End Interface End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC30026: 'End Sub' expected. Public Sub New() ~~~~~~~~~~~~~~~~ BC30289: Statement cannot appear within a method body. End of method assumed. Protected Interface D ~~~~~~~~~~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact(), WorkItem(530126, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530126")> Public Sub Bug_15314_Enum() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="NotYetImplementedInRoslyn"> <file name="a.vb"> Public Class CE Public Sub New() Protected Enum DE blah End Enum End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC30026: 'End Sub' expected. Public Sub New() ~~~~~~~~~~~~~~~~ BC30289: Statement cannot appear within a method body. End of method assumed. Protected Enum DE ~~~~~~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact(), WorkItem(530126, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530126")> Public Sub Bug_15314_Structure() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="NotYetImplementedInRoslyn"> <file name="a.vb"> Public Class CS Public Sub New() Protected Structure DS End Structure End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC30026: 'End Sub' expected. Public Sub New() ~~~~~~~~~~~~~~~~ BC30289: Statement cannot appear within a method body. End of method assumed. Protected Structure DS ~~~~~~~~~~~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub Bug4185() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="NotYetImplementedInRoslyn"> <file name="a.vb"> Public Class Hello5 Public Shared Sub Main(args As String()) System.Console.WriteLine("Hello, World!") Environent.ExitCode = 0 End Sub End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC30451: 'Environent' is not declared. It may be inaccessible due to its protection level. Environent.ExitCode = 0 ~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact(), WorkItem(545179, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545179")> Public Sub Bug13459() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="NotYetImplementedInRoslyn"> <file name="a.vb"> Imports System Module Program Function ReturnVoid() As System.Void Throw New Exception() End Function Sub Main() Dim x = Function() As System.Void Throw New Exception() End Function End Sub End Module </file> </compilation>) Dim expectedErrors1 = <errors> BC31422: 'System.Void' can only be used in a GetType expression. Function ReturnVoid() As System.Void ~~~~~~~~~~~ BC31422: 'System.Void' can only be used in a GetType expression. Dim x = Function() As System.Void ~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <WorkItem(541066, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541066")> <Fact()> Public Sub BaseConstructorImplicitCallWithoutSystemVoid() Dim compilation1 = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation name="BaseConstructorImplicitCallWithoutSystemVoid"> <file name="a.vb"> Public Class C1 Public Sub New() End Sub End Class Public Class C2 Inherits C1 End Class </file> </compilation>, Enumerable.Empty(Of MetadataReference)()) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC31091: Import of type 'Object' from assembly or module 'BaseConstructorImplicitCallWithoutSystemVoid.dll' failed. Public Class C1 ~~ BC30002: Type 'System.Void' is not defined. Public Sub New() ~~~~~~~~~~~~~~~~~ BC30002: Type 'System.Void' is not defined. Public Class C2 ~~~~~~~~~~~~~~~~~ </errors>) End Sub <WorkItem(541066, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541066")> <Fact()> Public Sub ParamArrayBindingCheckForAttributeConstructor() Dim compilation1 = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation name="ParamArrayBindingCheckForAttributeConstructor"> <file name="a.vb"> Public Class C1 Public Sub S(ParamArray p As String()) End Sub End Class </file> </compilation>, Enumerable.Empty(Of MetadataReference)()) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC30002: Type 'System.Void' is not defined. Public Class C1 ~~~~~~~~~~~~~~~~~ BC31091: Import of type 'Object' from assembly or module 'ParamArrayBindingCheckForAttributeConstructor.dll' failed. Public Class C1 ~~ BC30002: Type 'System.Void' is not defined. Public Sub S(ParamArray p As String()) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC35000: Requested operation is not available because the runtime library function 'System.ParamArrayAttribute..ctor' is not defined. Public Sub S(ParamArray p As String()) ~~~~~~~~~~~~~~~~~~~~~~~~ BC30002: Type 'System.String' is not defined. Public Sub S(ParamArray p As String()) ~~~~~~ </errors>) End Sub <WorkItem(541066, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541066")> <Fact()> Public Sub DefaultPropertyBindingCheckForAttributeConstructor() Dim compilation1 = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation name="DefaultPropertyBindingCheckForAttributeConstructor"> <file name="a.vb"> Public Class C1 Public Default Property P(prop As String) Get Return Nothing End Get Set End Set End Property End Class </file> </compilation>, Enumerable.Empty(Of MetadataReference)()) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC30002: Type 'System.Void' is not defined. Public Class C1 ~~~~~~~~~~~~~~~~ BC31091: Import of type 'Object' from assembly or module 'DefaultPropertyBindingCheckForAttributeConstructor.dll' failed. Public Class C1 ~~ BC35000: Requested operation is not available because the runtime library function 'System.Reflection.DefaultMemberAttribute..ctor' is not defined. Public Default Property P(prop As String) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30002: Type 'System.Object' is not defined. Public Default Property P(prop As String) ~ BC30002: Type 'System.String' is not defined. Public Default Property P(prop As String) ~~~~~~ BC30002: Type 'System.Void' is not defined. Set ~~~ </errors>) End Sub <WorkItem(541066, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541066")> <Fact()> Public Sub ConstBindingCheckForDateTimeConstantConstructor() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="DefaultPropertyBindingCheckForAttributeConstructor"> <file name="a.vb"> Imports System Public Class C1 Const DT1 As DateTime = #01/01/2000# Const DT2 = #01/01/2000# End Class </file> <file name="b.vb"> Namespace System.Runtime.CompilerServices Public Class DateTimeConstantAttribute Public Sub New(a As String) End Sub End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC35000: Requested operation is not available because the runtime library function 'System.Runtime.CompilerServices.DateTimeConstantAttribute..ctor' is not defined. Const DT1 As DateTime = #01/01/2000# ~~~~~~~~~~~~~~ BC35000: Requested operation is not available because the runtime library function 'System.Runtime.CompilerServices.DateTimeConstantAttribute..ctor' is not defined. Const DT2 = #01/01/2000# ~~~~~~~~~~~~~~ </errors>) End Sub <WorkItem(541066, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541066")> <Fact()> Public Sub ConstBindingCheckForDecimalConstantConstructor() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="DefaultPropertyBindingCheckForAttributeConstructor"> <file name="a.vb"> Imports System Public Class C1 Const DT1 As Decimal = 12d Const DT2 = 12d End Class </file> <file name="b.vb"> Namespace System.Runtime.CompilerServices Public Class DecimalConstantAttribute Public Sub New(a As String) End Sub End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC35000: Requested operation is not available because the runtime library function 'System.Runtime.CompilerServices.DecimalConstantAttribute..ctor' is not defined. Const DT1 As Decimal = 12d ~~~~~ BC35000: Requested operation is not available because the runtime library function 'System.Runtime.CompilerServices.DecimalConstantAttribute..ctor' is not defined. Const DT2 = 12d ~~~~~ </errors>) End Sub <WorkItem(541066, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541066")> <Fact()> Public Sub SynthesizedInstanceConstructorBinding() Dim compilation1 = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation name="SynthesizedInstanceConstructorBinding"> <file name="a.vb"> Public Class C1 End Class </file> </compilation>, Enumerable.Empty(Of MetadataReference)()) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC30002: Type 'System.Void' is not defined. Public Class C1 ~~~~~~~~~~~~~~~~ BC31091: Import of type 'Object' from assembly or module 'SynthesizedInstanceConstructorBinding.dll' failed. Public Class C1 ~~ </errors>) End Sub <WorkItem(541066, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541066")> <Fact()> Public Sub SynthesizedSharedConstructorBinding() Dim compilation1 = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation name="SynthesizedInstanceConstructorBinding"> <file name="a.vb"> Public Class C1 Const DA As DateTime = #1/1/1# End Class </file> </compilation>, Enumerable.Empty(Of MetadataReference)()) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC30002: Type 'System.Void' is not defined. Public Class C1 ~~~~~~~~~~~~~~~~ BC31091: Import of type 'Object' from assembly or module 'SynthesizedInstanceConstructorBinding.dll' failed. Public Class C1 ~~ BC30002: Type 'DateTime' is not defined. Const DA As DateTime = #1/1/1# ~~~~~~~~ BC31091: Import of type 'Object' from assembly or module 'SynthesizedInstanceConstructorBinding.dll' failed. Const DA As DateTime = #1/1/1# ~~~~~~~~ BC30002: Type 'System.DateTime' is not defined. Const DA As DateTime = #1/1/1# ~~~~~~~ </errors>) End Sub <WorkItem(541066, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541066")> <Fact()> Public Sub EnumWithoutMscorReference() Dim compilation1 = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation name="EnumWithoutMscorReference"> <file name="a.vb"> Enum E A End Enum </file> </compilation>, Enumerable.Empty(Of MetadataReference)()) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC30002: Type 'System.Void' is not defined. Enum E ~~~~~~~ BC30002: Type 'System.Int32' is not defined. Enum E ~ BC31091: Import of type '[Enum]' from assembly or module 'EnumWithoutMscorReference.dll' failed. Enum E ~ </errors>) End Sub <WorkItem(541468, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541468")> <Fact()> Public Sub TypeUsedViaAlias01() Dim compilation1 = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation name="TypeUsedViaAlias01"> <file name="a.vb"> Imports DnT = Microsoft.VisualBasic.DateAndTime Class c Sub S0() Dim a = DnT.DateString End Sub End Class </file> </compilation>, {MsvbRef}) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors><![CDATA[ BC30002: Type 'System.Void' is not defined. Class c ~~~~~~~~ BC30652: Reference required to assembly '<Missing Core Assembly>, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' containing the type 'Object'. Add one to your project. Class c ~ BC30002: Type 'System.Void' is not defined. Sub S0() ~~~~~~~~~ BC30002: Type 'System.Object' is not defined. Dim a = DnT.DateString ~ BC30652: Reference required to assembly '<Missing Core Assembly>, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' containing the type 'Object'. Add one to your project. Dim a = DnT.DateString ~~~ BC30652: Reference required to assembly '<Missing Core Assembly>, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' containing the type 'String'. Add one to your project. Dim a = DnT.DateString ~~~~~~~~~~~~~~ BC30652: Reference required to assembly 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' containing the type '[Object]'. Add one to your project. Dim a = DnT.DateString ~~~~~~~~~~~~~~ ]]></errors>) End Sub <WorkItem(541468, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541468")> <Fact()> Public Sub TypeUsedViaAlias02() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndReferences( <compilation name="TypeUsedViaAlias02"> <file name="a.vb"> Imports MyClass1 = Class1 Class c Dim _myclass As MyClass1 = Nothing End Class </file> </compilation>, {TestReferences.SymbolsTests.NoPia.NoPIAGenericsAsm1}) compilation1.AssertTheseDiagnostics( <errors> BC36924: Type 'List(Of FooStruct)' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type. Dim _myclass As MyClass1 = Nothing ~~~~~~~~ </errors>) End Sub <WorkItem(541468, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541468")> <Fact()> Public Sub TypeUsedViaAlias03() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndReferences( <compilation name="TypeUsedViaAlias03"> <file name="a.vb"> Imports MyClass1 = Class1 Class c Sub S0() Dim _myclass = MyClass1.Class1Foo End Sub End Class </file> </compilation>, {TestReferences.SymbolsTests.NoPia.NoPIAGenericsAsm1}) compilation1.AssertTheseDiagnostics( <errors> BC36924: Type 'List(Of FooStruct)' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type. Dim _myclass = MyClass1.Class1Foo ~~~~~~~~ BC36924: Type 'List(Of FooStruct)' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type. Dim _myclass = MyClass1.Class1Foo ~~~~~~~~~~~~~~~~~~ </errors>) End Sub <WorkItem(541468, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541468")> <Fact()> Public Sub TypeUsedViaAlias04() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndReferences( <compilation name="TypeUsedViaAlias04"> <file name="a.vb"> Imports MyClass1 = Class1 Class c Sub S0() Dim _myclass = directcast(nothing, MyClass1) End Sub End Class </file> </compilation>, {TestReferences.SymbolsTests.NoPia.NoPIAGenericsAsm1}) compilation1.AssertTheseDiagnostics( <errors> BC36924: Type 'List(Of FooStruct)' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type. Dim _myclass = directcast(nothing, MyClass1) ~~~~~~~~ </errors>) End Sub <Fact()> Public Sub Bug8522() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ArrayInitNoType"> <file name="a.vb"> Imports System Class A Sub New(x As Action) End Sub Public Const X As Integer = 0 End Class Class C Inherits Attribute Sub New(x As Integer) End Sub End Class Module M Friend Const main As Object=Main Sub Main End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30500: Constant 'main' cannot depend on its own value. Friend Const main As Object=Main ~~~~ BC30260: 'Main' is already declared as 'Friend Const main As Object' in this module. Sub Main ~~~~ </expected>) End Sub <WorkItem(542596, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542596")> <Fact()> Public Sub RegularArgumentAfterNamed() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="RegularArgumentAfterNamed"> <file name="a.vb"> Module Module1 Sub M1(x As Integer, y As Integer) End Sub Sub M1(x As Integer, y As Long) End Sub Sub M2(x As Integer, y As Integer) End Sub Sub Main() M1(x:=2, 3) 'BIND:"M1(x:=2, 3)" M2(x:=2, 3) End Sub End Module </file> </compilation>, parseOptions:=TestOptions.Regular.WithLanguageVersion(LanguageVersion.VisualBasic15)) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30241: Named argument expected. Please use language version 15.5 or greater to use non-trailing named arguments. M1(x:=2, 3) 'BIND:"M1(x:=2, 3)" ~ BC30241: Named argument expected. Please use language version 15.5 or greater to use non-trailing named arguments. M2(x:=2, 3) ~ </expected>) End Sub <Fact()> Public Sub EventMissingName() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="EventMissingName"> <file name="a.vb"> Imports System Imports System.Collections.Generic Module Program Event Sub Main(args As String()) End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC30203: Identifier expected. Event ~ </errors>) End Sub <Fact()> Public Sub EventClashSynthetic() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="EventClashSynthetic"> <file name="a.vb"> Imports System Imports System.Collections.Generic Module Program Event E() Dim EEvent As Integer Sub Main(args As String()) End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC31060: event 'E' implicitly defines 'EEvent', which conflicts with a member of the same name in module 'Program'. Event E() ~ </errors>) End Sub <Fact()> Public Sub EventClashSyntheticDelegate() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="EventClashSyntheticDelegate"> <file name="a.vb"> Imports System Imports System.Collections.Generic Module Program Event E() Dim EEventHandler As Integer Sub Main(args As String()) End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC31060: event 'E' implicitly defines 'EEventHandler', which conflicts with a member of the same name in module 'Program'. Event E() ~ </errors>) End Sub <Fact()> Public Sub EventNotADelegate() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="EventNotADelegate"> <file name="a.vb"> Imports System Imports System.Collections.Generic Module Program Event E as Integer Sub Main(args As String()) End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC31044: Events declared with an 'As' clause must have a delegate type. Event E as Integer ~~~~~~~ </errors>) End Sub <Fact()> Public Sub EventParamsAndAs() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="EventParamsAndAs"> <file name="a.vb"> Imports System Imports System.Collections.Generic Module Program Event E(x as integer) as Integer Sub Main(args As String()) End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC30032: Events cannot have a return type. Event E(x as integer) as Integer ~~ </errors>) End Sub <Fact()> Public Sub EventDelegateReturns() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="EventDelegateReturns"> <file name="a.vb"> Imports System Imports System.Collections.Generic Module Program Event E as Func(of Integer) Sub Main() End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC31084: Events cannot be declared with a delegate type that has a return type. Event E as Func(of Integer) ~~~~~~~~~~~~~~~~ </errors>) End Sub <Fact()> Public Sub EventDelegateClash() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="EventDelegateClash"> <file name="a.vb"> Imports System Imports System.Collections.Generic Module Program Event E() Event E(x as integer) Sub Main() End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC30260: 'E' is already declared as 'Public Event E()' in this module. Event E(x as integer) ~ </errors>) End Sub <Fact()> Public Sub EventNameLength() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="EventNameLength"> <file name="a.vb"> Imports System Imports System.Collections.Generic Module Program Event eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee() Event eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee() Sub Main(args As String()) End Sub End Module </file> </compilation>) CompilationUtils.AssertNoDiagnostics(compilation1) CompilationUtils.AssertTheseEmitDiagnostics(compilation1, <errors> BC37220: Name 'eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeEventHandler' exceeds the maximum length allowed in metadata. Event eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee() ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors>) End Sub <Fact()> Public Sub EventTypeChar() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="EventTypeChar"> <file name="a.vb"> Imports System Imports System.Collections.Generic Module Program Event e$ Sub Main(args As String()) End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC30468: Type declaration characters are not valid in this context. Event e$ ~~ </errors>) End Sub <Fact()> Public Sub EventIllegalImplements() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="EventIllegalImplements"> <file name="a.vb"> Imports System Imports System.Collections.Generic Interface I0 Event e End Interface Interface I1 Event e Implements I0.e End Interface Class Cls1 Implements I0 Shared Event e Implements I0.e End Class Module Program Event e Implements I0.e Sub Main(args As String()) End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC30688: Events in interfaces cannot be declared 'Implements'. Event e Implements I0.e ~~~~~~~~~~ BC30149: Class 'Cls1' must implement 'Event e()' for interface 'I0'. Implements I0 ~~ BC30505: Methods or events that implement interface members cannot be declared 'Shared'. Shared Event e Implements I0.e ~~~~~~ BC31083: Members in a Module cannot implement interface members. Event e Implements I0.e ~~~~~~~~~~ </errors>) End Sub <Fact()> Public Sub CustomEventMissingAccessors() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="CustomEventMissingAccessors"> <file name="a.vb"> Option Strict On Imports System Module Program Delegate Sub del1(x As Integer, x As Integer) Custom Event eeeeeee As del1 End Event Sub Main(args As String()) AddHandler eeeeeee, Nothing RemoveHandler eeeeeee, Nothing RaiseEvent eeeeeee(1,1) End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC31130: 'AddHandler' definition missing for event 'Public Event eeeeeee As Program.del1'. Custom Event eeeeeee As del1 ~~~~~~~ BC31131: 'RemoveHandler' definition missing for event 'Public Event eeeeeee As Program.del1'. Custom Event eeeeeee As del1 ~~~~~~~ BC31132: 'RaiseEvent' definition missing for event 'Public Event eeeeeee As Program.del1'. Custom Event eeeeeee As del1 ~~~~~~~ BC31132: 'RaiseEvent' definition missing for event 'eeeeeee'. RaiseEvent eeeeeee(1,1) ~~~~~~~ </errors>) End Sub <Fact()> Public Sub CustomEventDuplicateAccessors() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="CustomEventDuplicateAccessors"> <file name="a.vb"> Option Strict On Imports System Module Program Delegate Sub del1(x As Integer, x As Integer) Custom Event eeeeeee As del1 AddHandler(value As del1) End AddHandler RemoveHandler(value As del1) End RemoveHandler RaiseEvent(x As Integer, x1 As Integer) End RaiseEvent AddHandler(value As del1) End AddHandler RemoveHandler(value As del1) End RemoveHandler RaiseEvent(x As Integer, x1 As Integer) End RaiseEvent End Event Sub Main(args As String()) AddHandler eeeeeee, Nothing RemoveHandler eeeeeee, Nothing End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC31127: 'AddHandler' is already declared. AddHandler(value As del1) ~~~~~~~~~~~~~~~~~~~~~~~~~ BC31128: 'RemoveHandler' is already declared. RemoveHandler(value As del1) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC31129: 'RaiseEvent' is already declared. RaiseEvent(x As Integer, x1 As Integer) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors>) End Sub <Fact()> Public Sub CustomEventAccessorsWrongParamNum() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="CustomEventDuplicateAccessors"> <file name="a.vb"> Option Strict On Imports System Module Program Delegate Sub del1(x As Integer, x As Integer) Custom Event eeeeeee As del1 AddHandler() End AddHandler RemoveHandler(value As del1, x As Integer) End RemoveHandler RaiseEvent(x As Integer, x1 As Integer) End RaiseEvent End Event Sub Main(args As String()) AddHandler eeeeeee, Nothing RemoveHandler eeeeeee, Nothing End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC31133: 'AddHandler' and 'RemoveHandler' methods must have exactly one parameter. AddHandler() ~~~~~~~~~~~~ BC31133: 'AddHandler' and 'RemoveHandler' methods must have exactly one parameter. RemoveHandler(value As del1, x As Integer) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors>) End Sub <Fact()> Public Sub CustomEventAccessorsWrongParamTypes() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="CustomEventDuplicateAccessors"> <file name="a.vb"> Option Strict Off Imports System Module Program Delegate Sub del1(x As Integer) Custom Event eeeeeee As del1 AddHandler(value As Action(Of Integer)) End AddHandler RemoveHandler(value) End RemoveHandler RaiseEvent(x) ' not an error (strict off) End RaiseEvent End Event Sub Main(args As String()) AddHandler eeeeeee, Nothing RemoveHandler eeeeeee, Nothing End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC31136: 'AddHandler' and 'RemoveHandler' method parameters must have the same delegate type as the containing event. AddHandler(value As Action(Of Integer)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC31136: 'AddHandler' and 'RemoveHandler' method parameters must have the same delegate type as the containing event. RemoveHandler(value) ~~~~~~~~~~~~~~~~~~~~ </errors>) End Sub <Fact()> Public Sub CustomEventAccessorsWrongParamTypes1() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="CustomEventDuplicateAccessors"> <file name="a.vb"> Option Strict Off Imports System Module Program Delegate Sub del1(x As Integer) Custom Event eeeeeee As Object AddHandler(value As Object) End AddHandler RemoveHandler(value) End RemoveHandler RaiseEvent(x) ' not an error (strict off) End RaiseEvent End Event Sub Main(args As String()) AddHandler eeeeeee, Nothing RemoveHandler eeeeeee, Nothing End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC31044: Events declared with an 'As' clause must have a delegate type. Custom Event eeeeeee As Object ~~~~~~ </errors>) End Sub <Fact()> Public Sub CustomEventAccessorsArgModifiers() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="CustomEventAccessorsArgModifiers"> <file name="a.vb"> Option Strict Off Imports System Module Program Delegate Sub del1(ByRef x As Integer) Custom Event eeeeeee As del1 AddHandler(ParamArray value() As del1) End AddHandler RemoveHandler(Optional ByRef value As del1 = Nothing) End RemoveHandler RaiseEvent(Optional ByRef x As Integer = 1) End RaiseEvent End Event Sub Main(args As String()) AddHandler eeeeeee, Nothing RemoveHandler eeeeeee, Nothing End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC31136: 'AddHandler' and 'RemoveHandler' method parameters must have the same delegate type as the containing event. AddHandler(ParamArray value() As del1) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC31138: 'AddHandler', 'RemoveHandler' and 'RaiseEvent' method parameters cannot be declared 'ParamArray'. AddHandler(ParamArray value() As del1) ~~~~~~~~~~ BC31138: 'AddHandler', 'RemoveHandler' and 'RaiseEvent' method parameters cannot be declared 'Optional'. RemoveHandler(Optional ByRef value As del1 = Nothing) ~~~~~~~~ BC31134: 'AddHandler' and 'RemoveHandler' method parameters cannot be declared 'ByRef'. RemoveHandler(Optional ByRef value As del1 = Nothing) ~~~~~ BC31138: 'AddHandler', 'RemoveHandler' and 'RaiseEvent' method parameters cannot be declared 'Optional'. RaiseEvent(Optional ByRef x As Integer = 1) ~~~~~~~~ </errors>) End Sub <Fact()> Public Sub CustomEventRaiseRelaxed1() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="CustomEventRaiseRelaxed1"> <file name="a.vb"> Option Strict On Imports System Module Program Delegate Sub del1(x As Integer) Custom Event eeeeeee1 As del1 AddHandler(value As del1) End AddHandler RemoveHandler(value As del1) End RemoveHandler RaiseEvent(x As Short) ' error End RaiseEvent End Event Custom Event eeeeeee2 As del1 AddHandler(value As del1) End AddHandler RemoveHandler(value As del1) End RemoveHandler RaiseEvent(x As Integer, y As Integer) ' error End RaiseEvent End Event Custom Event eeeeeee3 As del1 AddHandler(value As del1) End AddHandler RemoveHandler(value As del1) End RemoveHandler RaiseEvent(x As Long) 'valid End RaiseEvent End Event Custom Event eeeeeee4 As del1 AddHandler(value As del1) End AddHandler RemoveHandler(value As del1) End RemoveHandler RaiseEvent() ' valid End RaiseEvent End Event Sub Main(args As String()) AddHandler eeeeeee1, Nothing RemoveHandler eeeeeee1, Nothing End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC31137: 'RaiseEvent' method must have the same signature as the containing event's delegate type 'Program.del1'. RaiseEvent(x As Short) ~~~~~~~~~~~~~~~~~~~~~~ BC31137: 'RaiseEvent' method must have the same signature as the containing event's delegate type 'Program.del1'. RaiseEvent(x As Integer, y As Integer) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors>) End Sub <Fact()> Public Sub CustomEventRaiseRelaxed2() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="CustomEventRaiseRelaxed3"> <file name="a.vb"> Option Strict Off Imports System Module Program Delegate Sub del1(x As Integer) Custom Event eeeeeee1 As del1 AddHandler(value As del1) End AddHandler RemoveHandler(value As del1) End RemoveHandler RaiseEvent(x As Short) ' valid End RaiseEvent End Event Custom Event eeeeeee2 As del1 AddHandler(value As del1) End AddHandler RemoveHandler(value As del1) End RemoveHandler RaiseEvent(x As Integer, y As Integer) ' error End RaiseEvent End Event Custom Event eeeeeee3 As del1 AddHandler(value As del1) End AddHandler RemoveHandler(value As del1) End RemoveHandler RaiseEvent(x As Long) 'valid End RaiseEvent End Event Custom Event eeeeeee4 As del1 AddHandler(value As del1) End AddHandler RemoveHandler(value As del1) End RemoveHandler RaiseEvent() ' valid End RaiseEvent End Event Sub Main(args As String()) AddHandler eeeeeee1, Nothing RemoveHandler eeeeeee1, Nothing End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC31137: 'RaiseEvent' method must have the same signature as the containing event's delegate type 'Program.del1'. RaiseEvent(x As Integer, y As Integer) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors>) End Sub <Fact()> Public Sub RaiseEventNotEvent() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="RaiseEventNotEvent"> <file name="a.vb"> Imports System Module Program Delegate Sub del1() Dim o As del1 Sub Main(args As String()) RaiseEvent o() RaiseEvent Blah RaiseEvent RaiseEvent RaiseEvent End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC30676: 'o' is not an event of 'Program'. RaiseEvent o() ~ BC30451: 'Blah' is not declared. It may be inaccessible due to its protection level. RaiseEvent Blah ~~~~ BC30203: Identifier expected. RaiseEvent ~ BC30451: 'RaiseEvent' is not declared. It may be inaccessible due to its protection level. RaiseEvent RaiseEvent ~~~~~~~~~~ </errors>) End Sub <Fact()> Public Sub RaiseEventInBase() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="RaiseEventInBase"> <file name="a.vb"> Imports System Module Program Delegate Sub del1() Dim o As del1 Sub Main(args As String()) End Sub Class cls1 Public Shared Event EFieldLike As Action Public Shared Custom Event ECustom As Action AddHandler(value As Action) End AddHandler RemoveHandler(value As Action) End RemoveHandler RaiseEvent() End RaiseEvent End Event Class cls2 Inherits cls1 Sub Test() ' valid as in Dev10 RaiseEvent EFieldLike() ' error RaiseEvent E1() End Sub End Class End Class End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC30451: 'E1' is not declared. It may be inaccessible due to its protection level. RaiseEvent E1() ~~ </errors>) End Sub <Fact()> Public Sub RaiseEventStrictOn() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="RaiseEventStrictOn"> <file name="a.vb"> Option Strict On Imports System Module Program Delegate Sub del1(ByRef x As Object) Event E As del1 Sub Main() Dim v As String RaiseEvent E(v) End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC32029: Option Strict On disallows narrowing from type 'Object' to type 'String' in copying the value of 'ByRef' parameter 'x' back to the matching argument. RaiseEvent E(v) ~ BC42104: Variable 'v' is used before it has been assigned a value. A null reference exception could result at runtime. RaiseEvent E(v) ~ </errors>) End Sub <Fact()> Public Sub RaiseEventStrictOff() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="RaiseEventStrictOff"> <file name="a.vb"> Option Strict Off Imports System Module Program Delegate Sub del1(ByRef x As Object) Event E As del1 Sub Main() Dim v As String RaiseEvent E(v) End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC42030: Variable 'v' is passed by reference before it has been assigned a value. A null reference exception could result at runtime. RaiseEvent E(v) ~ </errors>) End Sub <Fact()> Public Sub ImplementNotValidDelegate() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ImplementDifferentDelegate"> <file name="a.vb"> Imports System Module Program Interface i1 Delegate Sub del1() Delegate Sub del2(x As Integer) Delegate Sub del3(x() As Integer) Event E1 As del1 Event E2 As del2 Event E3 As del3 End Interface Class cls1 Implements i1 Private Event E1 As Integer Implements i1.E1 Private Event E2 As Func(Of Integer) Implements i1.E2 Private Event E3 As Implements i1.E3 Private Event E4(ParamArray x() As Integer) Implements i1.E3 End Class Sub Main() End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC30149: Class 'cls1' must implement 'Event E2 As Program.i1.del2' for interface 'i1'. Implements i1 ~~ BC31044: Events declared with an 'As' clause must have a delegate type. Private Event E1 As Integer Implements i1.E1 ~~~~~~~ BC31423: Event 'Private Event E1 As Integer' cannot implement event 'Event E1 As Program.i1.del1' on interface 'Program.i1' because their delegate types 'Integer' and 'Program.i1.del1' do not match. Private Event E1 As Integer Implements i1.E1 ~~~~~ BC31084: Events cannot be declared with a delegate type that has a return type. Private Event E2 As Func(Of Integer) Implements i1.E2 ~~~~~~~~~~~~~~~~ BC30401: 'E2' cannot implement 'E2' because there is no matching event on interface 'i1'. Private Event E2 As Func(Of Integer) Implements i1.E2 ~~~~~ BC30180: Keyword does not name a type. Private Event E3 As Implements i1.E3 ~ BC31044: Events declared with an 'As' clause must have a delegate type. Private Event E3 As Implements i1.E3 ~ BC33009: 'Event' parameters cannot be declared 'ParamArray'. Private Event E4(ParamArray x() As Integer) Implements i1.E3 ~~~~~~~~~~ </errors>) End Sub <Fact()> Public Sub ImplementDifferentDelegate() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ImplementDifferentDelegate"> <file name="a.vb"> Imports System Module Program Interface i1 Delegate Sub del1() Delegate Sub del2(x As Integer) Delegate Sub del3(ByRef x As Integer) Event E1 As del1 Event E2 As del2 Event E3 As del3 End Interface Class cls1 Implements i1 Private Event E1 As action Implements i1.E1 Private Event E2 As action Implements i1.E2 Private Event E3 As i1.del2 Implements i1.E3 End Class Sub Main() End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC30149: Class 'cls1' must implement 'Event E2 As Program.i1.del2' for interface 'i1'. Implements i1 ~~ BC30149: Class 'cls1' must implement 'Event E3 As Program.i1.del3' for interface 'i1'. Implements i1 ~~ BC31423: Event 'Private Event E1 As Action' cannot implement event 'Event E1 As Program.i1.del1' on interface 'Program.i1' because their delegate types 'Action' and 'Program.i1.del1' do not match. Private Event E1 As action Implements i1.E1 ~~~~~ BC30401: 'E2' cannot implement 'E2' because there is no matching event on interface 'i1'. Private Event E2 As action Implements i1.E2 ~~~~~ BC30401: 'E3' cannot implement 'E3' because there is no matching event on interface 'i1'. Private Event E3 As i1.del2 Implements i1.E3 ~~~~~ </errors>) End Sub <Fact()> Public Sub ImplementDifferentSignature() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ImplementDifferentDelegate"> <file name="a.vb"> Imports System Module Program Interface i1 Delegate Sub del1() Delegate Sub del2(x As Integer) Delegate Sub del3(ByRef x As Integer) Event E1 As del1 Event E2 As del2 Event E3 As del3 End Interface Class cls1 Implements i1 Private Event E1(x As Integer) Implements i1.E1 Private Event E2() Implements i1.E2 Private Event E3(x As Integer) Implements i1.E3 End Class Sub Main() End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC30149: Class 'cls1' must implement 'Event E1 As Program.i1.del1' for interface 'i1'. Implements i1 ~~ BC30149: Class 'cls1' must implement 'Event E2 As Program.i1.del2' for interface 'i1'. Implements i1 ~~ BC30149: Class 'cls1' must implement 'Event E3 As Program.i1.del3' for interface 'i1'. Implements i1 ~~ BC30401: 'E1' cannot implement 'E1' because there is no matching event on interface 'i1'. Private Event E1(x As Integer) Implements i1.E1 ~~~~~ BC30401: 'E2' cannot implement 'E2' because there is no matching event on interface 'i1'. Private Event E2() Implements i1.E2 ~~~~~ BC30401: 'E3' cannot implement 'E3' because there is no matching event on interface 'i1'. Private Event E3(x As Integer) Implements i1.E3 ~~~~~ </errors>) End Sub <Fact()> Public Sub ImplementConflicting() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ImplementConflicting"> <file name="a.vb"> Imports System Module Program Interface i1 Delegate Sub del1() Delegate Sub del2(x As Integer) Event E1 As del1 Event E2 As del2 Event E1a As del2 Event E2a As Action(Of Integer) End Interface Class cls1 Implements i1 Private Event E1 As i1.del1 Implements i1.E1, i1.E2 Private Event E2(x As Integer) Implements i1.E1a, i1.E2a End Class Sub Main() End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC30149: Class 'cls1' must implement 'Event E2 As Program.i1.del2' for interface 'i1'. Implements i1 ~~ BC30401: 'E1' cannot implement 'E2' because there is no matching event on interface 'i1'. Private Event E1 As i1.del1 Implements i1.E1, i1.E2 ~~~~~ BC31407: Event 'Private Event E2 As Program.i1.del2' cannot implement event 'Program.i1.Event E2a As Action(Of Integer)' because its delegate type does not match the delegate type of another event implemented by 'Private Event E2 As Program.i1.del2'. Private Event E2(x As Integer) Implements i1.E1a, i1.E2a ~~~~~~ </errors>) End Sub <Fact()> Public Sub ImplementTwice() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ImplementTwice"> <file name="a.vb"> Imports System Module Program Interface i1 Delegate Sub del1() Delegate Sub del2(x As Integer) Event E1 As del1 Event E2 As del2 End Interface Class cls1 Implements i1 Private Event E1 As i1.del1 Implements i1.E1, i1.E1 Private Event E2() Implements i1.E1 End Class Sub Main() End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC30149: Class 'cls1' must implement 'Event E2 As Program.i1.del2' for interface 'i1'. Implements i1 ~~ BC30583: 'i1.E1' cannot be implemented more than once. Private Event E1 As i1.del1 Implements i1.E1, i1.E1 ~~~~~ BC30583: 'i1.E1' cannot be implemented more than once. Private Event E2() Implements i1.E1 ~~~~~ </errors>) End Sub <Fact()> Public Sub ImplementIncomplete() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ImplementConflicting"> <file name="a.vb"> Imports System Module Program Interface i1 Delegate Sub del1() Delegate Sub del2(x As Integer) Event E1 As del1 Event E2 As del2 End Interface Class cls1 Implements i1 Private Event E1 As i1.del1 Implements Private Event E2() Implements i1 Private Event E3 Implements i1. Private Event E4 Implements i1.Blah End Class Sub Main() End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC30149: Class 'cls1' must implement 'Event E1 As Program.i1.del1' for interface 'i1'. Implements i1 ~~ BC30149: Class 'cls1' must implement 'Event E2 As Program.i1.del2' for interface 'i1'. Implements i1 ~~ BC30203: Identifier expected. Private Event E1 As i1.del1 Implements ~ BC30287: '.' expected. Private Event E1 As i1.del1 Implements ~ BC30287: '.' expected. Private Event E2() Implements i1 ~~ BC30401: 'E2' cannot implement '' because there is no matching event on interface 'i1'. Private Event E2() Implements i1 ~~ BC30401: 'E3' cannot implement '' because there is no matching event on interface 'i1'. Private Event E3 Implements i1. ~~~ BC30203: Identifier expected. Private Event E3 Implements i1. ~ BC30401: 'E4' cannot implement 'Blah' because there is no matching event on interface 'i1'. Private Event E4 Implements i1.Blah ~~~~~~~ </errors>) End Sub <WorkItem(543095, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543095")> <Fact()> Public Sub SelectCase_CaseStatementError() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="SelectCase_CaseStatementError"> <file name="a.vb"> Imports System Module Program Sub Main(args As String()) Dim x As New myclass1 Select x Ca End Sub End Module Structure myclass1 Implements IDisposable Public Sub dispose() Implements IDisposable.Dispose End Sub End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30095: 'Select Case' must end with a matching 'End Select'. Select x ~~~~~~~~ BC30058: Statements and labels are not valid between 'Select Case' and first 'Case'. Ca ~~ BC30451: 'Ca' is not declared. It may be inaccessible due to its protection level. Ca ~~ </expected>) End Sub <WorkItem(543095, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543095")> <Fact()> Public Sub SelectCase_CaseStatementError_02() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="SelectCase_CaseStatementError"> <file name="a.vb"> Imports System Module Program Sub Main(args As String()) Dim x As New myclass1 Select x Case End Select Select x Case y End Select End Sub End Module Structure myclass1 Implements IDisposable Public Sub dispose() Implements IDisposable.Dispose End Sub End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30201: Expression expected. Case ~ BC30451: 'y' is not declared. It may be inaccessible due to its protection level. Case y ~ </expected>) End Sub <WorkItem(543095, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543095")> <Fact()> Public Sub SelectCase() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="SelectCase"> <file name="a.vb"> Imports System Module Program Sub Main(args As String()) Dim x As New myclass1 Select x ca End Select End Sub End Module Structure myclass1 Implements IDisposable Public Sub dispose() Implements IDisposable.Dispose End Sub End Structure </file> </compilation>) VerifyDiagnostics(compilation, Diagnostic(ERRID.ERR_ExpectedCase, "ca"), Diagnostic(ERRID.ERR_NameNotDeclared1, "ca").WithArguments("ca")) End Sub <WorkItem(543300, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543300")> <Fact()> Public Sub BoundConversion() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="BoundConversion"> <file name="a.vb"> Imports System.Linq Class C1 sharSub MAIN() Dim lists = foo() lists.Where(Function(ByVal item) SyncLock item End SyncLock Return item.ToString() = "" End Function).ToList() End Sub Shared Function foo() As List(Of myattribute1) Return Nothing End Function End Class </file> </compilation>) VerifyDiagnostics(compilation, Diagnostic(ERRID.ERR_ExpectedSpecifier, "MAIN()"), Diagnostic(ERRID.ERR_ExpectedDeclaration, "sharSub"), Diagnostic(ERRID.ERR_ExpectedDeclaration, "lists"), Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "SyncLock item"), Diagnostic(ERRID.ERR_EndSyncLockNoSyncLock, "End SyncLock"), Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Return item.ToString() = """""), Diagnostic(ERRID.ERR_InvalidEndFunction, "End Function"), Diagnostic(ERRID.ERR_ExpectedEOS, ")"), Diagnostic(ERRID.ERR_InvalidEndSub, "End Sub"), Diagnostic(ERRID.WRN_UndefinedOrEmptyNamespaceOrClass1, "System.Linq").WithArguments("System.Linq"), Diagnostic(ERRID.ERR_UndefinedType1, "myattribute1").WithArguments("myattribute1"), Diagnostic(ERRID.ERR_UndefinedType1, "List(Of myattribute1)").WithArguments("List"), Diagnostic(ERRID.HDN_UnusedImportStatement, "Imports System.Linq")) End Sub <WorkItem(543300, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543300")> <Fact()> Public Sub BoundConversion_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="BoundConversion"> <file name="a.vb"> "".Where(Function(item) Return lab1 End Function: Return item.ToString() = "" End Function).ToList() End Sub </file> </compilation>, {Net40.SystemCore}) VerifyDiagnostics(compilation, Diagnostic(ERRID.ERR_Syntax, """"""), Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Return lab1"), Diagnostic(ERRID.ERR_InvalidEndFunction, "End Function"), Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Return item.ToString() = """""), Diagnostic(ERRID.ERR_InvalidEndFunction, "End Function"), Diagnostic(ERRID.ERR_ExpectedEOS, ")"), Diagnostic(ERRID.ERR_InvalidEndSub, "End Sub")) End Sub <WorkItem(543319, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543319")> <Fact()> Public Sub CaseOnlyAppearInSelect() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Module M1 Sub Main() Select "" Case "a" If (True) Case "b" GoTo lab1 End If End Select lab1: End Sub End Module ]]></file> </compilation>) VerifyDiagnostics(compilation, Diagnostic(ERRID.ERR_CaseNoSelect, "Case ""b""")) End Sub <WorkItem(543319, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543319")> <Fact()> Public Sub CaseOnlyAppearInSelect_1() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Class Test Public Shared Sub Main() Select Case "" Case "c" Try Case "a" Catch ex As Exception Case "b" End Try End Select End Sub End Class ]]></file> </compilation>) VerifyDiagnostics(compilation, Diagnostic(ERRID.ERR_CaseNoSelect, "Case ""a"""), Diagnostic(ERRID.ERR_CaseNoSelect, "Case ""b""")) End Sub <WorkItem(543333, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543333")> <Fact()> Public Sub BindReturn() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Class Program Shared Main() Return Nothing End sub End Class ]]></file> </compilation>) VerifyDiagnostics(compilation, Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Return Nothing"), Diagnostic(ERRID.ERR_InvalidEndSub, "End sub")) End Sub <WorkItem(543746, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543746")> <Fact()> Public Sub LocalConstAssignedToSelf() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Module Program Sub Main() Const X = X End Sub End Module ]]></file> </compilation>) VerifyDiagnostics(compilation, Diagnostic(ERRID.ERR_CircularEvaluation1, "X").WithArguments("X"), Diagnostic(ERRID.WRN_DefAsgUseNullRef, "X").WithArguments("X")) End Sub <WorkItem(543746, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543746")> <Fact> Public Sub LocalConstCycle() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Module Program Sub Main() Const Y = Z Const Z = Y Const a = c Const b = a Const c = b End Sub End Module ]]></file> </compilation>) VerifyDiagnostics(compilation, Diagnostic(ERRID.ERR_UseOfLocalBeforeDeclaration1, "Z").WithArguments("Z"), Diagnostic(ERRID.ERR_UseOfLocalBeforeDeclaration1, "c").WithArguments("c")) End Sub <WorkItem(543823, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543823")> <Fact()> Public Sub LocalConstCycle02() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Module Program Sub Main() Const X = 3 + Z Const Y = 2 + X Const Z = 1 + Y End Sub End Module ]]></file> </compilation>) ' Dev10: Diagnostic(ERRID.ERR_NameNotDeclared1, "Z").WithArguments("Z")) VerifyDiagnostics(compilation, Diagnostic(ERRID.ERR_UseOfLocalBeforeDeclaration1, "Z").WithArguments("Z"), Diagnostic(ERRID.ERR_RequiredConstConversion2, "2").WithArguments("Integer", "Object"), Diagnostic(ERRID.ERR_RequiredConstConversion2, "1").WithArguments("Integer", "Object")) End Sub <WorkItem(543821, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543821")> <Fact()> Public Sub LocalConstCycle03() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Module Program Sub Main() Const X = Y Const Y = Y + X Const Z = Y + Z End Sub End Module ]]></file> </compilation>) VerifyDiagnostics(compilation, Diagnostic(ERRID.ERR_UseOfLocalBeforeDeclaration1, "Y").WithArguments("Y"), Diagnostic(ERRID.ERR_CircularEvaluation1, "Y").WithArguments("Y"), Diagnostic(ERRID.ERR_CircularEvaluation1, "Z").WithArguments("Z"), Diagnostic(ERRID.WRN_DefAsgUseNullRef, "Y").WithArguments("Y"), Diagnostic(ERRID.WRN_DefAsgUseNullRef, "Z").WithArguments("Z")) End Sub <WorkItem(543755, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543755")> <Fact()> Public Sub BracketedIdentifierMissingEndBracket() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Module Program Sub Main() Dim [foo as integer = 23 : Dim [goo As Char = "d"c End Sub End Module ]]></file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30203: Identifier expected. Dim [foo as integer = 23 : Dim [goo As Char = "d"c ~ BC30034: Bracketed identifier is missing closing ']'. Dim [foo as integer = 23 : Dim [goo As Char = "d"c ~~~~ BC30203: Identifier expected. Dim [foo as integer = 23 : Dim [goo As Char = "d"c ~ BC30034: Bracketed identifier is missing closing ']'. Dim [foo as integer = 23 : Dim [goo As Char = "d"c ~~~~ </expected>) End Sub <Fact(), WorkItem(536245, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536245"), WorkItem(543652, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543652")> Public Sub BC30192ERR_ParamArrayMustBeLast() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Class C1 Sub foo(byval Paramarray pArr1() as Integer, byval paramarray pArr2 as integer) End Sub End Class ]]> </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30192: End of parameter list expected. Cannot define parameters after a paramarray parameter. Sub foo(byval Paramarray pArr1() as Integer, byval paramarray pArr2 as integer) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30050: ParamArray parameter must be an array. Sub foo(byval Paramarray pArr1() as Integer, byval paramarray pArr2 as integer) ~~~~~ </expected>) End Sub <WorkItem(544501, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544501")> <Fact()> Public Sub TestCombinePrivateAndNotOverridable() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Module Program Sub Main(args As String()) c1.Bar() End Sub End Module Class c1 Partial Private Sub foo(ByRef x() As Integer) End Sub End Class </file> <file name="b.vb"> Imports System Partial Class c1 Private NotOverridable Sub Foo(ByRef x() As Integer) Console.Write("Success") End Sub Shared Sub Bar() Dim x = New c1() x.foo({1}) End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC31408: 'Private' and 'NotOverridable' cannot be combined. Private NotOverridable Sub Foo(ByRef x() As Integer) ~~~~~~~~~~~~~~ </expected>) End Sub <WorkItem(546098, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546098")> <Fact()> Public Sub InstanceMemberOfStructInsideSharedLambda() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Module Test Public Structure S1 Dim a As Integer Public Shared c As Action(Of Integer) = Sub(c) a = 2 End Sub End Structure End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30369: Cannot refer to an instance member of a class from within a shared method or shared member initializer without an explicit instance of the class. a = 2 ~ </expected>) End Sub <WorkItem(546053, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546053")> <Fact()> Public Sub EventHandlerBindingError() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module Test Sub lbHnd() End Sub Dim oc As Object Sub Main() AddHandler oc.evt, AddressOf lbHnd End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30676: 'evt' is not an event of 'Object'. AddHandler oc.evt, AddressOf lbHnd ~~~ </expected>) End Sub <WorkItem(530912, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530912")> <Fact()> Public Sub Bug_17183_LateBinding_Object() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Class classes Public Property P As Object Get Return Nothing End Get Set End Set End Property End Class Module Module1 Sub Main() Dim h As classes = Nothing Dim x = h.P(0) End Sub End Module ]]> </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30574: Option Strict On disallows late binding. Dim x = h.P(0) ~ </expected>) End Sub <WorkItem(530912, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530912")> <Fact()> Public Sub Bug_17183_LateBinding_Array() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports System Class classes Public Property P As Array Get Return Nothing End Get Set End Set End Property End Class Module Module1 Sub Main() Dim h As classes = Nothing Dim x = h.P(0) End Sub End Module ]]> </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30574: Option Strict On disallows late binding. Dim x = h.P(0) ~ </expected>) End Sub <WorkItem(530912, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530912")> <Fact()> Public Sub Bug_17183_LateBinding_COM() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports System.Runtime.InteropServices <TypeLibTypeAttribute(TypeLibTypeFlags.FDispatchable)> Interface inter Default Property sss(x As Integer) As Integer End Interface Class classes Public Property P As inter Get Return Nothing End Get Set End Set End Property End Class Module Module1 Sub Main() Dim h As classes = Nothing Dim x = h.P(0) 'No Late Binding here Dim y = h.P.Member 'Late Binding here - error End Sub End Module ]]> </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30574: Option Strict On disallows late binding. Dim y = h.P.Member 'Late Binding here - error ~~~~~~~~~~ </expected>) End Sub <WorkItem(531400, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531400")> <Fact()> Public Sub Bug18070() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module Program Event E() Sub Main() End Sub Sub Main1() RaiseEvent E() ' 1 Static E As Integer = 1 AddHandler E, AddressOf Main ' 1 RemoveHandler E, AddressOf Main ' 1 End Sub Sub Main2() RaiseEvent E() ' 2 Dim E As Integer = 1 AddHandler E, AddressOf Main ' 2 RemoveHandler E, AddressOf Main ' 2 End Sub Sub Main3(E As Integer) RaiseEvent E() ' 3 AddHandler E, AddressOf Main ' 3 RemoveHandler E, AddressOf Main ' 3 End Sub End Module </file> </compilation>) CompileAndVerify(compilation) End Sub <Fact()> Public Sub Bug547318() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> End Set End Property End Class Font) _FONT = Value Set(ByVal Value As System.Drawing. 'BIND:"Drawing" </file> </compilation>) Dim node As ExpressionSyntax = FindBindingText(Of ExpressionSyntax)(compilation, "a.vb") Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim bindInfo1 As SemanticInfoSummary = semanticModel.GetSemanticInfoSummary(DirectCast(node, ExpressionSyntax)) End Sub <WorkItem(566606, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/566606")> <Fact()> Public Sub BrokenFor() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> </file> </compilation>) Dim text = <![CDATA[ Imports System 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 ]]> compilation = compilation.AddSyntaxTrees(Parse(text)) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30035: Syntax error. For {|stmt1:$$i|} = 1 To 20 ~ BC30035: Syntax error. For {|stmt1:$$i|} = 1 To 20 ~ BC30201: Expression expected. For {|stmt1:$$i|} = 1 To 20 ~ BC30249: '=' expected. For {|stmt1:$$i|} = 1 To 20 ~ BC30370: '}' expected. For {|stmt1:$$i|} = 1 To 20 ~ BC30037: Character is not valid. For {|stmt1:$$i|} = 1 To 20 ~ BC30037: Character is not valid. For {|stmt1:$$i|} = 1 To 20 ~ BC30037: Character is not valid. For {|stmt1:$$i|} = 1 To 20 ~ BC30037: Character is not valid. For {|stmt1:$$i|} = 1 To 20 ~ BC30198: ')' expected. Console.WriteLine({|stmt1:i|}) ~ BC30201: Expression expected. Console.WriteLine({|stmt1:i|}) ~ BC30370: '}' expected. Console.WriteLine({|stmt1:i|}) ~ BC30037: Character is not valid. Console.WriteLine({|stmt1:i|}) ~ BC30451: 'i' is not declared. It may be inaccessible due to its protection level. Console.WriteLine({|stmt1:i|}) ~ BC30037: Character is not valid. Console.WriteLine({|stmt1:i|}) ~ </expected>) End Sub <Fact> Public Sub ConflictsWithTypesInVBCore_EmbeddedTypes() Dim source = <compilation> <file><![CDATA[ Module Module1 Sub Main() End Sub End Module 'Partial Class on Type in Microsoft.VisualBasic Namespace Microsoft.VisualBasic Partial Class HideModuleNameAttribute Inherits Attribute Public Function ABC() As String Return "Success" End Function Public Overrides ReadOnly Property TypeId As Object Get Return "TypeID" End Get End Property End Class End Namespace ]]> </file> </compilation> Dim c = CompilationUtils.CreateEmptyCompilationWithReferences(source, references:={MscorlibRef, SystemRef, SystemCoreRef}, options:=TestOptions.ReleaseDll.WithEmbedVbCoreRuntime(True)).VerifyDiagnostics(Diagnostic(ERRID.ERR_TypeClashesWithVbCoreType4, "HideModuleNameAttribute").WithArguments("class", "HideModuleNameAttribute", "class", "HideModuleNameAttribute"), Diagnostic(ERRID.ERR_UndefinedType1, "Attribute").WithArguments("Attribute"), Diagnostic(ERRID.ERR_OverrideNotNeeded3, "TypeId").WithArguments("property", "TypeId")) End Sub <Fact()> Public Sub ERR_ExtensionMethodCannotBeLateBound_1() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="a.vb"><![CDATA[ Module Module1 Sub Main() Dim x As New Test() Dim y As Object = x x.M(y) End Sub <System.Runtime.CompilerServices.Extension> Sub M(this As Test, x As Double) End Sub End Module Class Test Sub M(x As Integer) End Sub Sub M(x As UInteger) End Sub End Class ]]></file> </compilation>, {Net40.SystemCore}, TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.Custom)) AssertTheseDiagnostics(compilation, <expected> BC36908: Late-bound extension methods are not supported. x.M(y) ~ </expected>) End Sub <Fact()> Public Sub ERR_ExtensionMethodCannotBeLateBound_2() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="a.vb"><![CDATA[ Module Module1 Sub Main() Dim x As New Test() Dim y As Object = x x.M(y) End Sub <System.Runtime.CompilerServices.Extension> Sub M(this As Test, x As Double, y as String) End Sub End Module Class Test Sub M(x As Integer) End Sub Sub M(x As UInteger) End Sub End Class ]]></file> </compilation>, {Net40.SystemCore}, TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.Custom)) AssertTheseDiagnostics(compilation, <expected> BC36908: Late-bound extension methods are not supported. x.M(y) ~ </expected>) End Sub <Fact()> Public Sub ERR_ExtensionMethodCannotBeLateBound_3() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="a.vb"><![CDATA[ Module Module1 Sub Main() Dim x As New Test() Dim y As Object = x x.M(y) End Sub <System.Runtime.CompilerServices.Extension> Sub M(this As Test, x As Double) End Sub End Module Class Test Sub M(x As UInteger) End Sub End Class ]]></file> </compilation>, {Net40.SystemCore}, TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.Custom)) AssertTheseDiagnostics(compilation, <expected> BC42016: Implicit conversion from 'Object' to 'UInteger'. x.M(y) ~ </expected>) CompileAndVerify(compilation) End Sub <Fact()> Public Sub ERR_ExtensionMethodCannotBeLateBound_4() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Linq.Expressions Imports System.Runtime.CompilerServices Imports System.Collections.Generic Module Module1 Sub Main() Dim c1 As New C1() Dim x As Object = New List(Of Integer) Try c1.fun(x) Catch e As Exception Console.WriteLine(e) End Try End Sub <Extension> Sub fun(Of X)(this As C1, ByVal a As Queue(Of X)) End Sub End Module Class C1 Sub fun(Of X)(ByVal a As List(Of X)) End Sub Sub fun(Of X)(ByVal a As Stack(Of X)) End Sub End Class ]]></file> </compilation>, {Net40.SystemCore}, TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.Custom)) AssertTheseDiagnostics(compilation, <expected> BC36908: Late-bound extension methods are not supported. c1.fun(x) ~~~ </expected>) End Sub <Fact()> Public Sub ERR_ExtensionMethodCannotBeLateBound_5() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Linq.Expressions Imports System.Runtime.CompilerServices Imports System.Collections.Generic Module Module1 Sub Main() Dim c1 As New C1() Dim x As Object = New List(Of Integer) Try c1.fun(x) Catch e As Exception Console.WriteLine(e) End Try End Sub <Extension> Sub fun(Of X)(this As C1, ByVal a As Queue(Of X)) End Sub End Module Class C1 Sub fun(Of X)(ByVal a As List(Of X)) End Sub End Class ]]></file> </compilation>, {Net40.SystemCore}, TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.Custom)) AssertTheseDiagnostics(compilation, <expected> BC36908: Late-bound extension methods are not supported. c1.fun(x) ~~~ </expected>) End Sub <WorkItem(573728, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/573728")> <Fact()> Public Sub Bug573728() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Delegate Sub D(i As Integer) Module M Sub M(o As D) o() o(1, 2) End Sub End Module ]]></file> </compilation>, TestOptions.ReleaseDll) AssertTheseDiagnostics(compilation, <expected> BC30455: Argument not specified for parameter 'i' of 'D'. o() ~ BC30057: Too many arguments to 'D'. o(1, 2) ~ </expected>) End Sub <Fact(), WorkItem(792754, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/792754")> Public Sub NameClashAcrossFiles() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Module M Sub Main() End Sub Private Test2 As Settings End Module ]]></file> <file name="b.vb"><![CDATA[ Module M ' b.vb Private ReadOnly TOOL_OUTPUT_FILE_NAME As String = Settings.OutputFileName Function Test() As Settings return Nothing End Function End Module ]]></file> </compilation>, TestOptions.ReleaseExe) Dim allDiagnostics = comp.GetDiagnostics() AssertTheseDiagnostics(allDiagnostics, <expected><![CDATA[ BC30002: Type 'Settings' is not defined. Private Test2 As Settings ~~~~~~~~ BC30179: module 'M' and module 'M' conflict in namespace '<Default>'. Module M ' b.vb ~ BC30451: 'Settings' is not declared. It may be inaccessible due to its protection level. Private ReadOnly TOOL_OUTPUT_FILE_NAME As String = Settings.OutputFileName ~~~~~~~~ BC30002: Type 'Settings' is not defined. Function Test() As Settings ~~~~~~~~ ]]></expected>) Dim tree = comp.SyntaxTrees.Where(Function(t) t.FilePath.EndsWith("a.vb", StringComparison.Ordinal)).Single Dim model = comp.GetSemanticModel(tree) AssertTheseDiagnostics(model.GetDiagnostics(), <expected><![CDATA[ BC30002: Type 'Settings' is not defined. Private Test2 As Settings ~~~~~~~~ ]]></expected>) tree = comp.SyntaxTrees.Where(Function(t) t.FilePath.EndsWith("b.vb", StringComparison.Ordinal)).Single model = comp.GetSemanticModel(tree) AssertTheseDiagnostics(model.GetDiagnostics(), <expected><![CDATA[ BC30179: module 'M' and module 'M' conflict in namespace '<Default>'. Module M ' b.vb ~ BC30451: 'Settings' is not declared. It may be inaccessible due to its protection level. Private ReadOnly TOOL_OUTPUT_FILE_NAME As String = Settings.OutputFileName ~~~~~~~~ BC30002: Type 'Settings' is not defined. Function Test() As Settings ~~~~~~~~ ]]></expected>) End Sub <Fact> Public Sub BC42004WRN_RecursiveOperatorCall() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Friend Module RecAcc001mod Class cls Sub New() End Sub Shared Operator +(ByVal y As cls) As Object Return +y End Operator Shared Operator -(ByVal x As cls, ByVal y As Object) As Object Return x - y End Operator Public Shared Operator >>(ByVal x As cls, ByVal y As Integer) As Object Return x >> y End Operator Public Shared Widening Operator CType(ByVal y As cls) As Integer Return CType(y, Integer) End Operator End Class End Module ]]></file> </compilation>) Dim allDiagnostics = comp.GetDiagnostics() AssertTheseDiagnostics(allDiagnostics, <expected><![CDATA[ BC42004: Expression recursively calls the containing Operator 'Public Shared Operator +(y As RecAcc001mod.cls) As Object'. Return +y ~~ BC42004: Expression recursively calls the containing Operator 'Public Shared Operator -(x As RecAcc001mod.cls, y As Object) As Object'. Return x - y ~~~~~ BC42004: Expression recursively calls the containing Operator 'Public Shared Operator >>(x As RecAcc001mod.cls, y As Integer) As Object'. Return x >> y ~~~~~~ BC42004: Expression recursively calls the containing Operator 'Public Shared Widening Operator CType(y As RecAcc001mod.cls) As Integer'. Return CType(y, Integer) ~ ]]></expected>) End Sub <Fact(), WorkItem(5072, "https://github.com/dotnet/roslyn/issues/5072")> Public Sub LangVersion_ReadonlyAutoProperties() Dim source = <compilation> <file name="a.vb"> Class TestClass Public Sub New() 'Check assignment of readonly auto property Test = "Test" End Sub 'Check readonly auto-properties Public ReadOnly Property Test As String End Class Interface I1 ReadOnly Property Test1 As String WriteOnly Property Test2 As String Property Test3 As String End Interface MustInherit Class C1 MustOverride ReadOnly Property Test1 As String MustOverride WriteOnly Property Test2 As String MustOverride Property Test3 As String End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(source, parseOptions:=VisualBasicParseOptions.Default.WithLanguageVersion(LanguageVersion.VisualBasic12)) CompilationUtils.AssertTheseParseDiagnostics(compilation, <expected> BC36716: Visual Basic 12.0 does not support readonly auto-implemented properties. Public ReadOnly Property Test As String ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) compilation = CompilationUtils.CreateCompilationWithMscorlib40(source, parseOptions:=VisualBasicParseOptions.Default.WithLanguageVersion(LanguageVersion.VisualBasic9)) CompilationUtils.AssertTheseParseDiagnostics(compilation, <expected> BC36716: Visual Basic 9.0 does not support auto-implemented properties. Public ReadOnly Property Test As String ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact(), WorkItem(5072, "https://github.com/dotnet/roslyn/issues/5072")> Public Sub LangVersion_RegionEveryWhere01() Dim source = <compilation> <file name="a.vb"> Class TestClass Sub New() #Region "Region in .ctor" #End Region ' "Region in .ctor" End Sub Shared Sub New() #Region "Region in .cctor" #End Region ' "Region in .cctor" End Sub Public Sub ASub() #Region "Region in a Sub" #End Region ' "Region in a Sub" End Sub Public Function AFunc() #Region "Region in a Func" #End Region ' "Region in a Func" End Function Shared Operator +(x As TestClass, y As TestClass) As TestClass #Region "Region in an operator" #End Region ' "Region in an operator" End Operator Property P As Integer Get #Region "Region in a get" #End Region ' "Region in a get" End Get Set(value As Integer) #Region "Region in a set" #End Region ' "Region in a set" End Set End Property Custom Event E As System.Action AddHandler(value As Action) #Region "Region in an add" #End Region ' "Region in an add" End AddHandler RemoveHandler(value As Action) #Region "Region in a remove" #End Region ' "Region in a remove" End RemoveHandler RaiseEvent() #Region "Region in a raise" #End Region ' "Region in a raise" End RaiseEvent End Event End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(source, parseOptions:=VisualBasicParseOptions.Default.WithLanguageVersion(LanguageVersion.VisualBasic12)) CompilationUtils.AssertTheseParseDiagnostics(compilation, <expected> BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #Region "Region in .ctor" ~~~~~~~~~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #End Region ' "Region in .ctor" ~~~~~~~~~~~ BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #Region "Region in .cctor" ~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #End Region ' "Region in .cctor" ~~~~~~~~~~~ BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #Region "Region in a Sub" ~~~~~~~~~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #End Region ' "Region in a Sub" ~~~~~~~~~~~ BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #Region "Region in a Func" ~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #End Region ' "Region in a Func" ~~~~~~~~~~~ BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #Region "Region in an operator" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #End Region ' "Region in an operator" ~~~~~~~~~~~ BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #Region "Region in a get" ~~~~~~~~~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #End Region ' "Region in a get" ~~~~~~~~~~~ BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #Region "Region in a set" ~~~~~~~~~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #End Region ' "Region in a set" ~~~~~~~~~~~ BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #Region "Region in an add" ~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #End Region ' "Region in an add" ~~~~~~~~~~~ BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #Region "Region in a remove" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #End Region ' "Region in a remove" ~~~~~~~~~~~ BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #Region "Region in a raise" ~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #End Region ' "Region in a raise" ~~~~~~~~~~~ </expected>) End Sub <Fact(), WorkItem(5072, "https://github.com/dotnet/roslyn/issues/5072")> Public Sub LangVersion_RegionEveryWhere02() Dim source = <compilation> <file name="a.vb"> Class TestClass #Region "Region" #End Region Sub New() End Sub #Region "Region" #End Region Shared Sub New() End Sub #Region "Region" #End Region Public Sub ASub() End Sub #Region "Region" #End Region Public Function AFunc() End Function #Region "Region" #End Region Shared Operator +(x As TestClass, y As TestClass) As TestClass End Operator #Region "Region" #End Region Property P As Integer #Region "Region" #End Region Get End Get #Region "Region" #End Region Set(value As Integer) End Set #Region "Region" #End Region End Property #Region "Region" #End Region Custom Event E As System.Action #Region "Region" #End Region AddHandler(value As Action) End AddHandler #Region "Region" #End Region RemoveHandler(value As Action) End RemoveHandler #Region "Region" #End Region RaiseEvent() End RaiseEvent #Region "Region" #End Region End Event #Region "Region" #End Region End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(source, parseOptions:=VisualBasicParseOptions.Default.WithLanguageVersion(LanguageVersion.VisualBasic12)) CompilationUtils.AssertTheseParseDiagnostics(compilation, <expected> </expected>) End Sub <Fact(), WorkItem(5072, "https://github.com/dotnet/roslyn/issues/5072")> Public Sub LangVersion_RegionEveryWhere03() Dim source = <compilation> <file name="a.vb"> Class TestClass #Region "Region" Private f1 as Integer #End Region Sub New() End Sub #Region "Region" Private f1 as Integer #End Region Shared Sub New() End Sub #Region "Region" Private f1 as Integer #End Region Public Sub ASub() End Sub #Region "Region" Private f1 as Integer #End Region Public Function AFunc() End Function #Region "Region" Private f1 as Integer #End Region Shared Operator +(x As TestClass, y As TestClass) As TestClass End Operator #Region "Region" Private f1 as Integer #End Region Property P As Integer #Region "Region" #End Region Get End Get #Region "Region" #End Region Set(value As Integer) End Set #Region "Region" #End Region End Property #Region "Region" Private f1 as Integer #End Region Custom Event E As System.Action #Region "Region" #End Region AddHandler(value As Action) End AddHandler #Region "Region" #End Region RemoveHandler(value As Action) End RemoveHandler #Region "Region" #End Region RaiseEvent() End RaiseEvent #Region "Region" #End Region End Event #Region "Region" Private f1 as Integer #End Region End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(source, parseOptions:=VisualBasicParseOptions.Default.WithLanguageVersion(LanguageVersion.VisualBasic12)) CompilationUtils.AssertTheseParseDiagnostics(compilation, <expected> </expected>) End Sub <Fact(), WorkItem(5072, "https://github.com/dotnet/roslyn/issues/5072")> Public Sub LangVersion_RegionEveryWhere04() Dim source = <compilation> <file name="a.vb"> Class TestClass #Region "Region" Sub New() End Sub #End Region #Region "Region" Shared Sub New() End Sub #End Region #Region "Region" Public Sub ASub() End Sub #End Region #Region "Region" Public Function AFunc() End Function #End Region #Region "Region" Shared Operator +(x As TestClass, y As TestClass) As TestClass End Operator #End Region #Region "Region" Property P As Integer #Region "Region" Get End Get #End Region #Region "Region" Set(value As Integer) End Set #End Region End Property #End Region #Region "Region" Custom Event E As System.Action #Region "Region" AddHandler(value As Action) End AddHandler #End Region #Region "Region" RemoveHandler(value As Action) End RemoveHandler #End Region #Region "Region" RaiseEvent() End RaiseEvent #End Region End Event #End Region End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(source, parseOptions:=VisualBasicParseOptions.Default.WithLanguageVersion(LanguageVersion.VisualBasic12)) CompilationUtils.AssertTheseParseDiagnostics(compilation, <expected> </expected>) End Sub <Fact(), WorkItem(5072, "https://github.com/dotnet/roslyn/issues/5072")> Public Sub LangVersion_RegionEveryWhere05() Dim source = <compilation> <file name="a.vb"> Class TestClass Property P As Integer Get #Region "Region" #End Region </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(source, parseOptions:=VisualBasicParseOptions.Default.WithLanguageVersion(LanguageVersion.VisualBasic12)) CompilationUtils.AssertTheseParseDiagnostics(compilation, <expected> BC30481: 'Class' statement must end with a matching 'End Class'. Class TestClass ~~~~~~~~~~~~~~~ BC30025: Property missing 'End Property'. Property P As Integer ~~~~~~~~~~~~~~~~~~~~~ BC30631: 'Get' statement must end with a matching 'End Get'. Get ~~~ </expected>) End Sub <Fact(), WorkItem(5072, "https://github.com/dotnet/roslyn/issues/5072")> Public Sub LangVersion_RegionEveryWhere06() Dim source = <compilation> <file name="a.vb"> Class TestClass Property P As Integer Get End Get #Region "Region" #End Region</file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(source, parseOptions:=VisualBasicParseOptions.Default.WithLanguageVersion(LanguageVersion.VisualBasic12)) CompilationUtils.AssertTheseParseDiagnostics(compilation, <expected> BC30481: 'Class' statement must end with a matching 'End Class'. Class TestClass ~~~~~~~~~~~~~~~ BC30025: Property missing 'End Property'. Property P As Integer ~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact(), WorkItem(5072, "https://github.com/dotnet/roslyn/issues/5072")> Public Sub LangVersion_RegionEveryWhere07() Dim source = <compilation> <file name="a.vb"> Class TestClass Property P As Integer Get #Region "Region" #End Region End Property End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(source, parseOptions:=VisualBasicParseOptions.Default.WithLanguageVersion(LanguageVersion.VisualBasic12)) CompilationUtils.AssertTheseParseDiagnostics(compilation, <expected> BC30631: 'Get' statement must end with a matching 'End Get'. Get ~~~ </expected>) End Sub <Fact(), WorkItem(5072, "https://github.com/dotnet/roslyn/issues/5072")> Public Sub LangVersion_RegionEveryWhere08() Dim source = <compilation> <file name="a.vb"> Class TestClass Sub Test() #if False #Region "Region" #End Region #End if End Sub End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(source, parseOptions:=VisualBasicParseOptions.Default.WithLanguageVersion(LanguageVersion.VisualBasic12)) CompilationUtils.AssertTheseParseDiagnostics(compilation, <expected> </expected>) End Sub <Fact(), WorkItem(5072, "https://github.com/dotnet/roslyn/issues/5072")> Public Sub LangVersion_RegionEveryWhere09() Dim source = <compilation> <file name="a.vb"> #Region "Region 1" #End Region ' 1 </file> <file name="b.vb"> #Region "Region 2" </file> <file name="c.vb"> #End Region ' 3 </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(source, parseOptions:=VisualBasicParseOptions.Default.WithLanguageVersion(LanguageVersion.VisualBasic12)) CompilationUtils.AssertTheseParseDiagnostics(compilation, <expected> BC30681: '#Region' statement must end with a matching '#End Region'. #Region "Region 2" ~~~~~~~~~~~~~~~~~~ BC30680: '#End Region' must be preceded by a matching '#Region'. #End Region ' 3 ~~~~~~~~~~~ </expected>) End Sub <Fact(), WorkItem(5072, "https://github.com/dotnet/roslyn/issues/5072")> Public Sub LangVersion_RegionEveryWhere10() Dim source = <compilation> <file name="a.vb"> Namespace NS1 #Region "Region1" #End Region ' 1 End Namespace #Region "Region2" Namespace NS2 #End Region ' 2 End Namespace Namespace NS3 #Region "Region3" End Namespace #End Region ' 3 Namespace NS4 #Region "Region4" End Namespace Namespace NS5 #End Region ' 4 End Namespace #Region "Region5" Namespace NS6 End Namespace #End Region ' 5 </file> <file name="b.vb"> Namespace NS7 #Region "Region6" End Namespace </file> <file name="c.vb"> Namespace NS8 #End Region ' 7 End Namespace </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(source, parseOptions:=VisualBasicParseOptions.Default.WithLanguageVersion(LanguageVersion.VisualBasic12)) CompilationUtils.AssertTheseParseDiagnostics(compilation, <expected> BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #End Region ' 2 ~~~~~~~~~~~ BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #End Region ' 3 ~~~~~~~~~~~ BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #End Region ' 4 ~~~~~~~~~~~ BC30681: '#Region' statement must end with a matching '#End Region'. #Region "Region6" ~~~~~~~~~~~~~~~~~ BC30680: '#End Region' must be preceded by a matching '#Region'. #End Region ' 7 ~~~~~~~~~~~ </expected>) End Sub <Fact(), WorkItem(5072, "https://github.com/dotnet/roslyn/issues/5072")> Public Sub LangVersion_RegionEveryWhere11() Dim source = <compilation> <file name="a.vb"> Module NS1 #Region "Region1" #End Region ' 1 End Module #Region "Region2" Module NS2 #End Region ' 2 End Module Module NS3 #Region "Region3" End Module #End Region ' 3 Module NS4 #Region "Region4" End Module Module NS5 #End Region ' 4 End Module #Region "Region5" Module NS6 End Module #End Region ' 5 </file> <file name="b.vb"> Module NS7 #Region "Region6" End Module </file> <file name="c.vb"> Module NS8 #End Region ' 7 End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(source, parseOptions:=VisualBasicParseOptions.Default.WithLanguageVersion(LanguageVersion.VisualBasic12)) CompilationUtils.AssertTheseParseDiagnostics(compilation, <expected> BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #End Region ' 2 ~~~~~~~~~~~ BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #End Region ' 3 ~~~~~~~~~~~ BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #End Region ' 4 ~~~~~~~~~~~ BC30681: '#Region' statement must end with a matching '#End Region'. #Region "Region6" ~~~~~~~~~~~~~~~~~ BC30680: '#End Region' must be preceded by a matching '#Region'. #End Region ' 7 ~~~~~~~~~~~ </expected>) End Sub <Fact(), WorkItem(5072, "https://github.com/dotnet/roslyn/issues/5072")> Public Sub LangVersion_RegionEveryWhere12() Dim source = <compilation> <file name="a.vb"> Class NS1 #Region "Region1" #End Region ' 1 End Class #Region "Region2" Class NS2 #End Region ' 2 End Class Class NS3 #Region "Region3" End Class #End Region ' 3 Class NS4 #Region "Region4" End Class Class NS5 #End Region ' 4 End Class #Region "Region5" Class NS6 End Class #End Region ' 5 </file> <file name="b.vb"> Class NS7 #Region "Region6" End Class </file> <file name="c.vb"> Class NS8 #End Region ' 7 End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(source, parseOptions:=VisualBasicParseOptions.Default.WithLanguageVersion(LanguageVersion.VisualBasic12)) CompilationUtils.AssertTheseParseDiagnostics(compilation, <expected> BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #End Region ' 2 ~~~~~~~~~~~ BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #End Region ' 3 ~~~~~~~~~~~ BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #End Region ' 4 ~~~~~~~~~~~ BC30681: '#Region' statement must end with a matching '#End Region'. #Region "Region6" ~~~~~~~~~~~~~~~~~ BC30680: '#End Region' must be preceded by a matching '#Region'. #End Region ' 7 ~~~~~~~~~~~ </expected>) End Sub <Fact(), WorkItem(5072, "https://github.com/dotnet/roslyn/issues/5072")> Public Sub LangVersion_RegionEveryWhere13() Dim source = <compilation> <file name="a.vb"> Structure NS1 #Region "Region1" #End Region ' 1 End Structure #Region "Region2" Structure NS2 #End Region ' 2 End Structure Structure NS3 #Region "Region3" End Structure #End Region ' 3 Structure NS4 #Region "Region4" End Structure Structure NS5 #End Region ' 4 End Structure #Region "Region5" Structure NS6 End Structure #End Region ' 5 </file> <file name="b.vb"> Structure NS7 #Region "Region6" End Structure </file> <file name="c.vb"> Structure NS8 #End Region ' 7 End Structure </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(source, parseOptions:=VisualBasicParseOptions.Default.WithLanguageVersion(LanguageVersion.VisualBasic12)) CompilationUtils.AssertTheseParseDiagnostics(compilation, <expected> BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #End Region ' 2 ~~~~~~~~~~~ BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #End Region ' 3 ~~~~~~~~~~~ BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #End Region ' 4 ~~~~~~~~~~~ BC30681: '#Region' statement must end with a matching '#End Region'. #Region "Region6" ~~~~~~~~~~~~~~~~~ BC30680: '#End Region' must be preceded by a matching '#Region'. #End Region ' 7 ~~~~~~~~~~~ </expected>) End Sub <Fact(), WorkItem(5072, "https://github.com/dotnet/roslyn/issues/5072")> Public Sub LangVersion_RegionEveryWhere14() Dim source = <compilation> <file name="a.vb"> Interface NS1 #Region "Region1" #End Region ' 1 End Interface #Region "Region2" Interface NS2 #End Region ' 2 End Interface Interface NS3 #Region "Region3" End Interface #End Region ' 3 Interface NS4 #Region "Region4" End Interface Interface NS5 #End Region ' 4 End Interface #Region "Region5" Interface NS6 End Interface #End Region ' 5 </file> <file name="b.vb"> Interface NS7 #Region "Region6" End Interface </file> <file name="c.vb"> Interface NS8 #End Region ' 7 End Interface </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(source, parseOptions:=VisualBasicParseOptions.Default.WithLanguageVersion(LanguageVersion.VisualBasic12)) CompilationUtils.AssertTheseParseDiagnostics(compilation, <expected> BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #End Region ' 2 ~~~~~~~~~~~ BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #End Region ' 3 ~~~~~~~~~~~ BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #End Region ' 4 ~~~~~~~~~~~ BC30681: '#Region' statement must end with a matching '#End Region'. #Region "Region6" ~~~~~~~~~~~~~~~~~ BC30680: '#End Region' must be preceded by a matching '#Region'. #End Region ' 7 ~~~~~~~~~~~ </expected>) End Sub <Fact(), WorkItem(5072, "https://github.com/dotnet/roslyn/issues/5072")> Public Sub LangVersion_RegionEveryWhere15() Dim source = <compilation> <file name="a.vb"> Enum NS1 #Region "Region1" #End Region ' 1 End Enum #Region "Region2" Enum NS2 #End Region ' 2 End Enum Enum NS3 #Region "Region3" End Enum #End Region ' 3 Enum NS4 #Region "Region4" End Enum Enum NS5 #End Region ' 4 End Enum #Region "Region5" Enum NS6 End Enum #End Region ' 5 </file> <file name="b.vb"> Enum NS7 #Region "Region6" End Enum </file> <file name="c.vb"> Enum NS8 #End Region ' 7 End Enum </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(source, parseOptions:=VisualBasicParseOptions.Default.WithLanguageVersion(LanguageVersion.VisualBasic12)) CompilationUtils.AssertTheseParseDiagnostics(compilation, <expected> BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #End Region ' 2 ~~~~~~~~~~~ BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #End Region ' 3 ~~~~~~~~~~~ BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #End Region ' 4 ~~~~~~~~~~~ BC30681: '#Region' statement must end with a matching '#End Region'. #Region "Region6" ~~~~~~~~~~~~~~~~~ BC30680: '#End Region' must be preceded by a matching '#Region'. #End Region ' 7 ~~~~~~~~~~~ </expected>) End Sub <Fact(), WorkItem(5072, "https://github.com/dotnet/roslyn/issues/5072")> Public Sub LangVersion_RegionEveryWhere16() Dim source = <compilation> <file name="a.vb"> Class NS1 Property P1 As Integer #Region "Region1" #End Region ' 1 Get End Get Set End Set End Property End Class Class NS2 #Region "Region2" Property P1 As Integer #End Region ' 2 Get End Get Set End Set End Property End Class Class NS3 Property P1 As Integer #Region "Region3" Get End Get Set End Set End Property #End Region ' 3 End Class Class NS4 Property P1 As Integer #Region "Region4" Get End Get Set End Set End Property Property P2 As Integer #End Region ' 4 Get End Get Set End Set End Property End Class Class NS6 #Region "Region5" Property P1 As Integer Get End Get Set End Set End Property #End Region ' 5 End Class </file> <file name="b.vb"> Class NS7 Property P1 As Integer #Region "Region6" Get End Get Set End Set End Property End Class </file> <file name="c.vb"> Class NS8 Property P1 As Integer #End Region ' 7 Get End Get Set End Set End Property End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(source, parseOptions:=VisualBasicParseOptions.Default.WithLanguageVersion(LanguageVersion.VisualBasic12)) CompilationUtils.AssertTheseParseDiagnostics(compilation, <expected> BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #End Region ' 2 ~~~~~~~~~~~ BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #End Region ' 3 ~~~~~~~~~~~ BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #End Region ' 4 ~~~~~~~~~~~ BC30681: '#Region' statement must end with a matching '#End Region'. #Region "Region6" ~~~~~~~~~~~~~~~~~ BC30680: '#End Region' must be preceded by a matching '#Region'. #End Region ' 7 ~~~~~~~~~~~ </expected>) End Sub <Fact(), WorkItem(5072, "https://github.com/dotnet/roslyn/issues/5072")> Public Sub LangVersion_RegionEveryWhere17() Dim source = <compilation> <file name="a.vb"> Class NS1 Custom Event E1 As System.Action #Region "Region1" #End Region ' 1 AddHandler(value As Action) End AddHandler RemoveHandler(value As Action) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class Class NS2 #Region "Region2" Custom Event E1 As System.Action #End Region ' 2 AddHandler(value As Action) End AddHandler RemoveHandler(value As Action) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class Class NS3 Custom Event E1 As System.Action #Region "Region3" AddHandler(value As Action) End AddHandler RemoveHandler(value As Action) End RemoveHandler RaiseEvent() End RaiseEvent End Event #End Region ' 3 End Class Class NS4 Custom Event E1 As System.Action #Region "Region4" AddHandler(value As Action) End AddHandler RemoveHandler(value As Action) End RemoveHandler RaiseEvent() End RaiseEvent End Event Custom Event E2 As System.Action #End Region ' 4 AddHandler(value As Action) End AddHandler RemoveHandler(value As Action) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class Class NS6 #Region "Region5" Custom Event E1 As System.Action AddHandler(value As Action) End AddHandler RemoveHandler(value As Action) End RemoveHandler RaiseEvent() End RaiseEvent End Event #End Region ' 5 End Class </file> <file name="b.vb"> Class NS7 Custom Event E1 As System.Action #Region "Region6" AddHandler(value As Action) End AddHandler RemoveHandler(value As Action) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class </file> <file name="c.vb"> Class NS8 Custom Event E1 As System.Action #End Region ' 7 AddHandler(value As Action) End AddHandler RemoveHandler(value As Action) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(source, parseOptions:=VisualBasicParseOptions.Default.WithLanguageVersion(LanguageVersion.VisualBasic12)) CompilationUtils.AssertTheseParseDiagnostics(compilation, <expected> BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #End Region ' 2 ~~~~~~~~~~~ BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #End Region ' 3 ~~~~~~~~~~~ BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #End Region ' 4 ~~~~~~~~~~~ BC30681: '#Region' statement must end with a matching '#End Region'. #Region "Region6" ~~~~~~~~~~~~~~~~~ BC30680: '#End Region' must be preceded by a matching '#Region'. #End Region ' 7 ~~~~~~~~~~~ </expected>) End Sub <Fact(), WorkItem(5072, "https://github.com/dotnet/roslyn/issues/5072")> Public Sub LangVersion_RegionEveryWhere18() Dim source = <compilation> <file name="a.vb"> #Region "Region1" Class NS1 #Region "Region2" Sub Test1() #End Region ' 2 End Sub End Class #End Region ' 1 </file> <file name="b.vb"> #Region "Region3" Class NS2 Sub Test1() #Region "Region4" End Sub #End Region ' 4 End Class #End Region ' 3 </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(source, parseOptions:=VisualBasicParseOptions.Default.WithLanguageVersion(LanguageVersion.VisualBasic12)) CompilationUtils.AssertTheseParseDiagnostics(compilation, <expected> BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #End Region ' 2 ~~~~~~~~~~~ BC36716: Visual Basic 12.0 does not support region directives within method bodies or regions crossing boundaries of declaration blocks. #Region "Region4" ~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact(), WorkItem(5072, "https://github.com/dotnet/roslyn/issues/5072")> Public Sub LangVersion_CObjInAttributes() Dim source = <compilation> <file name="a.vb"><![CDATA[ Class TestClass1 <System.ComponentModel.DefaultValue(CObj("Test"))> Public Property Test2 As String '<System.ComponentModel.DefaultValue(CType("Test", Object))> 'Public Property Test3 As String '<System.ComponentModel.DefaultValue(DirectCast("Test", Object))> 'Public Property Test4 As String '<System.ComponentModel.DefaultValue(TryCast("Test", Object))> 'Public Property Test5 As String End Class ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndReferences(source, {SystemRef}, parseOptions:=VisualBasicParseOptions.Default.WithLanguageVersion(LanguageVersion.VisualBasic12)) CompilationUtils.AssertTheseDiagnostics(compilation, <expected><![CDATA[ BC36716: Visual Basic 12.0 does not support CObj in attribute arguments. <System.ComponentModel.DefaultValue(CObj("Test"))> ~~~~ ]]></expected>) End Sub <Fact(), WorkItem(5072, "https://github.com/dotnet/roslyn/issues/5072")> Public Sub LangVersion_MultilineStrings() Dim source = <compilation> <file name="a.vb"><![CDATA[ Class TestClass Dim test4 = " This is a muiltiline string" End Class ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(source, parseOptions:=VisualBasicParseOptions.Default.WithLanguageVersion(LanguageVersion.VisualBasic12)) CompilationUtils.AssertTheseParseDiagnostics(compilation, <expected> BC36716: Visual Basic 12.0 does not support multiline string literals. Dim test4 = " ~~ </expected>) End Sub <Fact(), WorkItem(5072, "https://github.com/dotnet/roslyn/issues/5072")> Public Sub LangVersion_LineContinuationComments() Dim source = <compilation> <file name="a.vb"><![CDATA[ Class TestClass Dim test5 As String = "" Dim chars = From c In test5 'This is a test of comments in a linq statement Let asc = Asc(c) 'VS2015 can handle this Select asc Sub Test() Dim chars2 = From c In test5 'This is a test of comments in a linq statement Let asc = Asc(c) 'VS2015 can handle this Select asc End Sub End Class ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(source, parseOptions:=VisualBasicParseOptions.Default.WithLanguageVersion(LanguageVersion.VisualBasic12)) CompilationUtils.AssertTheseParseDiagnostics(compilation, <expected> BC36716: Visual Basic 12.0 does not support line continuation comments. Dim chars = From c In test5 'This is a test of comments in a linq statement ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 12.0 does not support line continuation comments. Dim chars2 = From c In test5 'This is a test of comments in a linq statement ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) compilation = CompilationUtils.CreateCompilationWithMscorlib40(source, parseOptions:=VisualBasicParseOptions.Default.WithLanguageVersion(LanguageVersion.VisualBasic9)) CompilationUtils.AssertTheseParseDiagnostics(compilation, <expected> BC36716: Visual Basic 9.0 does not support implicit line continuation. Dim chars = From c In test5 'This is a test of comments in a linq statement ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 9.0 does not support implicit line continuation. Dim chars2 = From c In test5 'This is a test of comments in a linq statement ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact(), WorkItem(5072, "https://github.com/dotnet/roslyn/issues/5072")> Public Sub LangVersion_TypeOfIsNot() Dim source = <compilation> <file name="a.vb"><![CDATA[ Class TestClass Sub Test() Dim test6 As String = "" If TypeOf test6 IsNot System.String Then Console.WriteLine("That string isn't a string") End Sub End Class ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(source, parseOptions:=VisualBasicParseOptions.Default.WithLanguageVersion(LanguageVersion.VisualBasic12)) CompilationUtils.AssertTheseParseDiagnostics(compilation, <expected> BC36716: Visual Basic 12.0 does not support TypeOf IsNot expression. If TypeOf test6 IsNot System.String Then Console.WriteLine("That string isn't a string") ~~~~~ </expected>) End Sub <Fact(), WorkItem(5072, "https://github.com/dotnet/roslyn/issues/5072")> Public Sub LangVersion_YearFirstDateLiterals() Dim source = <compilation> <file name="a.vb"><![CDATA[ Class TestClass Sub Test() Dim d = #2015-08-23# End Sub End Class ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(source, parseOptions:=VisualBasicParseOptions.Default.WithLanguageVersion(LanguageVersion.VisualBasic12)) CompilationUtils.AssertTheseParseDiagnostics(compilation, <expected> BC36716: Visual Basic 12.0 does not support year-first date literals. Dim d = #2015-08-23# ~~~~~~~~~~~~ </expected>) End Sub <Fact(), WorkItem(5072, "https://github.com/dotnet/roslyn/issues/5072")> Public Sub LangVersion_Pragma() Dim source = <compilation> <file name="a.vb"><![CDATA[ Class TestClass Sub Test() #Disable Warning BC42024 Dim test7 As String 'Should have no "unused variable" warning #Enable Warning BC42024 End Sub End Class ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(source, parseOptions:=VisualBasicParseOptions.Default.WithLanguageVersion(LanguageVersion.VisualBasic12)) CompilationUtils.AssertTheseParseDiagnostics(compilation, <expected> BC36716: Visual Basic 12.0 does not support warning directives. #Disable Warning BC42024 ~~~~~~~~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 12.0 does not support warning directives. #Enable Warning BC42024 ~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact(), WorkItem(5072, "https://github.com/dotnet/roslyn/issues/5072")> Public Sub LangVersion_PartialModulesAndInterfaces() Dim source = <compilation> <file name="a.vb"><![CDATA[ Partial Module Module1 End Module Partial Interface IFace End Interface ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(source, parseOptions:=VisualBasicParseOptions.Default.WithLanguageVersion(LanguageVersion.VisualBasic12)) CompilationUtils.AssertTheseParseDiagnostics(compilation, <expected> BC36716: Visual Basic 12.0 does not support partial modules. Partial Module Module1 ~~~~~~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 12.0 does not support partial interfaces. Partial Interface IFace ~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact(), WorkItem(5072, "https://github.com/dotnet/roslyn/issues/5072")> Public Sub LangVersion_ImplementReadonlyWithReadwrite() Dim source = <compilation> <file name="a.vb"><![CDATA[ Interface IReadOnly ReadOnly Property Test1 As String WriteOnly Property Test2 As String End Interface Class ReadWrite Implements IReadOnly Public Property Test1 As String Implements IReadOnly.Test1 Public Property Test2 As String Implements IReadOnly.Test2 End Class ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndReferences(source, {SystemRef}, parseOptions:=VisualBasicParseOptions.Default.WithLanguageVersion(LanguageVersion.VisualBasic12)) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36716: Visual Basic 12.0 does not support implementing read-only or write-only property with read-write property. Public Property Test1 As String Implements IReadOnly.Test1 ~~~~~~~~~~~~~~~ BC36716: Visual Basic 12.0 does not support implementing read-only or write-only property with read-write property. Public Property Test2 As String Implements IReadOnly.Test2 ~~~~~~~~~~~~~~~ </expected>) End Sub <Fact(), WorkItem(13617, "https://github.com/dotnet/roslyn/issues/13617")> Public Sub MissingTypeArgumentInGenericExtensionMethod() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.CompilerServices Module FooExtensions <Extension()> Public Function ExtensionMethod0(ByVal obj As Object) Return GetType(Object) End Function <Extension()> Public Function ExtensionMethod1(Of T)(ByVal obj As Object) Return GetType(T) End Function <Extension()> Public Function ExtensionMethod2(Of T1, T2)(ByVal obj As Object) Return GetType(T1) End Function End Module Module Module1 Sub Main() Dim omittedArg0 As Type = "string literal".ExtensionMethod0(Of )() Dim omittedArg1 As Type = "string literal".ExtensionMethod1(Of )() Dim omittedArg2 As Type = "string literal".ExtensionMethod2(Of )() Dim omittedArgFunc0 As Func(Of Object) = "string literal".ExtensionMethod0(Of ) Dim omittedArgFunc1 As Func(Of Object) = "string literal".ExtensionMethod1(Of ) Dim omittedArgFunc2 As Func(Of Object) = "string literal".ExtensionMethod2(Of ) Dim moreArgs0 As Type = "string literal".ExtensionMethod0(Of Integer)() Dim moreArgs1 As Type = "string literal".ExtensionMethod1(Of Integer, Boolean)() Dim moreArgs2 As Type = "string literal".ExtensionMethod2(Of Integer, Boolean, String)() Dim lessArgs1 As Type = "string literal".ExtensionMethod1() Dim lessArgs2 As Type = "string literal".ExtensionMethod2(Of Integer)() Dim nonExistingMethod0 As Type = "string literal".ExtensionMethodNotFound0() Dim nonExistingMethod1 As Type = "string literal".ExtensionMethodNotFound1(Of Integer)() Dim nonExistingMethod2 As Type = "string literal".ExtensionMethodNotFound2(Of Integer, String)() Dim exactArgs0 As Type = "string literal".ExtensionMethod0() Dim exactArgs1 As Type = "string literal".ExtensionMethod1(Of Integer)() Dim exactArgs2 As Type = "string literal".ExtensionMethod2(Of Integer, Boolean)() End Sub End Module ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, {Net40.SystemCore}) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36907: Extension method 'Public Function ExtensionMethod0() As Object' defined in 'FooExtensions' is not generic (or has no free type parameters) and so cannot have type arguments. Dim omittedArg0 As Type = "string literal".ExtensionMethod0(Of )() ~~~~~ BC30182: Type expected. Dim omittedArg0 As Type = "string literal".ExtensionMethod0(Of )() ~ BC30182: Type expected. Dim omittedArg1 As Type = "string literal".ExtensionMethod1(Of )() ~ BC36590: Too few type arguments to extension method 'Public Function ExtensionMethod2(Of T1, T2)() As Object' defined in 'FooExtensions'. Dim omittedArg2 As Type = "string literal".ExtensionMethod2(Of )() ~~~~~ BC30182: Type expected. Dim omittedArg2 As Type = "string literal".ExtensionMethod2(Of )() ~ BC36907: Extension method 'Public Function ExtensionMethod0() As Object' defined in 'FooExtensions' is not generic (or has no free type parameters) and so cannot have type arguments. Dim omittedArgFunc0 As Func(Of Object) = "string literal".ExtensionMethod0(Of ) ~~~~~ BC30182: Type expected. Dim omittedArgFunc0 As Func(Of Object) = "string literal".ExtensionMethod0(Of ) ~ BC30182: Type expected. Dim omittedArgFunc1 As Func(Of Object) = "string literal".ExtensionMethod1(Of ) ~ BC36590: Too few type arguments to extension method 'Public Function ExtensionMethod2(Of T1, T2)() As Object' defined in 'FooExtensions'. Dim omittedArgFunc2 As Func(Of Object) = "string literal".ExtensionMethod2(Of ) ~~~~~ BC30182: Type expected. Dim omittedArgFunc2 As Func(Of Object) = "string literal".ExtensionMethod2(Of ) ~ BC36907: Extension method 'Public Function ExtensionMethod0() As Object' defined in 'FooExtensions' is not generic (or has no free type parameters) and so cannot have type arguments. Dim moreArgs0 As Type = "string literal".ExtensionMethod0(Of Integer)() ~~~~~~~~~~~~ BC36591: Too many type arguments to extension method 'Public Function ExtensionMethod1(Of T)() As Object' defined in 'FooExtensions'. Dim moreArgs1 As Type = "string literal".ExtensionMethod1(Of Integer, Boolean)() ~~~~~~~~~~~~~~~~~~~~~ BC36591: Too many type arguments to extension method 'Public Function ExtensionMethod2(Of T1, T2)() As Object' defined in 'FooExtensions'. Dim moreArgs2 As Type = "string literal".ExtensionMethod2(Of Integer, Boolean, String)() ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36589: Type parameter 'T' for extension method 'Public Function ExtensionMethod1(Of T)() As Object' defined in 'FooExtensions' cannot be inferred. Dim lessArgs1 As Type = "string literal".ExtensionMethod1() ~~~~~~~~~~~~~~~~ BC36590: Too few type arguments to extension method 'Public Function ExtensionMethod2(Of T1, T2)() As Object' defined in 'FooExtensions'. Dim lessArgs2 As Type = "string literal".ExtensionMethod2(Of Integer)() ~~~~~~~~~~~~ BC30456: 'ExtensionMethodNotFound0' is not a member of 'String'. Dim nonExistingMethod0 As Type = "string literal".ExtensionMethodNotFound0() ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30456: 'ExtensionMethodNotFound1' is not a member of 'String'. Dim nonExistingMethod1 As Type = "string literal".ExtensionMethodNotFound1(Of Integer)() ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30456: 'ExtensionMethodNotFound2' is not a member of 'String'. Dim nonExistingMethod2 As Type = "string literal".ExtensionMethodNotFound2(Of Integer, String)() ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub End Class End Namespace
1
dotnet/roslyn
56,011
React to string comparison changing on .NET Core
The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
jaredpar
"2021-08-30T17:18:52Z"
"2021-08-30T20:20:04Z"
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
4d99cda6e446e77dbb302e26388c1093bd3ef569
React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
./src/Compilers/VisualBasic/Test/Semantic/Compilation/SemanticModelLookupSymbolsAPITests.vb
' 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.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Partial Public Class SemanticModelTests Inherits SemanticModelTestBase #Region "LookupSymbols Function" <Fact()> Public Sub LookupSymbols1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Class B Public f1 as Integer End Class Class D Inherits B Public Sub goo() Console.WriteLine() 'BIND:"WriteLine" End Sub End Class Module M Public f1 As Integer Public f2 As Integer End Module Module M2 Public f1 As Integer Public f2 As Integer End Module </file> </compilation>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim pos As Integer = FindBindingTextPosition(compilation, "a.vb") Dim syms = semanticModel.LookupSymbols(pos, Nothing, "f1") Assert.Equal(1, syms.Length) Assert.Equal("B.f1 As System.Int32", syms(0).ToTestDisplayString()) ' This one is tricky.. M.f2 and M2.f2 are ambiguous at the same ' binding scope, so we get both symbols here. syms = semanticModel.LookupSymbols(pos, Nothing, "f2") Assert.Equal(2, syms.Length) Dim fullNames = From s In syms.AsEnumerable Order By s.ToTestDisplayString() Select s.ToTestDisplayString() Assert.Equal("M.f2 As System.Int32", fullNames(0)) Assert.Equal("M2.f2 As System.Int32", fullNames(1)) syms = semanticModel.LookupSymbols(pos, Nothing, "int32") Assert.Equal(1, syms.Length) Assert.Equal("System.Int32", syms(0).ToTestDisplayString()) CompilationUtils.AssertNoErrors(compilation) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:="https://github.com/dotnet/roslyn/issues/29531")> Public Sub LookupSymbols2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System Class B End Class Class A Class B(Of X) End Class Class B(Of X, Y) End Class Sub M() Dim B As Integer Console.WriteLine() End Sub End Class </file> </compilation>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim posInside As Integer = CompilationUtils.FindPositionFromText(tree, "WriteLine") Dim posOutside As Integer = CompilationUtils.FindPositionFromText(tree, "Sub M") ' Inside the method, "B" shadows classes of any arity. Dim syms = semanticModel.LookupSymbols(posInside, Nothing, "b", Nothing) Assert.Equal(1, syms.Length) Assert.Equal("B As System.Int32", syms(0).ToTestDisplayString()) Assert.Equal(SymbolKind.Local, syms(0).Kind) ' Outside the method, all B's are available. syms = semanticModel.LookupSymbols(posOutside, Nothing, "b", Nothing) Assert.Equal(3, syms.Length) Dim fullNames = From s In syms.AsEnumerable Order By s.ToTestDisplayString() Select s.ToTestDisplayString() Assert.Equal("A.B(Of X)", fullNames(0)) Assert.Equal("A.B(Of X, Y)", fullNames(1)) Assert.Equal("B", fullNames(2)) ' Inside the method, all B's are available if only types/namespace are allowed syms = semanticModel.LookupNamespacesAndTypes(posOutside, Nothing, "b") Assert.Equal(3, syms.Length) fullNames = From s In syms.AsEnumerable Order By s.ToTestDisplayString() Select s.ToTestDisplayString() Assert.Equal("A.B(Of X)", fullNames(0)) Assert.Equal("A.B(Of X, Y)", fullNames(1)) Assert.Equal("B", fullNames(2)) CompilationUtils.AssertNoErrors(compilation) End Sub <Fact()> Public Sub LookupSymbols3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports AliasZ = B.Z Class A Public Class Z(Of X) End Class Public Class Z(Of X, Y) End Class End Class Class B Inherits A Public Class Z ' in B End Class Public Class Z(Of X) End Class End Class Class C Inherits B Public z As Integer ' in C End Class </file> </compilation>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim posInsideB As Integer = CompilationUtils.FindPositionFromText(tree, "in B") Dim posInsideC As Integer = CompilationUtils.FindPositionFromText(tree, "in C") ' Lookup Z, all arities, inside B Dim syms = semanticModel.LookupSymbols(posInsideB, name:="z") ' Assert.Equal(3, syms.Count) Dim fullNames = From s In syms.AsEnumerable Order By s.ToTestDisplayString() Select s.ToTestDisplayString() Assert.Equal("A.Z(Of X, Y)", fullNames(0)) Assert.Equal("B.Z", fullNames(1)) Assert.Equal("B.Z(Of X)", fullNames(2)) ' Lookup Z, all arities, inside C. Since fields shadow by name in VB, only the field is found. syms = semanticModel.LookupSymbols(posInsideC, name:="z") Assert.Equal(1, syms.Length) Assert.Equal("C.z As System.Int32", syms(0).ToTestDisplayString()) ' Lookup AliasZ, all arities, inside C syms = semanticModel.LookupSymbols(posInsideC, name:="aliasz") Assert.Equal(1, syms.Length) Assert.Equal("AliasZ=B.Z", syms(0).ToTestDisplayString()) ' Lookup AliasZ, all arities, inside C with container syms = semanticModel.LookupSymbols(posInsideC, name:="C") Assert.Equal(1, syms.Length) Assert.Equal("C", syms(0).ToTestDisplayString()) Dim C = DirectCast(syms.Single, NamespaceOrTypeSymbol) syms = semanticModel.LookupSymbols(posInsideC, name:="aliasz", container:=C) Assert.Equal(0, syms.Length) CompilationUtils.AssertNoErrors(compilation) End Sub <Fact()> Public Sub LookupSymbols4() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Namespace N1.N2 Class A Public X As Integer End Class Class B Inherits A Public Y As Integer End Class Class C Inherits B Public Z As Integer Public Sub M() System.Console.WriteLine() ' in M End Sub End Class End Namespace </file> </compilation>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim posInsideM As Integer = CompilationUtils.FindPositionFromText(tree, "in M") ' Lookup all symbols Dim syms = From s In semanticModel.LookupSymbols(posInsideM, name:=Nothing) Dim fullNames = From s In syms Order By s.ToTestDisplayString() Select s.ToTestDisplayString() Assert.Contains("N1.N2.A", fullNames) Assert.Contains("N1.N2.B", fullNames) Assert.Contains("N1.N2.C", fullNames) Assert.Contains("N1.N2.C.Z As System.Int32", fullNames) Assert.Contains("Sub N1.N2.C.M()", fullNames) Assert.Contains("N1", fullNames) Assert.Contains("N1.N2", fullNames) Assert.Contains("System", fullNames) Assert.Contains("Microsoft", fullNames) Assert.Contains("Function System.Object.ToString() As System.String", fullNames) CompilationUtils.AssertNoErrors(compilation) End Sub <Fact()> Public Sub LookupSymbolsMustNotBeInstance() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class A Public X As Integer Public Shared SX As Integer End Class Class B Inherits A Public Function Y() As Integer End Function Public Shared Function SY() As Integer End Function End Class Class C Inherits B Public Z As Integer ' in C End Class </file> </compilation>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim classC As NamedTypeSymbol = DirectCast(compilation.GlobalNamespace().GetMembers("C").Single(), NamedTypeSymbol) Dim posInsideC As Integer = CompilationUtils.FindPositionFromText(tree, "in C") Dim symbols = semanticModel.LookupStaticMembers(position:=posInsideC, container:=classC, name:=Nothing) Dim fullNames = From s In symbols.AsEnumerable Order By s.ToTestDisplayString() Select s.ToTestDisplayString() Assert.Equal(4, symbols.Length) Assert.Equal("A.SX As System.Int32", fullNames(0)) Assert.Equal("Function B.SY() As System.Int32", fullNames(1)) Assert.Equal("Function System.Object.Equals(objA As System.Object, objB As System.Object) As System.Boolean", fullNames(2)) Assert.Equal("Function System.Object.ReferenceEquals(objA As System.Object, objB As System.Object) As System.Boolean", fullNames(3)) CompilationUtils.AssertNoErrors(compilation) End Sub <Fact()> Public Sub LookupSymbolsInTypeParameter() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="a.vb"><![CDATA[ Imports System.Runtime.CompilerServices Interface IA Sub MA() End Interface Interface IB Sub MB() End Interface Interface IC Sub M(Of T, U)() End Interface Class C Implements IA Private Sub MA() Implements IA.MA End Sub Public Sub M(Of T)() End Sub End Class Class D(Of T As IB) Public Sub MD(Of U As {C, T, IC}, V As Structure)(_u As U, _v As V) End Sub End Class Module E <Extension()> Friend Sub [ME](c As IC, o As Object) End Sub <Extension()> Friend Sub [ME](v As System.ValueType) End Sub End Module ]]></file> </compilation>, {TestMetadata.Net40.SystemCore}) Dim tree = compilation.SyntaxTrees.Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim method = compilation.GlobalNamespace().GetMember(Of NamedTypeSymbol)("D").GetMember(Of MethodSymbol)("MD") Dim parameter = method.Parameters(0) Dim position = CompilationUtils.FindPositionFromText(tree, "As U") Dim symbols = semanticModel.LookupSymbols(position, container:=parameter.Type, includeReducedExtensionMethods:=True) CheckSymbols(symbols, "Sub C.M(Of T)()", "Function Object.ToString() As String", "Function Object.Equals(obj As Object) As Boolean", "Function Object.Equals(objA As Object, objB As Object) As Boolean", "Function Object.ReferenceEquals(objA As Object, objB As Object) As Boolean", "Function Object.GetHashCode() As Integer", "Function Object.GetType() As Type", "Sub IB.MB()", "Sub IC.ME(o As Object)") parameter = method.Parameters(1) position = CompilationUtils.FindPositionFromText(tree, "As V") symbols = semanticModel.LookupSymbols(position, container:=parameter.Type, includeReducedExtensionMethods:=True) CheckSymbols(symbols, "Function ValueType.Equals(obj As Object) As Boolean", "Function Object.Equals(obj As Object) As Boolean", "Function Object.Equals(objA As Object, objB As Object) As Boolean", "Function ValueType.GetHashCode() As Integer", "Function Object.GetHashCode() As Integer", "Function ValueType.ToString() As String", "Function Object.ToString() As String", "Function Object.ReferenceEquals(objA As Object, objB As Object) As Boolean", "Function Object.GetType() As Type", "Sub ValueType.ME()") CompilationUtils.AssertNoErrors(compilation) End Sub Private Shared Sub CheckSymbols(symbols As ImmutableArray(Of ISymbol), ParamArray descriptions As String()) CompilationUtils.CheckSymbols(symbols, descriptions) End Sub <Fact()> Public Sub LookupNames1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Namespace N1.N2 Class A Public X As Integer End Class Class B Inherits A Public Y As Integer End Class Class C Inherits B Public Z As Integer Public Sub M() System.Console.WriteLine() ' in M End Sub End Class End Namespace </file> </compilation>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim posInsideM As Integer = CompilationUtils.FindPositionFromText(tree, "in M") ' Lookup names Dim names As IEnumerable(Of String) = From n In semanticModel.LookupNames(posInsideM) Order By n Assert.Contains("A", names) Assert.Contains("B", names) Assert.Contains("C", names) Assert.Contains("Z", names) Assert.Contains("M", names) Assert.Contains("N1", names) Assert.Contains("N2", names) Assert.Contains("System", names) Assert.Contains("Microsoft", names) Assert.Contains("ToString", names) Assert.Contains("Equals", names) Assert.Contains("GetType", names) ' Lookup names, namespace and types only names = From n In semanticModel.LookupNames(posInsideM, namespacesAndTypesOnly:=True) Order By n Assert.Contains("A", names) Assert.Contains("B", names) Assert.Contains("C", names) Assert.DoesNotContain("Z", names) Assert.DoesNotContain("M", names) Assert.Contains("N1", names) Assert.Contains("N2", names) Assert.Contains("System", names) Assert.Contains("Microsoft", names) Assert.DoesNotContain("ToString", names) Assert.DoesNotContain("Equals", names) Assert.DoesNotContain("GetType", names) CompilationUtils.AssertNoErrors(compilation) End Sub <Fact()> Public Sub LookupNames2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class A Inherits B Public X As Integer End Class Class B Inherits A Public Y As Integer ' in B End Class </file> </compilation>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim posInsideB As Integer = CompilationUtils.FindPositionFromText(tree, "in B") CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30257: Class 'A' cannot inherit from itself: 'A' inherits from 'B'. 'B' inherits from 'A'. Inherits B ~ </expected>) ' Lookup names Dim names As IEnumerable(Of String) = From n In semanticModel.LookupNames(posInsideB) Order By n Assert.Contains("A", names) Assert.Contains("B", names) Assert.Contains("X", names) Assert.Contains("Y", names) End Sub <Fact()> Public Sub ObjectMembersOnInterfaces1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ObjectMembersOnInterfaces"> <file name="a.vb"> Module Module1 Sub Main() System.Console.WriteLine(System.IDisposable.Equals(1, 1)) Dim x As I1 = New C1() System.Console.WriteLine(x.GetHashCode()) 'BIND:"GetHashCode" End Sub End Module Interface I1 End Interface Class C1 Implements I1 Public Overrides Function GetHashCode() As Integer Return 1234 End Function End Class </file> </compilation>, TestOptions.ReleaseExe) CompileAndVerify(compilation, <![CDATA[ True 1234 ]]>) Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", container:=compilation.GetTypeByMetadataName("I1"), name:="GetHashCode") Assert.Equal(1, actual_lookupSymbols.Count) Assert.Equal("Function System.Object.GetHashCode() As System.Int32", actual_lookupSymbols(0).ToTestDisplayString()) Dim getHashCode = DirectCast(actual_lookupSymbols(0), MethodSymbol) Assert.Contains(getHashCode, GetLookupSymbols(compilation, "a.vb", container:=compilation.GetTypeByMetadataName("I1"))) End Sub <Fact()> Public Sub ObjectMembersOnInterfaces2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ObjectMembersOnInterfaces"> <file name="a.vb"> Imports System.Runtime.CompilerServices Module Module1 Sub Main() Dim x As I1 = Nothing x.GetHashCode() x.GetHashCode(1) x.ToString() x.ToString(1) x.ToString(1, 2) Dim y As I5 = Nothing y.GetHashCode() End Sub &lt;Extension()&gt; Function ToString(this As I1, x As Integer, y As Integer) As String Return Nothing End Function End Module Interface I1 Function GetHashCode(x As Integer) As Integer Function ToString(x As Integer) As Integer End Interface Interface I3 Function GetHashCode(x As Integer) As Integer End Interface Interface I4 Function GetHashCode() As Integer End Interface Interface I5 Inherits I3, I4 End Interface Namespace System.Runtime.CompilerServices &lt;AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)&gt; Class ExtensionAttribute Inherits Attribute End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <result> BC30455: Argument not specified for parameter 'x' of 'Function GetHashCode(x As Integer) As Integer'. x.GetHashCode() ~~~~~~~~~~~ BC30516: Overload resolution failed because no accessible 'ToString' accepts this number of arguments. x.ToString() ~~~~~~~~ </result> ) End Sub <Fact()> Public Sub LookupOfConstructorMemberOnMe() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="LookupOfConstructorMember"> <file name="a.vb"> Class B1 Public Sub New(x As Integer) End Sub Private Sub New(x as String) End Sub End Class Class C1 Inherits B1 Public Sub New(x As Integer, y as Integer) Me.New() 'BIND:"New" End Sub Private Sub New(x as String, y as Integer) End Sub End Class </file> </compilation>) Dim expected_in_lookupSymbols = { "Function System.Object.ToString() As System.String", "Function System.Object.Equals(obj As System.Object) As System.Boolean", "Function System.Object.Equals(objA As System.Object, objB As System.Object) As System.Boolean", "Function System.Object.ReferenceEquals(objA As System.Object, objB As System.Object) As System.Boolean", "Function System.Object.GetHashCode() As System.Int32", "Function System.Object.GetType() As System.Type", "Sub System.Object.Finalize()", "Function System.Object.MemberwiseClone() As System.Object", "Sub C1..ctor(x As System.Int32, y As System.Int32)", "Sub C1..ctor(x As System.String, y As System.Int32)" } Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", container:=compilation.GetTypeByMetadataName("C1"), name:=Nothing) Dim actual_lookupSymbols_strings = actual_lookupSymbols.Select(Function(s) s.ToTestDisplayString()).ToList() For Each s In expected_in_lookupSymbols Assert.Contains(s, actual_lookupSymbols_strings) Next Assert.Equal(expected_in_lookupSymbols.Count, actual_lookupSymbols_strings.Count) End Sub <Fact()> Public Sub LookupOfConstructorMemberOnMyClass() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="LookupOfConstructorMemberOnMyClass"> <file name="a.vb"> Class B1 Public Sub New(x As Integer) End Sub Private Sub New(x as String) End Sub End Class Class C1 Inherits B1 Public Sub New(x As Integer, y as Integer) MyClass.New() 'BIND:"New" End Sub Private Sub New(x as String, y as Integer) End Sub End Class </file> </compilation>) Dim expected_in_lookupSymbols = { "Function System.Object.ToString() As System.String", "Function System.Object.Equals(obj As System.Object) As System.Boolean", "Function System.Object.Equals(objA As System.Object, objB As System.Object) As System.Boolean", "Function System.Object.ReferenceEquals(objA As System.Object, objB As System.Object) As System.Boolean", "Function System.Object.GetHashCode() As System.Int32", "Function System.Object.GetType() As System.Type", "Sub System.Object.Finalize()", "Function System.Object.MemberwiseClone() As System.Object", "Sub C1..ctor(x As System.Int32, y As System.Int32)", "Sub C1..ctor(x As System.String, y As System.Int32)" } Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", container:=compilation.GetTypeByMetadataName("C1"), name:=Nothing) Dim actual_lookupSymbols_strings = actual_lookupSymbols.Select(Function(s) s.ToTestDisplayString()).ToList() For Each s In expected_in_lookupSymbols Assert.Contains(s, actual_lookupSymbols_strings) Next Assert.Equal(expected_in_lookupSymbols.Count, actual_lookupSymbols_strings.Count) End Sub <Fact()> Public Sub LookupOfConstructorMemberOnMeNotInConstructor() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="LookupOfConstructorMemberOnMeNotInConstructor"> <file name="a.vb"> Class B1 Public Sub New(x As Integer) End Sub Private Sub New(x as String) End Sub End Class Class C1 Inherits B1 Public Sub New(x As Integer, y as Integer) End Sub Private Sub New(x as String, y as Integer) End Sub Public Sub q() Me.New() 'BIND:"New" End Sub End Class </file> </compilation>) Dim expected_in_lookupSymbols = { "Function System.Object.ToString() As System.String", "Function System.Object.Equals(obj As System.Object) As System.Boolean", "Function System.Object.Equals(objA As System.Object, objB As System.Object) As System.Boolean", "Function System.Object.ReferenceEquals(objA As System.Object, objB As System.Object) As System.Boolean", "Function System.Object.GetHashCode() As System.Int32", "Function System.Object.GetType() As System.Type", "Sub System.Object.Finalize()", "Function System.Object.MemberwiseClone() As System.Object", "Sub C1.q()" } Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", container:=compilation.GetTypeByMetadataName("C1"), name:=Nothing) Dim actual_lookupSymbols_strings = actual_lookupSymbols.Select(Function(s) s.ToTestDisplayString()).ToList() For Each s In expected_in_lookupSymbols Assert.Contains(s, actual_lookupSymbols_strings) Next Assert.Equal(expected_in_lookupSymbols.Count, actual_lookupSymbols_strings.Count) End Sub <Fact()> Public Sub LookupOfConstructorMemberOnMyClassNotInConstructor() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="LookupOfConstructorMemberOnMyClassNotInConstructor"> <file name="a.vb"> Class B1 Public Sub New(x As Integer) End Sub Private Sub New(x as String) End Sub End Class Class C1 Inherits B1 Public Sub New(x As Integer, y as Integer) End Sub Private Sub New(x as String, y as Integer) End Sub Public Sub q() MyClass.New() 'BIND:"New" End Sub End Class </file> </compilation>) Dim expected_in_lookupSymbols = { "Function System.Object.ToString() As System.String", "Function System.Object.Equals(obj As System.Object) As System.Boolean", "Function System.Object.Equals(objA As System.Object, objB As System.Object) As System.Boolean", "Function System.Object.ReferenceEquals(objA As System.Object, objB As System.Object) As System.Boolean", "Function System.Object.GetHashCode() As System.Int32", "Function System.Object.GetType() As System.Type", "Sub System.Object.Finalize()", "Function System.Object.MemberwiseClone() As System.Object", "Sub C1.q()" } Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", container:=compilation.GetTypeByMetadataName("C1"), name:=Nothing) Dim actual_lookupSymbols_strings = actual_lookupSymbols.Select(Function(s) s.ToTestDisplayString()).ToList() For Each s In expected_in_lookupSymbols Assert.Contains(s, actual_lookupSymbols_strings) Next Assert.Equal(expected_in_lookupSymbols.Count, actual_lookupSymbols_strings.Count) End Sub <Fact()> Public Sub LookupOfConstructorMemberOnMeNoInstance() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="LookupOfConstructorMember"> <file name="a.vb"> Class B1 Public Sub New(x As Integer) End Sub Private Sub New(x as String) End Sub End Class Class C1 Inherits B1 Public Sub New(x As Integer, y as Integer) Me.New() 'BIND:"New" End Sub Private Sub New(x as String, y as Integer) End Sub End Class </file> </compilation>) Dim expected_in_lookupSymbols = { "Function System.Object.Equals(objA As System.Object, objB As System.Object) As System.Boolean", "Function System.Object.ReferenceEquals(objA As System.Object, objB As System.Object) As System.Boolean" } Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", container:=compilation.GetTypeByMetadataName("C1"), name:=Nothing, mustBeStatic:=True) Dim actual_lookupSymbols_strings = actual_lookupSymbols.Select(Function(s) s.ToTestDisplayString()).ToList() For Each s In expected_in_lookupSymbols Assert.Contains(s, actual_lookupSymbols_strings) Next Assert.Equal(expected_in_lookupSymbols.Count, actual_lookupSymbols_strings.Count) End Sub <Fact()> Public Sub LookupOfConstructorMemberOnMyClassNoInstance() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="LookupOfConstructorMemberOnMyClassNoInstance"> <file name="a.vb"> Class B1 Public Sub New(x As Integer) End Sub Private Sub New(x as String) End Sub End Class Class C1 Inherits B1 Public Sub New(x As Integer, y as Integer) MyClass.New() 'BIND:"New" End Sub Private Sub New(x as String, y as Integer) End Sub End Class </file> </compilation>) Dim expected_in_lookupSymbols = { "Function System.Object.Equals(objA As System.Object, objB As System.Object) As System.Boolean", "Function System.Object.ReferenceEquals(objA As System.Object, objB As System.Object) As System.Boolean" } Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", container:=compilation.GetTypeByMetadataName("C1"), name:=Nothing, mustBeStatic:=True) Dim actual_lookupSymbols_strings = actual_lookupSymbols.Select(Function(s) s.ToTestDisplayString()).ToList() For Each s In expected_in_lookupSymbols Assert.Contains(s, actual_lookupSymbols_strings) Next Assert.Equal(expected_in_lookupSymbols.Count, actual_lookupSymbols_strings.Count) End Sub <Fact()> Public Sub LookupOfConstructorMemberOnMyBase() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="LookupOfConstructorMemberOnMyBase"> <file name="a.vb"> Class B1 Public Sub New(x As Integer) End Sub Private Sub New(x as String) End Sub End Class Class C1 Inherits B1 Public Sub New(x As Integer, y as Integer) MyBase.New() 'BIND:"New" End Sub Private Sub New(x as String, y as Integer) End Sub Public Sub C() End Sub End Class </file> </compilation>) Dim expected_in_lookupSymbols = { "Function System.Object.ToString() As System.String", "Function System.Object.Equals(obj As System.Object) As System.Boolean", "Function System.Object.Equals(objA As System.Object, objB As System.Object) As System.Boolean", "Function System.Object.ReferenceEquals(objA As System.Object, objB As System.Object) As System.Boolean", "Function System.Object.GetHashCode() As System.Int32", "Function System.Object.GetType() As System.Type", "Sub B1..ctor(x As System.Int32)" } Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", container:=compilation.GetTypeByMetadataName("B1"), name:=Nothing) Dim actual_lookupSymbols_strings = actual_lookupSymbols.Select(Function(s) s.ToTestDisplayString()).ToList() For Each s In expected_in_lookupSymbols Assert.Contains(s, actual_lookupSymbols_strings) Next Assert.Equal(expected_in_lookupSymbols.Count, actual_lookupSymbols_strings.Count) End Sub <Fact()> Public Sub LookupOfInaccessibleOnMyBase() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="LookupOfConstructorMemberOnMyBase"> <file name="a.vb"> Class B1 Public Sub New(x As Integer) End Sub Private Sub New(x as String) End Sub End Class Class C1 Inherits B1 Public Sub New(x As Integer, y as Integer) MyBase.New() 'BIND:"New" End Sub Private Sub New(x as String, y as Integer) End Sub End Class </file> </compilation>) Dim expected_in_lookupSymbols = { "Function System.Object.ToString() As System.String", "Function System.Object.Equals(obj As System.Object) As System.Boolean", "Function System.Object.Equals(objA As System.Object, objB As System.Object) As System.Boolean", "Function System.Object.ReferenceEquals(objA As System.Object, objB As System.Object) As System.Boolean", "Function System.Object.GetHashCode() As System.Int32", "Function System.Object.GetType() As System.Type", "Sub System.Object.Finalize()", "Function System.Object.MemberwiseClone() As System.Object", "Sub B1..ctor(x As System.Int32)", "Sub B1..ctor(x As System.String)" } Dim tree = compilation.SyntaxTrees.Single() Dim model = compilation.GetSemanticModel(tree) Dim position = tree.ToString().IndexOf("MyBase", StringComparison.Ordinal) Dim binder = DirectCast(model, VBSemanticModel).GetEnclosingBinder(position) Dim baseType = compilation.GlobalNamespace.GetMember(Of NamedTypeSymbol)("B1") Dim useSiteDiagnostics As HashSet(Of DiagnosticInfo) = Nothing Dim result = LookupResult.GetInstance() binder.LookupMember(result, baseType, "Finalize", 0, LookupOptions.IgnoreAccessibility, useSiteDiagnostics) Assert.Null(useSiteDiagnostics) Assert.True(result.IsGood) Assert.Equal("Sub System.Object.Finalize()", result.SingleSymbol.ToTestDisplayString()) result.Clear() binder.LookupMember(result, baseType, "MemberwiseClone", 0, LookupOptions.IgnoreAccessibility, useSiteDiagnostics) Assert.Null(useSiteDiagnostics) Assert.True(result.IsGood) Assert.Equal("Function System.Object.MemberwiseClone() As System.Object", result.SingleSymbol.ToTestDisplayString()) result.Free() End Sub #End Region #Region "Regression" <WorkItem(539107, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539107")> <Fact()> Public Sub LookupAtLocationEndSubNode() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Class Test Public Sub Method1(ByVal param1 As Integer) Dim count As Integer = 45 End Sub 'BIND:"End Sub" End Class </file> </compilation>) Dim expected_in_lookupNames = { "count", "param1" } Dim expected_in_lookupSymbols = { "count As System.Int32", "param1 As System.Int32" } Dim actual_lookupNames = GetLookupNames(compilation, "a.vb") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb") Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) Assert.Contains(expected_in_lookupNames(0), actual_lookupNames) Assert.Contains(expected_in_lookupNames(1), actual_lookupNames) Assert.Contains(expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) Assert.Contains(expected_in_lookupSymbols(1), actual_lookupSymbols_as_string) End Sub <WorkItem(539114, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539114")> <Fact()> Public Sub LookupAtLocationSubBlockNode() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Class Test Public Sub Method1(ByVal param1 As Integer) 'BIND:"Public Sub Method1(ByVal param1 As Integer)" Dim count As Integer = 45 End Sub End Class </file> </compilation>) Dim not_expected_in_lookupNames = { "count", "param1" } Dim not_expected_in_lookupSymbols = { "count As System.Int32", "param1 As System.Int32" } Dim actual_lookupNames = GetLookupNames(compilation, "a.vb") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb") Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) Assert.DoesNotContain(not_expected_in_lookupNames(0), actual_lookupNames) Assert.DoesNotContain(not_expected_in_lookupNames(1), actual_lookupNames) Assert.DoesNotContain(not_expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) Assert.DoesNotContain(not_expected_in_lookupSymbols(1), actual_lookupSymbols_as_string) End Sub <WorkItem(539119, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539119")> <Fact()> Public Sub LookupSymbolsByNameIncorrectArity() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Class Test Public Sub Method1(ByVal param1 As Integer) Dim count As Integer = 45 'BIND:"45" End Sub End Class </file> </compilation>) Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="count", arity:=1) Assert.Empty(actual_lookupSymbols) End Sub <WorkItem(539130, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539130")> <Fact()> Public Sub LookupWithNameZeroArity() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Module Module1 Sub Method1(Of T)(i As T) End Sub Sub Method1(Of T, U)(i As T, j As U) End Sub Sub Method1(i As Integer) End Sub Sub Method1(i As Integer, j As Integer) End Sub Public Sub Main() Dim x As Integer = 45 'BIND:"45" End Sub End Module </file> </compilation>) Dim expected_in_lookupSymbols = { "Sub Module1.Method1(i As System.Int32)", "Sub Module1.Method1(i As System.Int32, j As System.Int32)" } Dim not_expected_in_lookupSymbols = { "Sub Module1.Method1(Of T)(i As T)", "Sub Module1.Method1(Of T, U)(i As T, j As U)" } Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="Method1", arity:=0) Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) Assert.Contains(expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) Assert.Contains(expected_in_lookupSymbols(1), actual_lookupSymbols_as_string) Assert.DoesNotContain(not_expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) Assert.DoesNotContain(not_expected_in_lookupSymbols(1), actual_lookupSymbols_as_string) End Sub <WorkItem(5004, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub LookupExcludeInAppropriateNS() Dim compilation = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation name="GetSemanticInfo"> <file name="a.vb"> Module Module1 End Module </file> </compilation>, {SystemDataRef}) Dim not_expected_in_lookup = { "<CrtImplementationDetails>", "<CppImplementationDetails>" } Dim tree = compilation.SyntaxTrees.Single() Dim model = compilation.GetSemanticModel(tree) Const position = 0 Dim binder = DirectCast(model, VBSemanticModel).GetEnclosingBinder(position) Dim actual_lookupSymbols = model.LookupSymbols(position) Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) Assert.DoesNotContain(not_expected_in_lookup(0), actual_lookupSymbols_as_string) Assert.DoesNotContain(not_expected_in_lookup(1), actual_lookupSymbols_as_string) End Sub <WorkItem(539166, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539166")> <Fact()> Public Sub LookupLocationInsideFunctionIgnoreReturnVariable() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Class Test Function Func1() As Integer Dim x As Integer = "10" Return 10 End Function End Class </file> </compilation>) Dim tree = compilation.SyntaxTrees.Single() Dim model = compilation.GetSemanticModel(tree) Dim position = tree.ToString().IndexOf("Dim", StringComparison.Ordinal) Dim binder = DirectCast(model, VBSemanticModel).GetEnclosingBinder(position) Dim result = LookupResult.GetInstance() Dim useSiteDiagnostics As HashSet(Of DiagnosticInfo) = Nothing binder.Lookup(result, "Func1", arity:=0, options:=LookupOptions.MustNotBeReturnValueVariable, useSiteDiagnostics:=useSiteDiagnostics) Assert.Null(useSiteDiagnostics) Assert.True(result.IsGood) Assert.Equal("Function Test.Func1() As System.Int32", result.SingleSymbol.ToTestDisplayString()) result.Clear() binder.Lookup(result, "x", arity:=0, options:=LookupOptions.MustNotBeReturnValueVariable, useSiteDiagnostics:=useSiteDiagnostics) Assert.Null(useSiteDiagnostics) Assert.True(result.IsGood) Assert.Equal("x As System.Int32", result.SingleSymbol.ToTestDisplayString()) result.Free() End Sub <WorkItem(539166, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539166")> <Fact()> Public Sub LookupLocationInsideFunction() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Class Test Function Func1() As Integer Dim x As Integer = "10" 'BIND:"10" Return 10 End Function End Class </file> </compilation>) Dim expected_in_lookupNames = { "Func1", "x" } Dim expected_in_lookupSymbols = { "Func1 As System.Int32", "x As System.Int32" } Dim actual_lookupNames = GetLookupNames(compilation, "a.vb") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb") Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) Assert.Contains(expected_in_lookupNames(0), actual_lookupNames) Assert.Contains(expected_in_lookupNames(1), actual_lookupNames) Assert.Contains(expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) Assert.Contains(expected_in_lookupSymbols(1), actual_lookupSymbols_as_string) End Sub <WorkItem(527759, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527759")> <Fact()> Public Sub LookupAtLocationClassTypeBlockSyntax() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Class Test 'BIND:"Class Test" Public Sub PublicMethod() End Sub Protected Sub ProtectedMethod() End Sub Private Sub PrivateMethod() End Sub End Class </file> </compilation>) Dim expected_in_lookupNames = { "PublicMethod", "ProtectedMethod", "PrivateMethod" } Dim expected_in_lookupSymbols = { "Sub Test.PublicMethod()", "Sub Test.ProtectedMethod()", "Sub Test.PrivateMethod()" } Dim actual_lookupNames = GetLookupNames(compilation, "a.vb") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb") Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) Assert.Contains(expected_in_lookupNames(0), actual_lookupNames) Assert.Contains(expected_in_lookupNames(1), actual_lookupNames) Assert.Contains(expected_in_lookupNames(2), actual_lookupNames) Assert.Contains(expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) Assert.Contains(expected_in_lookupSymbols(1), actual_lookupSymbols_as_string) Assert.Contains(expected_in_lookupSymbols(2), actual_lookupSymbols_as_string) End Sub <WorkItem(527760, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527760")> <Fact()> Public Sub LookupAtLocationClassTypeStatementSyntax() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Class Test 'BIND:"Class Test" Public Sub PublicMethod() End Sub Protected Sub ProtectedMethod() End Sub Private Sub PrivateMethod() End Sub End Class </file> </compilation>) Dim expected_in_lookupNames = { "PublicMethod", "ProtectedMethod", "PrivateMethod" } Dim expected_in_lookupSymbols = { "Sub Test.PublicMethod()", "Sub Test.ProtectedMethod()", "Sub Test.PrivateMethod()" } Dim actual_lookupNames = GetLookupNames(compilation, "a.vb") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb") Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) Assert.Contains(expected_in_lookupNames(0), actual_lookupNames) Assert.Contains(expected_in_lookupNames(1), actual_lookupNames) Assert.Contains(expected_in_lookupNames(2), actual_lookupNames) Assert.Contains(expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) Assert.Contains(expected_in_lookupSymbols(1), actual_lookupSymbols_as_string) Assert.Contains(expected_in_lookupSymbols(2), actual_lookupSymbols_as_string) End Sub <WorkItem(527761, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527761")> <Fact()> Public Sub LookupAtLocationEndClassStatementSyntax() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Class Test Public Sub PublicMethod() End Sub Protected Sub ProtectedMethod() End Sub Private Sub PrivateMethod() End Sub End Class 'BIND:"End Class" </file> </compilation>) Dim expected_in_lookupNames = { "PublicMethod", "ProtectedMethod", "PrivateMethod" } Dim expected_in_lookupSymbols = { "Sub Test.PublicMethod()", "Sub Test.ProtectedMethod()", "Sub Test.PrivateMethod()" } Dim actual_lookupNames = GetLookupNames(compilation, "a.vb") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb") Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) Assert.Contains(expected_in_lookupNames(0), actual_lookupNames) Assert.Contains(expected_in_lookupNames(1), actual_lookupNames) Assert.Contains(expected_in_lookupNames(2), actual_lookupNames) Assert.Contains(expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) Assert.Contains(expected_in_lookupSymbols(1), actual_lookupSymbols_as_string) Assert.Contains(expected_in_lookupSymbols(2), actual_lookupSymbols_as_string) End Sub <WorkItem(539175, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539175")> <Fact()> Public Sub LookupAtLocationNamespaceBlockSyntax() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Namespace NS1 'BIND:"Namespace NS1" Namespace NS2 Class T1 End Class End Namespace Class T2 End Class Friend Class T3 End Class End Namespace Namespace NS3 End Namespace </file> </compilation>) Dim expected_in_lookupNames = { "NS1", "NS3" } Dim not_expected_in_lookupNames = { "NS2", "T1", "T2", "T3" } Dim expected_in_lookupSymbols = { "NS1", "NS3" } Dim not_expected_in_lookupSymbols = { "NS1.NS2", "NS1.NS2.T1", "NS1.T2", "NS1.T3" } Dim actual_lookupNames = GetLookupNames(compilation, "a.vb") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb") Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) Assert.Contains(expected_in_lookupNames(0), actual_lookupNames) Assert.Contains(expected_in_lookupNames(1), actual_lookupNames) Assert.DoesNotContain(not_expected_in_lookupNames(0), actual_lookupNames) Assert.DoesNotContain(not_expected_in_lookupNames(1), actual_lookupNames) Assert.DoesNotContain(not_expected_in_lookupNames(2), actual_lookupNames) Assert.DoesNotContain(not_expected_in_lookupNames(3), actual_lookupNames) Assert.Contains(expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) Assert.Contains(expected_in_lookupSymbols(1), actual_lookupSymbols_as_string) Assert.DoesNotContain(not_expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) Assert.DoesNotContain(not_expected_in_lookupSymbols(1), actual_lookupSymbols_as_string) Assert.DoesNotContain(not_expected_in_lookupSymbols(2), actual_lookupSymbols_as_string) Assert.DoesNotContain(not_expected_in_lookupSymbols(3), actual_lookupSymbols_as_string) End Sub <WorkItem(539177, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539177")> <Fact()> Public Sub LookupAtLocationEndNamespaceStatementSyntax() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Namespace NS1 Namespace NS2 Class T1 End Class End Namespace Class T2 End Class Friend Class T3 End Class End Namespace 'BIND:"End Namespace" Namespace NS3 End Namespace </file> </compilation>) Dim expected_in_lookupNames = { "NS1", "NS2", "NS3", "T2", "T3" } Dim not_expected_in_lookupNames = { "T1" } Dim expected_in_lookupSymbols = { "NS1", "NS3", "NS1.NS2", "NS1.T2", "NS1.T3" } Dim not_expected_in_lookupSymbols = { "NS1.NS2.T1" } Dim actual_lookupNames = GetLookupNames(compilation, "a.vb") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb") Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) For Each expectedName In expected_in_lookupNames Assert.Contains(expectedName, actual_lookupNames) Next For Each notExpectedName In not_expected_in_lookupNames Assert.DoesNotContain(notExpectedName, actual_lookupNames) Next For Each expectedName In expected_in_lookupSymbols Assert.Contains(expectedName, actual_lookupSymbols_as_string) Next For Each notExpectedName In not_expected_in_lookupSymbols Assert.DoesNotContain(notExpectedName, actual_lookupSymbols_as_string) Next End Sub <WorkItem(539185, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539185")> <Fact()> Public Sub LookupAtLocationInterfaceBlockSyntax() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Interface Interface1 'BIND:"Interface Interface1" Sub sub1(ByVal i As Integer) End Interface </file> </compilation>) Dim expected_in_lookupNames = { "Interface1", "sub1" } Dim expected_in_lookupSymbols = { "Interface1", "Sub Interface1.sub1(i As System.Int32)" } Dim actual_lookupNames = GetLookupNames(compilation, "a.vb") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb") Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) Assert.Contains(expected_in_lookupNames(0), actual_lookupNames) Assert.Contains(expected_in_lookupNames(1), actual_lookupNames) Assert.Contains(expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) Assert.Contains(expected_in_lookupSymbols(1), actual_lookupSymbols_as_string) End Sub <WorkItem(539185, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539185")> <Fact> Public Sub LookupAtLocationInterfaceStatementSyntax() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Interface Interface1 'BIND:"Interface Interface1" Sub sub1(ByVal i As Integer) End Interface </file> </compilation>) Dim expected_in_lookupNames = { "Interface1", "sub1" } Dim expected_in_lookupSymbols = { "Interface1", "Sub Interface1.sub1(i As System.Int32)" } Dim actual_lookupNames = GetLookupNames(compilation, "a.vb") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb") Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) Assert.Contains(expected_in_lookupNames(0), actual_lookupNames) Assert.Contains(expected_in_lookupNames(1), actual_lookupNames) Assert.Contains(expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) Assert.Contains(expected_in_lookupSymbols(1), actual_lookupSymbols_as_string) End Sub <WorkItem(539185, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539185")> <Fact> Public Sub LookupAtLocationEndInterfaceStatementSyntax() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Interface Interface1 Sub sub1(ByVal i As Integer) End Interface 'BIND:"End Interface" </file> </compilation>) Dim expected_in_lookupNames = { "Interface1", "sub1" } Dim expected_in_lookupSymbols = { "Interface1", "Sub Interface1.sub1(i As System.Int32)" } Dim actual_lookupNames = GetLookupNames(compilation, "a.vb") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb") Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) Assert.Contains(expected_in_lookupNames(0), actual_lookupNames) Assert.Contains(expected_in_lookupNames(1), actual_lookupNames) Assert.Contains(expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) Assert.Contains(expected_in_lookupSymbols(1), actual_lookupSymbols_as_string) End Sub <WorkItem(527774, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527774")> <Fact()> Public Sub LookupAtLocationCompilationUnitSyntax() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Imports A1 = System 'BIND:"Imports A1 = System" </file> </compilation>) Dim expected_in_lookupNames = { "System", "Microsoft" } Dim expected_in_lookupSymbols = { "System", "Microsoft" } Dim actual_lookupNames = GetLookupNames(compilation, "a.vb") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb") Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) Assert.Equal(2, actual_lookupNames.Count) Assert.Equal(2, actual_lookupSymbols_as_string.Count) Assert.Contains(expected_in_lookupNames(0), actual_lookupNames) Assert.Contains(expected_in_lookupNames(1), actual_lookupNames) Assert.Contains(expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) Assert.Contains(expected_in_lookupSymbols(1), actual_lookupSymbols_as_string) End Sub <WorkItem(527779, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527779")> <Fact()> Public Sub LookupAtLocationInheritsStatementSyntax() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Public Class C1 Public Sub C1Sub1() End Sub End Class Public Class C2 Inherits C1 'BIND:"Inherits C1" Public Sub C2Sub1() End Sub End Class </file> </compilation>) Dim expected_in_lookupNames = { "C1", "C2", "C2Sub1" } Dim not_expected_in_lookupNames = { "C1Sub1" } Dim expected_in_lookupSymbols = { "C1", "C2", "Sub C2.C2Sub1()" } Dim not_expected_in_lookupSymbols = { "Sub C1.C1Sub1()" } Dim actual_lookupNames = GetLookupNames(compilation, "a.vb") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb") Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) Assert.Contains(expected_in_lookupNames(0), actual_lookupNames) Assert.Contains(expected_in_lookupNames(1), actual_lookupNames) Assert.Contains(expected_in_lookupNames(2), actual_lookupNames) Assert.DoesNotContain(not_expected_in_lookupNames(0), actual_lookupNames) Assert.Contains(expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) Assert.Contains(expected_in_lookupSymbols(1), actual_lookupSymbols_as_string) Assert.Contains(expected_in_lookupSymbols(2), actual_lookupSymbols_as_string) Assert.DoesNotContain(not_expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) End Sub <WorkItem(527780, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527780")> <Fact()> Public Sub LookupAtLocationImplementsStatementSyntax() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Interface Interface1 Sub Sub1() End Interface Public Class ImplementationClass1 Implements Interface1 'BIND:"Implements Interface1" Sub Sub1() Implements Interface1.Sub1 End Sub Sub Sub2() End Sub End Class </file> </compilation>) Dim expected_in_lookupNames = { "Interface1", "ImplementationClass1", "Sub1", "Sub2" } Dim expected_in_lookupSymbols = { "Interface1", "ImplementationClass1", "Sub ImplementationClass1.Sub1()", "Sub ImplementationClass1.Sub2()" } Dim actual_lookupNames = GetLookupNames(compilation, "a.vb") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb") Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) Assert.Contains(expected_in_lookupNames(0), actual_lookupNames) Assert.Contains(expected_in_lookupNames(1), actual_lookupNames) Assert.Contains(expected_in_lookupNames(2), actual_lookupNames) Assert.Contains(expected_in_lookupNames(3), actual_lookupNames) Assert.Contains(expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) Assert.Contains(expected_in_lookupSymbols(1), actual_lookupSymbols_as_string) Assert.Contains(expected_in_lookupSymbols(2), actual_lookupSymbols_as_string) Assert.Contains(expected_in_lookupSymbols(3), actual_lookupSymbols_as_string) End Sub <WorkItem(539232, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539232")> <Fact()> Public Sub LookupAtLocationInsideIfPartOfSingleLineIfStatement() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Module Program Sub Main() If True Then Dim me1 As Integer = 10 Else Dim me2 As Integer = 20 'BIND:"Dim me1 As Integer = 10" End Sub End Module </file> </compilation>) Dim expected_in_lookupNames = { "me1" } Dim not_expected_in_lookupNames = { "me2" } Dim expected_in_lookupSymbols = { "me1 As System.Int32" } Dim not_expected_in_lookupSymbols = { "me2 As System.Int32" } Dim actual_lookupNames = GetLookupNames(compilation, "a.vb") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb") Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) Assert.Contains(expected_in_lookupNames(0), actual_lookupNames) Assert.DoesNotContain(not_expected_in_lookupNames(0), actual_lookupNames) Assert.Contains(expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) Assert.DoesNotContain(not_expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) End Sub <WorkItem(539234, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539234")> <Fact()> Public Sub LookupAtLocationInsideElsePartOfSingleLineElseStatement() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Module Program Sub Main() If True Then Dim me1 As Integer = 10 Else Dim me2 As Integer = 20 'BIND:"Dim me2 As Integer = 20" End Sub End Module </file> </compilation>) Dim expected_in_lookupNames = { "me2" } Dim not_expected_in_lookupNames = { "me1" } Dim expected_in_lookupSymbols = { "me2 As System.Int32" } Dim not_expected_in_lookupSymbols = { "me1 As System.Int32" } Dim actual_lookupNames = GetLookupNames(compilation, "a.vb") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb") Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) Assert.Contains(expected_in_lookupNames(0), actual_lookupNames) Assert.DoesNotContain(not_expected_in_lookupNames(0), actual_lookupNames) Assert.Contains(expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) Assert.DoesNotContain(not_expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) End Sub <WorkItem(542856, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542856")> <Fact()> Public Sub LookupParamSingleLineLambdaExpr() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Module Program Sub Main(args As String()) Dim x5 = Function(x1) x4 'BIND:" x4" End Sub End Module </file> </compilation>) Dim expected_in_lookupNames = { "x1" } Dim expected_in_lookupSymbols = { "x1 As System.Object" } Dim actual_lookupNames = GetLookupNames(compilation, "a.vb") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb") Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) Assert.Contains(expected_in_lookupNames(0), actual_lookupNames) Assert.Contains(expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) End Sub <Fact()> Public Sub Bug10272_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Module Program Sub Main(args As String()) Dim x5 = Sub(x1) x4 'BIND:" x4" End Sub End Module </file> </compilation>) Dim expected_in_lookupNames = { "x1" } Dim expected_in_lookupSymbols = { "x1 As System.Object" } Dim actual_lookupNames = GetLookupNames(compilation, "a.vb") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb") Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) Assert.Contains(expected_in_lookupNames(0), actual_lookupNames) Assert.Contains(expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) End Sub <Fact(), WorkItem(546400, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546400")> Public Sub Bug10272_3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Module Program Sub Main(args As String()) Dim x5 = Function(x1) x4 'BIND:" x4" End Function End Sub End Module </file> </compilation>) Dim expected_in_lookupNames = { "x1" } Dim expected_in_lookupSymbols = { "x1 As System.Object" } Dim actual_lookupNames = GetLookupNames(compilation, "a.vb") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb") Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) Assert.Contains(expected_in_lookupNames(0), actual_lookupNames) Assert.Contains(expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) End Sub <Fact(), WorkItem(546400, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546400")> Public Sub Bug10272_4() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Module Program Sub Main(args As String()) Dim x5 = Sub(x1) x4 'BIND:" x4" End Sub End Sub End Module </file> </compilation>) Dim expected_in_lookupNames = { "x1" } Dim expected_in_lookupSymbols = { "x1 As System.Object" } Dim actual_lookupNames = GetLookupNames(compilation, "a.vb") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb") Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) Assert.Contains(expected_in_lookupNames(0), actual_lookupNames) Assert.Contains(expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) End Sub <Fact()> Public Sub LookupSymbolsAtEOF() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C End Class </file> </compilation>) Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim eof = tree.GetCompilationUnitRoot().FullSpan.End Assert.NotEqual(eof, 0) Dim symbols = model.LookupSymbols(eof) CompilationUtils.CheckSymbols(symbols, "Microsoft", "C", "System") End Sub <Fact(), WorkItem(939844, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/939844")> Public Sub Bug939844_01() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module Program Sub Main(args As String()) Dim x = 1 If True Then Dim y = 1 x=y 'BIND:"y" End If End Sub End Module </file> </compilation>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim pos As Integer = FindBindingTextPosition(compilation, "a.vb") + 20 Dim symsX = semanticModel.LookupSymbols(pos, Nothing, "x") Assert.Equal(1, symsX.Length) Assert.Equal("x As System.Int32", symsX(0).ToTestDisplayString()) Dim symsY = semanticModel.LookupSymbols(pos, Nothing, "y") Assert.Equal(1, symsY.Length) Assert.Equal("y As System.Int32", symsY(0).ToTestDisplayString()) End Sub <Fact(), WorkItem(939844, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/939844")> Public Sub Bug939844_02() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module Program Sub Main(args As String()) Dim x = 1 Select Case 1 Case 1 Dim y = 1 x=y 'BIND:"y" End Select End Sub End Module </file> </compilation>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim pos As Integer = FindBindingTextPosition(compilation, "a.vb") + 20 Dim symsX = semanticModel.LookupSymbols(pos, Nothing, "x") Assert.Equal(1, symsX.Length) Assert.Equal("x As System.Int32", symsX(0).ToTestDisplayString()) Dim symsY = semanticModel.LookupSymbols(pos, Nothing, "y") Assert.Equal(1, symsY.Length) Assert.Equal("y As System.Int32", symsY(0).ToTestDisplayString()) End Sub #End Region End Class End Namespace
' 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.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Partial Public Class SemanticModelTests Inherits SemanticModelTestBase #Region "LookupSymbols Function" <Fact()> Public Sub LookupSymbols1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Class B Public f1 as Integer End Class Class D Inherits B Public Sub goo() Console.WriteLine() 'BIND:"WriteLine" End Sub End Class Module M Public f1 As Integer Public f2 As Integer End Module Module M2 Public f1 As Integer Public f2 As Integer End Module </file> </compilation>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim pos As Integer = FindBindingTextPosition(compilation, "a.vb") Dim syms = semanticModel.LookupSymbols(pos, Nothing, "f1") Assert.Equal(1, syms.Length) Assert.Equal("B.f1 As System.Int32", syms(0).ToTestDisplayString()) ' This one is tricky.. M.f2 and M2.f2 are ambiguous at the same ' binding scope, so we get both symbols here. syms = semanticModel.LookupSymbols(pos, Nothing, "f2") Assert.Equal(2, syms.Length) Dim fullNames = From s In syms.AsEnumerable Order By s.ToTestDisplayString() Select s.ToTestDisplayString() Assert.Equal("M.f2 As System.Int32", fullNames(0)) Assert.Equal("M2.f2 As System.Int32", fullNames(1)) syms = semanticModel.LookupSymbols(pos, Nothing, "int32") Assert.Equal(1, syms.Length) Assert.Equal("System.Int32", syms(0).ToTestDisplayString()) CompilationUtils.AssertNoErrors(compilation) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:="https://github.com/dotnet/roslyn/issues/29531")> Public Sub LookupSymbols2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System Class B End Class Class A Class B(Of X) End Class Class B(Of X, Y) End Class Sub M() Dim B As Integer Console.WriteLine() End Sub End Class </file> </compilation>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim posInside As Integer = CompilationUtils.FindPositionFromText(tree, "WriteLine") Dim posOutside As Integer = CompilationUtils.FindPositionFromText(tree, "Sub M") ' Inside the method, "B" shadows classes of any arity. Dim syms = semanticModel.LookupSymbols(posInside, Nothing, "b", Nothing) Assert.Equal(1, syms.Length) Assert.Equal("B As System.Int32", syms(0).ToTestDisplayString()) Assert.Equal(SymbolKind.Local, syms(0).Kind) ' Outside the method, all B's are available. syms = semanticModel.LookupSymbols(posOutside, Nothing, "b", Nothing) Assert.Equal(3, syms.Length) Dim fullNames = syms.Select(Function(x) x.ToTestDisplayString()).OrderBy(StringComparer.Ordinal).ToArray() Assert.Equal("A.B(Of X)", fullNames(0)) Assert.Equal("A.B(Of X, Y)", fullNames(1)) Assert.Equal("B", fullNames(2)) ' Inside the method, all B's are available if only types/namespace are allowed syms = semanticModel.LookupNamespacesAndTypes(posOutside, Nothing, "b") Assert.Equal(3, syms.Length) fullNames = syms.Select(Function(x) x.ToTestDisplayString()).OrderBy(StringComparer.Ordinal).ToArray() Assert.Equal("A.B(Of X)", fullNames(0)) Assert.Equal("A.B(Of X, Y)", fullNames(1)) Assert.Equal("B", fullNames(2)) CompilationUtils.AssertNoErrors(compilation) End Sub <Fact()> Public Sub LookupSymbols3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports AliasZ = B.Z Class A Public Class Z(Of X) End Class Public Class Z(Of X, Y) End Class End Class Class B Inherits A Public Class Z ' in B End Class Public Class Z(Of X) End Class End Class Class C Inherits B Public z As Integer ' in C End Class </file> </compilation>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim posInsideB As Integer = CompilationUtils.FindPositionFromText(tree, "in B") Dim posInsideC As Integer = CompilationUtils.FindPositionFromText(tree, "in C") ' Lookup Z, all arities, inside B Dim syms = semanticModel.LookupSymbols(posInsideB, name:="z") ' Assert.Equal(3, syms.Count) Dim fullNames = From s In syms.AsEnumerable Order By s.ToTestDisplayString() Select s.ToTestDisplayString() Assert.Equal("A.Z(Of X, Y)", fullNames(0)) Assert.Equal("B.Z", fullNames(1)) Assert.Equal("B.Z(Of X)", fullNames(2)) ' Lookup Z, all arities, inside C. Since fields shadow by name in VB, only the field is found. syms = semanticModel.LookupSymbols(posInsideC, name:="z") Assert.Equal(1, syms.Length) Assert.Equal("C.z As System.Int32", syms(0).ToTestDisplayString()) ' Lookup AliasZ, all arities, inside C syms = semanticModel.LookupSymbols(posInsideC, name:="aliasz") Assert.Equal(1, syms.Length) Assert.Equal("AliasZ=B.Z", syms(0).ToTestDisplayString()) ' Lookup AliasZ, all arities, inside C with container syms = semanticModel.LookupSymbols(posInsideC, name:="C") Assert.Equal(1, syms.Length) Assert.Equal("C", syms(0).ToTestDisplayString()) Dim C = DirectCast(syms.Single, NamespaceOrTypeSymbol) syms = semanticModel.LookupSymbols(posInsideC, name:="aliasz", container:=C) Assert.Equal(0, syms.Length) CompilationUtils.AssertNoErrors(compilation) End Sub <Fact()> Public Sub LookupSymbols4() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Namespace N1.N2 Class A Public X As Integer End Class Class B Inherits A Public Y As Integer End Class Class C Inherits B Public Z As Integer Public Sub M() System.Console.WriteLine() ' in M End Sub End Class End Namespace </file> </compilation>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim posInsideM As Integer = CompilationUtils.FindPositionFromText(tree, "in M") ' Lookup all symbols Dim syms = From s In semanticModel.LookupSymbols(posInsideM, name:=Nothing) Dim fullNames = From s In syms Order By s.ToTestDisplayString() Select s.ToTestDisplayString() Assert.Contains("N1.N2.A", fullNames) Assert.Contains("N1.N2.B", fullNames) Assert.Contains("N1.N2.C", fullNames) Assert.Contains("N1.N2.C.Z As System.Int32", fullNames) Assert.Contains("Sub N1.N2.C.M()", fullNames) Assert.Contains("N1", fullNames) Assert.Contains("N1.N2", fullNames) Assert.Contains("System", fullNames) Assert.Contains("Microsoft", fullNames) Assert.Contains("Function System.Object.ToString() As System.String", fullNames) CompilationUtils.AssertNoErrors(compilation) End Sub <Fact()> Public Sub LookupSymbolsMustNotBeInstance() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class A Public X As Integer Public Shared SX As Integer End Class Class B Inherits A Public Function Y() As Integer End Function Public Shared Function SY() As Integer End Function End Class Class C Inherits B Public Z As Integer ' in C End Class </file> </compilation>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim classC As NamedTypeSymbol = DirectCast(compilation.GlobalNamespace().GetMembers("C").Single(), NamedTypeSymbol) Dim posInsideC As Integer = CompilationUtils.FindPositionFromText(tree, "in C") Dim symbols = semanticModel.LookupStaticMembers(position:=posInsideC, container:=classC, name:=Nothing) Dim fullNames = From s In symbols.AsEnumerable Order By s.ToTestDisplayString() Select s.ToTestDisplayString() Assert.Equal(4, symbols.Length) Assert.Equal("A.SX As System.Int32", fullNames(0)) Assert.Equal("Function B.SY() As System.Int32", fullNames(1)) Assert.Equal("Function System.Object.Equals(objA As System.Object, objB As System.Object) As System.Boolean", fullNames(2)) Assert.Equal("Function System.Object.ReferenceEquals(objA As System.Object, objB As System.Object) As System.Boolean", fullNames(3)) CompilationUtils.AssertNoErrors(compilation) End Sub <Fact()> Public Sub LookupSymbolsInTypeParameter() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="a.vb"><![CDATA[ Imports System.Runtime.CompilerServices Interface IA Sub MA() End Interface Interface IB Sub MB() End Interface Interface IC Sub M(Of T, U)() End Interface Class C Implements IA Private Sub MA() Implements IA.MA End Sub Public Sub M(Of T)() End Sub End Class Class D(Of T As IB) Public Sub MD(Of U As {C, T, IC}, V As Structure)(_u As U, _v As V) End Sub End Class Module E <Extension()> Friend Sub [ME](c As IC, o As Object) End Sub <Extension()> Friend Sub [ME](v As System.ValueType) End Sub End Module ]]></file> </compilation>, {TestMetadata.Net40.SystemCore}) Dim tree = compilation.SyntaxTrees.Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim method = compilation.GlobalNamespace().GetMember(Of NamedTypeSymbol)("D").GetMember(Of MethodSymbol)("MD") Dim parameter = method.Parameters(0) Dim position = CompilationUtils.FindPositionFromText(tree, "As U") Dim symbols = semanticModel.LookupSymbols(position, container:=parameter.Type, includeReducedExtensionMethods:=True) CheckSymbols(symbols, "Sub C.M(Of T)()", "Function Object.ToString() As String", "Function Object.Equals(obj As Object) As Boolean", "Function Object.Equals(objA As Object, objB As Object) As Boolean", "Function Object.ReferenceEquals(objA As Object, objB As Object) As Boolean", "Function Object.GetHashCode() As Integer", "Function Object.GetType() As Type", "Sub IB.MB()", "Sub IC.ME(o As Object)") parameter = method.Parameters(1) position = CompilationUtils.FindPositionFromText(tree, "As V") symbols = semanticModel.LookupSymbols(position, container:=parameter.Type, includeReducedExtensionMethods:=True) CheckSymbols(symbols, "Function ValueType.Equals(obj As Object) As Boolean", "Function Object.Equals(obj As Object) As Boolean", "Function Object.Equals(objA As Object, objB As Object) As Boolean", "Function ValueType.GetHashCode() As Integer", "Function Object.GetHashCode() As Integer", "Function ValueType.ToString() As String", "Function Object.ToString() As String", "Function Object.ReferenceEquals(objA As Object, objB As Object) As Boolean", "Function Object.GetType() As Type", "Sub ValueType.ME()") CompilationUtils.AssertNoErrors(compilation) End Sub Private Shared Sub CheckSymbols(symbols As ImmutableArray(Of ISymbol), ParamArray descriptions As String()) CompilationUtils.CheckSymbols(symbols, descriptions) End Sub <Fact()> Public Sub LookupNames1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Namespace N1.N2 Class A Public X As Integer End Class Class B Inherits A Public Y As Integer End Class Class C Inherits B Public Z As Integer Public Sub M() System.Console.WriteLine() ' in M End Sub End Class End Namespace </file> </compilation>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim posInsideM As Integer = CompilationUtils.FindPositionFromText(tree, "in M") ' Lookup names Dim names As IEnumerable(Of String) = From n In semanticModel.LookupNames(posInsideM) Order By n Assert.Contains("A", names) Assert.Contains("B", names) Assert.Contains("C", names) Assert.Contains("Z", names) Assert.Contains("M", names) Assert.Contains("N1", names) Assert.Contains("N2", names) Assert.Contains("System", names) Assert.Contains("Microsoft", names) Assert.Contains("ToString", names) Assert.Contains("Equals", names) Assert.Contains("GetType", names) ' Lookup names, namespace and types only names = From n In semanticModel.LookupNames(posInsideM, namespacesAndTypesOnly:=True) Order By n Assert.Contains("A", names) Assert.Contains("B", names) Assert.Contains("C", names) Assert.DoesNotContain("Z", names) Assert.DoesNotContain("M", names) Assert.Contains("N1", names) Assert.Contains("N2", names) Assert.Contains("System", names) Assert.Contains("Microsoft", names) Assert.DoesNotContain("ToString", names) Assert.DoesNotContain("Equals", names) Assert.DoesNotContain("GetType", names) CompilationUtils.AssertNoErrors(compilation) End Sub <Fact()> Public Sub LookupNames2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class A Inherits B Public X As Integer End Class Class B Inherits A Public Y As Integer ' in B End Class </file> </compilation>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim posInsideB As Integer = CompilationUtils.FindPositionFromText(tree, "in B") CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30257: Class 'A' cannot inherit from itself: 'A' inherits from 'B'. 'B' inherits from 'A'. Inherits B ~ </expected>) ' Lookup names Dim names As IEnumerable(Of String) = From n In semanticModel.LookupNames(posInsideB) Order By n Assert.Contains("A", names) Assert.Contains("B", names) Assert.Contains("X", names) Assert.Contains("Y", names) End Sub <Fact()> Public Sub ObjectMembersOnInterfaces1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ObjectMembersOnInterfaces"> <file name="a.vb"> Module Module1 Sub Main() System.Console.WriteLine(System.IDisposable.Equals(1, 1)) Dim x As I1 = New C1() System.Console.WriteLine(x.GetHashCode()) 'BIND:"GetHashCode" End Sub End Module Interface I1 End Interface Class C1 Implements I1 Public Overrides Function GetHashCode() As Integer Return 1234 End Function End Class </file> </compilation>, TestOptions.ReleaseExe) CompileAndVerify(compilation, <![CDATA[ True 1234 ]]>) Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", container:=compilation.GetTypeByMetadataName("I1"), name:="GetHashCode") Assert.Equal(1, actual_lookupSymbols.Count) Assert.Equal("Function System.Object.GetHashCode() As System.Int32", actual_lookupSymbols(0).ToTestDisplayString()) Dim getHashCode = DirectCast(actual_lookupSymbols(0), MethodSymbol) Assert.Contains(getHashCode, GetLookupSymbols(compilation, "a.vb", container:=compilation.GetTypeByMetadataName("I1"))) End Sub <Fact()> Public Sub ObjectMembersOnInterfaces2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ObjectMembersOnInterfaces"> <file name="a.vb"> Imports System.Runtime.CompilerServices Module Module1 Sub Main() Dim x As I1 = Nothing x.GetHashCode() x.GetHashCode(1) x.ToString() x.ToString(1) x.ToString(1, 2) Dim y As I5 = Nothing y.GetHashCode() End Sub &lt;Extension()&gt; Function ToString(this As I1, x As Integer, y As Integer) As String Return Nothing End Function End Module Interface I1 Function GetHashCode(x As Integer) As Integer Function ToString(x As Integer) As Integer End Interface Interface I3 Function GetHashCode(x As Integer) As Integer End Interface Interface I4 Function GetHashCode() As Integer End Interface Interface I5 Inherits I3, I4 End Interface Namespace System.Runtime.CompilerServices &lt;AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)&gt; Class ExtensionAttribute Inherits Attribute End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <result> BC30455: Argument not specified for parameter 'x' of 'Function GetHashCode(x As Integer) As Integer'. x.GetHashCode() ~~~~~~~~~~~ BC30516: Overload resolution failed because no accessible 'ToString' accepts this number of arguments. x.ToString() ~~~~~~~~ </result> ) End Sub <Fact()> Public Sub LookupOfConstructorMemberOnMe() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="LookupOfConstructorMember"> <file name="a.vb"> Class B1 Public Sub New(x As Integer) End Sub Private Sub New(x as String) End Sub End Class Class C1 Inherits B1 Public Sub New(x As Integer, y as Integer) Me.New() 'BIND:"New" End Sub Private Sub New(x as String, y as Integer) End Sub End Class </file> </compilation>) Dim expected_in_lookupSymbols = { "Function System.Object.ToString() As System.String", "Function System.Object.Equals(obj As System.Object) As System.Boolean", "Function System.Object.Equals(objA As System.Object, objB As System.Object) As System.Boolean", "Function System.Object.ReferenceEquals(objA As System.Object, objB As System.Object) As System.Boolean", "Function System.Object.GetHashCode() As System.Int32", "Function System.Object.GetType() As System.Type", "Sub System.Object.Finalize()", "Function System.Object.MemberwiseClone() As System.Object", "Sub C1..ctor(x As System.Int32, y As System.Int32)", "Sub C1..ctor(x As System.String, y As System.Int32)" } Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", container:=compilation.GetTypeByMetadataName("C1"), name:=Nothing) Dim actual_lookupSymbols_strings = actual_lookupSymbols.Select(Function(s) s.ToTestDisplayString()).ToList() For Each s In expected_in_lookupSymbols Assert.Contains(s, actual_lookupSymbols_strings) Next Assert.Equal(expected_in_lookupSymbols.Count, actual_lookupSymbols_strings.Count) End Sub <Fact()> Public Sub LookupOfConstructorMemberOnMyClass() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="LookupOfConstructorMemberOnMyClass"> <file name="a.vb"> Class B1 Public Sub New(x As Integer) End Sub Private Sub New(x as String) End Sub End Class Class C1 Inherits B1 Public Sub New(x As Integer, y as Integer) MyClass.New() 'BIND:"New" End Sub Private Sub New(x as String, y as Integer) End Sub End Class </file> </compilation>) Dim expected_in_lookupSymbols = { "Function System.Object.ToString() As System.String", "Function System.Object.Equals(obj As System.Object) As System.Boolean", "Function System.Object.Equals(objA As System.Object, objB As System.Object) As System.Boolean", "Function System.Object.ReferenceEquals(objA As System.Object, objB As System.Object) As System.Boolean", "Function System.Object.GetHashCode() As System.Int32", "Function System.Object.GetType() As System.Type", "Sub System.Object.Finalize()", "Function System.Object.MemberwiseClone() As System.Object", "Sub C1..ctor(x As System.Int32, y As System.Int32)", "Sub C1..ctor(x As System.String, y As System.Int32)" } Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", container:=compilation.GetTypeByMetadataName("C1"), name:=Nothing) Dim actual_lookupSymbols_strings = actual_lookupSymbols.Select(Function(s) s.ToTestDisplayString()).ToList() For Each s In expected_in_lookupSymbols Assert.Contains(s, actual_lookupSymbols_strings) Next Assert.Equal(expected_in_lookupSymbols.Count, actual_lookupSymbols_strings.Count) End Sub <Fact()> Public Sub LookupOfConstructorMemberOnMeNotInConstructor() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="LookupOfConstructorMemberOnMeNotInConstructor"> <file name="a.vb"> Class B1 Public Sub New(x As Integer) End Sub Private Sub New(x as String) End Sub End Class Class C1 Inherits B1 Public Sub New(x As Integer, y as Integer) End Sub Private Sub New(x as String, y as Integer) End Sub Public Sub q() Me.New() 'BIND:"New" End Sub End Class </file> </compilation>) Dim expected_in_lookupSymbols = { "Function System.Object.ToString() As System.String", "Function System.Object.Equals(obj As System.Object) As System.Boolean", "Function System.Object.Equals(objA As System.Object, objB As System.Object) As System.Boolean", "Function System.Object.ReferenceEquals(objA As System.Object, objB As System.Object) As System.Boolean", "Function System.Object.GetHashCode() As System.Int32", "Function System.Object.GetType() As System.Type", "Sub System.Object.Finalize()", "Function System.Object.MemberwiseClone() As System.Object", "Sub C1.q()" } Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", container:=compilation.GetTypeByMetadataName("C1"), name:=Nothing) Dim actual_lookupSymbols_strings = actual_lookupSymbols.Select(Function(s) s.ToTestDisplayString()).ToList() For Each s In expected_in_lookupSymbols Assert.Contains(s, actual_lookupSymbols_strings) Next Assert.Equal(expected_in_lookupSymbols.Count, actual_lookupSymbols_strings.Count) End Sub <Fact()> Public Sub LookupOfConstructorMemberOnMyClassNotInConstructor() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="LookupOfConstructorMemberOnMyClassNotInConstructor"> <file name="a.vb"> Class B1 Public Sub New(x As Integer) End Sub Private Sub New(x as String) End Sub End Class Class C1 Inherits B1 Public Sub New(x As Integer, y as Integer) End Sub Private Sub New(x as String, y as Integer) End Sub Public Sub q() MyClass.New() 'BIND:"New" End Sub End Class </file> </compilation>) Dim expected_in_lookupSymbols = { "Function System.Object.ToString() As System.String", "Function System.Object.Equals(obj As System.Object) As System.Boolean", "Function System.Object.Equals(objA As System.Object, objB As System.Object) As System.Boolean", "Function System.Object.ReferenceEquals(objA As System.Object, objB As System.Object) As System.Boolean", "Function System.Object.GetHashCode() As System.Int32", "Function System.Object.GetType() As System.Type", "Sub System.Object.Finalize()", "Function System.Object.MemberwiseClone() As System.Object", "Sub C1.q()" } Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", container:=compilation.GetTypeByMetadataName("C1"), name:=Nothing) Dim actual_lookupSymbols_strings = actual_lookupSymbols.Select(Function(s) s.ToTestDisplayString()).ToList() For Each s In expected_in_lookupSymbols Assert.Contains(s, actual_lookupSymbols_strings) Next Assert.Equal(expected_in_lookupSymbols.Count, actual_lookupSymbols_strings.Count) End Sub <Fact()> Public Sub LookupOfConstructorMemberOnMeNoInstance() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="LookupOfConstructorMember"> <file name="a.vb"> Class B1 Public Sub New(x As Integer) End Sub Private Sub New(x as String) End Sub End Class Class C1 Inherits B1 Public Sub New(x As Integer, y as Integer) Me.New() 'BIND:"New" End Sub Private Sub New(x as String, y as Integer) End Sub End Class </file> </compilation>) Dim expected_in_lookupSymbols = { "Function System.Object.Equals(objA As System.Object, objB As System.Object) As System.Boolean", "Function System.Object.ReferenceEquals(objA As System.Object, objB As System.Object) As System.Boolean" } Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", container:=compilation.GetTypeByMetadataName("C1"), name:=Nothing, mustBeStatic:=True) Dim actual_lookupSymbols_strings = actual_lookupSymbols.Select(Function(s) s.ToTestDisplayString()).ToList() For Each s In expected_in_lookupSymbols Assert.Contains(s, actual_lookupSymbols_strings) Next Assert.Equal(expected_in_lookupSymbols.Count, actual_lookupSymbols_strings.Count) End Sub <Fact()> Public Sub LookupOfConstructorMemberOnMyClassNoInstance() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="LookupOfConstructorMemberOnMyClassNoInstance"> <file name="a.vb"> Class B1 Public Sub New(x As Integer) End Sub Private Sub New(x as String) End Sub End Class Class C1 Inherits B1 Public Sub New(x As Integer, y as Integer) MyClass.New() 'BIND:"New" End Sub Private Sub New(x as String, y as Integer) End Sub End Class </file> </compilation>) Dim expected_in_lookupSymbols = { "Function System.Object.Equals(objA As System.Object, objB As System.Object) As System.Boolean", "Function System.Object.ReferenceEquals(objA As System.Object, objB As System.Object) As System.Boolean" } Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", container:=compilation.GetTypeByMetadataName("C1"), name:=Nothing, mustBeStatic:=True) Dim actual_lookupSymbols_strings = actual_lookupSymbols.Select(Function(s) s.ToTestDisplayString()).ToList() For Each s In expected_in_lookupSymbols Assert.Contains(s, actual_lookupSymbols_strings) Next Assert.Equal(expected_in_lookupSymbols.Count, actual_lookupSymbols_strings.Count) End Sub <Fact()> Public Sub LookupOfConstructorMemberOnMyBase() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="LookupOfConstructorMemberOnMyBase"> <file name="a.vb"> Class B1 Public Sub New(x As Integer) End Sub Private Sub New(x as String) End Sub End Class Class C1 Inherits B1 Public Sub New(x As Integer, y as Integer) MyBase.New() 'BIND:"New" End Sub Private Sub New(x as String, y as Integer) End Sub Public Sub C() End Sub End Class </file> </compilation>) Dim expected_in_lookupSymbols = { "Function System.Object.ToString() As System.String", "Function System.Object.Equals(obj As System.Object) As System.Boolean", "Function System.Object.Equals(objA As System.Object, objB As System.Object) As System.Boolean", "Function System.Object.ReferenceEquals(objA As System.Object, objB As System.Object) As System.Boolean", "Function System.Object.GetHashCode() As System.Int32", "Function System.Object.GetType() As System.Type", "Sub B1..ctor(x As System.Int32)" } Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", container:=compilation.GetTypeByMetadataName("B1"), name:=Nothing) Dim actual_lookupSymbols_strings = actual_lookupSymbols.Select(Function(s) s.ToTestDisplayString()).ToList() For Each s In expected_in_lookupSymbols Assert.Contains(s, actual_lookupSymbols_strings) Next Assert.Equal(expected_in_lookupSymbols.Count, actual_lookupSymbols_strings.Count) End Sub <Fact()> Public Sub LookupOfInaccessibleOnMyBase() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="LookupOfConstructorMemberOnMyBase"> <file name="a.vb"> Class B1 Public Sub New(x As Integer) End Sub Private Sub New(x as String) End Sub End Class Class C1 Inherits B1 Public Sub New(x As Integer, y as Integer) MyBase.New() 'BIND:"New" End Sub Private Sub New(x as String, y as Integer) End Sub End Class </file> </compilation>) Dim expected_in_lookupSymbols = { "Function System.Object.ToString() As System.String", "Function System.Object.Equals(obj As System.Object) As System.Boolean", "Function System.Object.Equals(objA As System.Object, objB As System.Object) As System.Boolean", "Function System.Object.ReferenceEquals(objA As System.Object, objB As System.Object) As System.Boolean", "Function System.Object.GetHashCode() As System.Int32", "Function System.Object.GetType() As System.Type", "Sub System.Object.Finalize()", "Function System.Object.MemberwiseClone() As System.Object", "Sub B1..ctor(x As System.Int32)", "Sub B1..ctor(x As System.String)" } Dim tree = compilation.SyntaxTrees.Single() Dim model = compilation.GetSemanticModel(tree) Dim position = tree.ToString().IndexOf("MyBase", StringComparison.Ordinal) Dim binder = DirectCast(model, VBSemanticModel).GetEnclosingBinder(position) Dim baseType = compilation.GlobalNamespace.GetMember(Of NamedTypeSymbol)("B1") Dim useSiteDiagnostics As HashSet(Of DiagnosticInfo) = Nothing Dim result = LookupResult.GetInstance() binder.LookupMember(result, baseType, "Finalize", 0, LookupOptions.IgnoreAccessibility, useSiteDiagnostics) Assert.Null(useSiteDiagnostics) Assert.True(result.IsGood) Assert.Equal("Sub System.Object.Finalize()", result.SingleSymbol.ToTestDisplayString()) result.Clear() binder.LookupMember(result, baseType, "MemberwiseClone", 0, LookupOptions.IgnoreAccessibility, useSiteDiagnostics) Assert.Null(useSiteDiagnostics) Assert.True(result.IsGood) Assert.Equal("Function System.Object.MemberwiseClone() As System.Object", result.SingleSymbol.ToTestDisplayString()) result.Free() End Sub #End Region #Region "Regression" <WorkItem(539107, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539107")> <Fact()> Public Sub LookupAtLocationEndSubNode() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Class Test Public Sub Method1(ByVal param1 As Integer) Dim count As Integer = 45 End Sub 'BIND:"End Sub" End Class </file> </compilation>) Dim expected_in_lookupNames = { "count", "param1" } Dim expected_in_lookupSymbols = { "count As System.Int32", "param1 As System.Int32" } Dim actual_lookupNames = GetLookupNames(compilation, "a.vb") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb") Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) Assert.Contains(expected_in_lookupNames(0), actual_lookupNames) Assert.Contains(expected_in_lookupNames(1), actual_lookupNames) Assert.Contains(expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) Assert.Contains(expected_in_lookupSymbols(1), actual_lookupSymbols_as_string) End Sub <WorkItem(539114, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539114")> <Fact()> Public Sub LookupAtLocationSubBlockNode() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Class Test Public Sub Method1(ByVal param1 As Integer) 'BIND:"Public Sub Method1(ByVal param1 As Integer)" Dim count As Integer = 45 End Sub End Class </file> </compilation>) Dim not_expected_in_lookupNames = { "count", "param1" } Dim not_expected_in_lookupSymbols = { "count As System.Int32", "param1 As System.Int32" } Dim actual_lookupNames = GetLookupNames(compilation, "a.vb") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb") Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) Assert.DoesNotContain(not_expected_in_lookupNames(0), actual_lookupNames) Assert.DoesNotContain(not_expected_in_lookupNames(1), actual_lookupNames) Assert.DoesNotContain(not_expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) Assert.DoesNotContain(not_expected_in_lookupSymbols(1), actual_lookupSymbols_as_string) End Sub <WorkItem(539119, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539119")> <Fact()> Public Sub LookupSymbolsByNameIncorrectArity() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Class Test Public Sub Method1(ByVal param1 As Integer) Dim count As Integer = 45 'BIND:"45" End Sub End Class </file> </compilation>) Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="count", arity:=1) Assert.Empty(actual_lookupSymbols) End Sub <WorkItem(539130, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539130")> <Fact()> Public Sub LookupWithNameZeroArity() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Module Module1 Sub Method1(Of T)(i As T) End Sub Sub Method1(Of T, U)(i As T, j As U) End Sub Sub Method1(i As Integer) End Sub Sub Method1(i As Integer, j As Integer) End Sub Public Sub Main() Dim x As Integer = 45 'BIND:"45" End Sub End Module </file> </compilation>) Dim expected_in_lookupSymbols = { "Sub Module1.Method1(i As System.Int32)", "Sub Module1.Method1(i As System.Int32, j As System.Int32)" } Dim not_expected_in_lookupSymbols = { "Sub Module1.Method1(Of T)(i As T)", "Sub Module1.Method1(Of T, U)(i As T, j As U)" } Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="Method1", arity:=0) Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) Assert.Contains(expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) Assert.Contains(expected_in_lookupSymbols(1), actual_lookupSymbols_as_string) Assert.DoesNotContain(not_expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) Assert.DoesNotContain(not_expected_in_lookupSymbols(1), actual_lookupSymbols_as_string) End Sub <WorkItem(5004, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub LookupExcludeInAppropriateNS() Dim compilation = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation name="GetSemanticInfo"> <file name="a.vb"> Module Module1 End Module </file> </compilation>, {SystemDataRef}) Dim not_expected_in_lookup = { "<CrtImplementationDetails>", "<CppImplementationDetails>" } Dim tree = compilation.SyntaxTrees.Single() Dim model = compilation.GetSemanticModel(tree) Const position = 0 Dim binder = DirectCast(model, VBSemanticModel).GetEnclosingBinder(position) Dim actual_lookupSymbols = model.LookupSymbols(position) Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) Assert.DoesNotContain(not_expected_in_lookup(0), actual_lookupSymbols_as_string) Assert.DoesNotContain(not_expected_in_lookup(1), actual_lookupSymbols_as_string) End Sub <WorkItem(539166, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539166")> <Fact()> Public Sub LookupLocationInsideFunctionIgnoreReturnVariable() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Class Test Function Func1() As Integer Dim x As Integer = "10" Return 10 End Function End Class </file> </compilation>) Dim tree = compilation.SyntaxTrees.Single() Dim model = compilation.GetSemanticModel(tree) Dim position = tree.ToString().IndexOf("Dim", StringComparison.Ordinal) Dim binder = DirectCast(model, VBSemanticModel).GetEnclosingBinder(position) Dim result = LookupResult.GetInstance() Dim useSiteDiagnostics As HashSet(Of DiagnosticInfo) = Nothing binder.Lookup(result, "Func1", arity:=0, options:=LookupOptions.MustNotBeReturnValueVariable, useSiteDiagnostics:=useSiteDiagnostics) Assert.Null(useSiteDiagnostics) Assert.True(result.IsGood) Assert.Equal("Function Test.Func1() As System.Int32", result.SingleSymbol.ToTestDisplayString()) result.Clear() binder.Lookup(result, "x", arity:=0, options:=LookupOptions.MustNotBeReturnValueVariable, useSiteDiagnostics:=useSiteDiagnostics) Assert.Null(useSiteDiagnostics) Assert.True(result.IsGood) Assert.Equal("x As System.Int32", result.SingleSymbol.ToTestDisplayString()) result.Free() End Sub <WorkItem(539166, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539166")> <Fact()> Public Sub LookupLocationInsideFunction() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Class Test Function Func1() As Integer Dim x As Integer = "10" 'BIND:"10" Return 10 End Function End Class </file> </compilation>) Dim expected_in_lookupNames = { "Func1", "x" } Dim expected_in_lookupSymbols = { "Func1 As System.Int32", "x As System.Int32" } Dim actual_lookupNames = GetLookupNames(compilation, "a.vb") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb") Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) Assert.Contains(expected_in_lookupNames(0), actual_lookupNames) Assert.Contains(expected_in_lookupNames(1), actual_lookupNames) Assert.Contains(expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) Assert.Contains(expected_in_lookupSymbols(1), actual_lookupSymbols_as_string) End Sub <WorkItem(527759, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527759")> <Fact()> Public Sub LookupAtLocationClassTypeBlockSyntax() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Class Test 'BIND:"Class Test" Public Sub PublicMethod() End Sub Protected Sub ProtectedMethod() End Sub Private Sub PrivateMethod() End Sub End Class </file> </compilation>) Dim expected_in_lookupNames = { "PublicMethod", "ProtectedMethod", "PrivateMethod" } Dim expected_in_lookupSymbols = { "Sub Test.PublicMethod()", "Sub Test.ProtectedMethod()", "Sub Test.PrivateMethod()" } Dim actual_lookupNames = GetLookupNames(compilation, "a.vb") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb") Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) Assert.Contains(expected_in_lookupNames(0), actual_lookupNames) Assert.Contains(expected_in_lookupNames(1), actual_lookupNames) Assert.Contains(expected_in_lookupNames(2), actual_lookupNames) Assert.Contains(expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) Assert.Contains(expected_in_lookupSymbols(1), actual_lookupSymbols_as_string) Assert.Contains(expected_in_lookupSymbols(2), actual_lookupSymbols_as_string) End Sub <WorkItem(527760, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527760")> <Fact()> Public Sub LookupAtLocationClassTypeStatementSyntax() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Class Test 'BIND:"Class Test" Public Sub PublicMethod() End Sub Protected Sub ProtectedMethod() End Sub Private Sub PrivateMethod() End Sub End Class </file> </compilation>) Dim expected_in_lookupNames = { "PublicMethod", "ProtectedMethod", "PrivateMethod" } Dim expected_in_lookupSymbols = { "Sub Test.PublicMethod()", "Sub Test.ProtectedMethod()", "Sub Test.PrivateMethod()" } Dim actual_lookupNames = GetLookupNames(compilation, "a.vb") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb") Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) Assert.Contains(expected_in_lookupNames(0), actual_lookupNames) Assert.Contains(expected_in_lookupNames(1), actual_lookupNames) Assert.Contains(expected_in_lookupNames(2), actual_lookupNames) Assert.Contains(expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) Assert.Contains(expected_in_lookupSymbols(1), actual_lookupSymbols_as_string) Assert.Contains(expected_in_lookupSymbols(2), actual_lookupSymbols_as_string) End Sub <WorkItem(527761, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527761")> <Fact()> Public Sub LookupAtLocationEndClassStatementSyntax() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Class Test Public Sub PublicMethod() End Sub Protected Sub ProtectedMethod() End Sub Private Sub PrivateMethod() End Sub End Class 'BIND:"End Class" </file> </compilation>) Dim expected_in_lookupNames = { "PublicMethod", "ProtectedMethod", "PrivateMethod" } Dim expected_in_lookupSymbols = { "Sub Test.PublicMethod()", "Sub Test.ProtectedMethod()", "Sub Test.PrivateMethod()" } Dim actual_lookupNames = GetLookupNames(compilation, "a.vb") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb") Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) Assert.Contains(expected_in_lookupNames(0), actual_lookupNames) Assert.Contains(expected_in_lookupNames(1), actual_lookupNames) Assert.Contains(expected_in_lookupNames(2), actual_lookupNames) Assert.Contains(expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) Assert.Contains(expected_in_lookupSymbols(1), actual_lookupSymbols_as_string) Assert.Contains(expected_in_lookupSymbols(2), actual_lookupSymbols_as_string) End Sub <WorkItem(539175, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539175")> <Fact()> Public Sub LookupAtLocationNamespaceBlockSyntax() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Namespace NS1 'BIND:"Namespace NS1" Namespace NS2 Class T1 End Class End Namespace Class T2 End Class Friend Class T3 End Class End Namespace Namespace NS3 End Namespace </file> </compilation>) Dim expected_in_lookupNames = { "NS1", "NS3" } Dim not_expected_in_lookupNames = { "NS2", "T1", "T2", "T3" } Dim expected_in_lookupSymbols = { "NS1", "NS3" } Dim not_expected_in_lookupSymbols = { "NS1.NS2", "NS1.NS2.T1", "NS1.T2", "NS1.T3" } Dim actual_lookupNames = GetLookupNames(compilation, "a.vb") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb") Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) Assert.Contains(expected_in_lookupNames(0), actual_lookupNames) Assert.Contains(expected_in_lookupNames(1), actual_lookupNames) Assert.DoesNotContain(not_expected_in_lookupNames(0), actual_lookupNames) Assert.DoesNotContain(not_expected_in_lookupNames(1), actual_lookupNames) Assert.DoesNotContain(not_expected_in_lookupNames(2), actual_lookupNames) Assert.DoesNotContain(not_expected_in_lookupNames(3), actual_lookupNames) Assert.Contains(expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) Assert.Contains(expected_in_lookupSymbols(1), actual_lookupSymbols_as_string) Assert.DoesNotContain(not_expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) Assert.DoesNotContain(not_expected_in_lookupSymbols(1), actual_lookupSymbols_as_string) Assert.DoesNotContain(not_expected_in_lookupSymbols(2), actual_lookupSymbols_as_string) Assert.DoesNotContain(not_expected_in_lookupSymbols(3), actual_lookupSymbols_as_string) End Sub <WorkItem(539177, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539177")> <Fact()> Public Sub LookupAtLocationEndNamespaceStatementSyntax() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Namespace NS1 Namespace NS2 Class T1 End Class End Namespace Class T2 End Class Friend Class T3 End Class End Namespace 'BIND:"End Namespace" Namespace NS3 End Namespace </file> </compilation>) Dim expected_in_lookupNames = { "NS1", "NS2", "NS3", "T2", "T3" } Dim not_expected_in_lookupNames = { "T1" } Dim expected_in_lookupSymbols = { "NS1", "NS3", "NS1.NS2", "NS1.T2", "NS1.T3" } Dim not_expected_in_lookupSymbols = { "NS1.NS2.T1" } Dim actual_lookupNames = GetLookupNames(compilation, "a.vb") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb") Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) For Each expectedName In expected_in_lookupNames Assert.Contains(expectedName, actual_lookupNames) Next For Each notExpectedName In not_expected_in_lookupNames Assert.DoesNotContain(notExpectedName, actual_lookupNames) Next For Each expectedName In expected_in_lookupSymbols Assert.Contains(expectedName, actual_lookupSymbols_as_string) Next For Each notExpectedName In not_expected_in_lookupSymbols Assert.DoesNotContain(notExpectedName, actual_lookupSymbols_as_string) Next End Sub <WorkItem(539185, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539185")> <Fact()> Public Sub LookupAtLocationInterfaceBlockSyntax() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Interface Interface1 'BIND:"Interface Interface1" Sub sub1(ByVal i As Integer) End Interface </file> </compilation>) Dim expected_in_lookupNames = { "Interface1", "sub1" } Dim expected_in_lookupSymbols = { "Interface1", "Sub Interface1.sub1(i As System.Int32)" } Dim actual_lookupNames = GetLookupNames(compilation, "a.vb") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb") Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) Assert.Contains(expected_in_lookupNames(0), actual_lookupNames) Assert.Contains(expected_in_lookupNames(1), actual_lookupNames) Assert.Contains(expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) Assert.Contains(expected_in_lookupSymbols(1), actual_lookupSymbols_as_string) End Sub <WorkItem(539185, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539185")> <Fact> Public Sub LookupAtLocationInterfaceStatementSyntax() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Interface Interface1 'BIND:"Interface Interface1" Sub sub1(ByVal i As Integer) End Interface </file> </compilation>) Dim expected_in_lookupNames = { "Interface1", "sub1" } Dim expected_in_lookupSymbols = { "Interface1", "Sub Interface1.sub1(i As System.Int32)" } Dim actual_lookupNames = GetLookupNames(compilation, "a.vb") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb") Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) Assert.Contains(expected_in_lookupNames(0), actual_lookupNames) Assert.Contains(expected_in_lookupNames(1), actual_lookupNames) Assert.Contains(expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) Assert.Contains(expected_in_lookupSymbols(1), actual_lookupSymbols_as_string) End Sub <WorkItem(539185, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539185")> <Fact> Public Sub LookupAtLocationEndInterfaceStatementSyntax() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Interface Interface1 Sub sub1(ByVal i As Integer) End Interface 'BIND:"End Interface" </file> </compilation>) Dim expected_in_lookupNames = { "Interface1", "sub1" } Dim expected_in_lookupSymbols = { "Interface1", "Sub Interface1.sub1(i As System.Int32)" } Dim actual_lookupNames = GetLookupNames(compilation, "a.vb") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb") Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) Assert.Contains(expected_in_lookupNames(0), actual_lookupNames) Assert.Contains(expected_in_lookupNames(1), actual_lookupNames) Assert.Contains(expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) Assert.Contains(expected_in_lookupSymbols(1), actual_lookupSymbols_as_string) End Sub <WorkItem(527774, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527774")> <Fact()> Public Sub LookupAtLocationCompilationUnitSyntax() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Imports A1 = System 'BIND:"Imports A1 = System" </file> </compilation>) Dim expected_in_lookupNames = { "System", "Microsoft" } Dim expected_in_lookupSymbols = { "System", "Microsoft" } Dim actual_lookupNames = GetLookupNames(compilation, "a.vb") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb") Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) Assert.Equal(2, actual_lookupNames.Count) Assert.Equal(2, actual_lookupSymbols_as_string.Count) Assert.Contains(expected_in_lookupNames(0), actual_lookupNames) Assert.Contains(expected_in_lookupNames(1), actual_lookupNames) Assert.Contains(expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) Assert.Contains(expected_in_lookupSymbols(1), actual_lookupSymbols_as_string) End Sub <WorkItem(527779, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527779")> <Fact()> Public Sub LookupAtLocationInheritsStatementSyntax() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Public Class C1 Public Sub C1Sub1() End Sub End Class Public Class C2 Inherits C1 'BIND:"Inherits C1" Public Sub C2Sub1() End Sub End Class </file> </compilation>) Dim expected_in_lookupNames = { "C1", "C2", "C2Sub1" } Dim not_expected_in_lookupNames = { "C1Sub1" } Dim expected_in_lookupSymbols = { "C1", "C2", "Sub C2.C2Sub1()" } Dim not_expected_in_lookupSymbols = { "Sub C1.C1Sub1()" } Dim actual_lookupNames = GetLookupNames(compilation, "a.vb") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb") Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) Assert.Contains(expected_in_lookupNames(0), actual_lookupNames) Assert.Contains(expected_in_lookupNames(1), actual_lookupNames) Assert.Contains(expected_in_lookupNames(2), actual_lookupNames) Assert.DoesNotContain(not_expected_in_lookupNames(0), actual_lookupNames) Assert.Contains(expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) Assert.Contains(expected_in_lookupSymbols(1), actual_lookupSymbols_as_string) Assert.Contains(expected_in_lookupSymbols(2), actual_lookupSymbols_as_string) Assert.DoesNotContain(not_expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) End Sub <WorkItem(527780, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527780")> <Fact()> Public Sub LookupAtLocationImplementsStatementSyntax() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Interface Interface1 Sub Sub1() End Interface Public Class ImplementationClass1 Implements Interface1 'BIND:"Implements Interface1" Sub Sub1() Implements Interface1.Sub1 End Sub Sub Sub2() End Sub End Class </file> </compilation>) Dim expected_in_lookupNames = { "Interface1", "ImplementationClass1", "Sub1", "Sub2" } Dim expected_in_lookupSymbols = { "Interface1", "ImplementationClass1", "Sub ImplementationClass1.Sub1()", "Sub ImplementationClass1.Sub2()" } Dim actual_lookupNames = GetLookupNames(compilation, "a.vb") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb") Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) Assert.Contains(expected_in_lookupNames(0), actual_lookupNames) Assert.Contains(expected_in_lookupNames(1), actual_lookupNames) Assert.Contains(expected_in_lookupNames(2), actual_lookupNames) Assert.Contains(expected_in_lookupNames(3), actual_lookupNames) Assert.Contains(expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) Assert.Contains(expected_in_lookupSymbols(1), actual_lookupSymbols_as_string) Assert.Contains(expected_in_lookupSymbols(2), actual_lookupSymbols_as_string) Assert.Contains(expected_in_lookupSymbols(3), actual_lookupSymbols_as_string) End Sub <WorkItem(539232, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539232")> <Fact()> Public Sub LookupAtLocationInsideIfPartOfSingleLineIfStatement() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Module Program Sub Main() If True Then Dim me1 As Integer = 10 Else Dim me2 As Integer = 20 'BIND:"Dim me1 As Integer = 10" End Sub End Module </file> </compilation>) Dim expected_in_lookupNames = { "me1" } Dim not_expected_in_lookupNames = { "me2" } Dim expected_in_lookupSymbols = { "me1 As System.Int32" } Dim not_expected_in_lookupSymbols = { "me2 As System.Int32" } Dim actual_lookupNames = GetLookupNames(compilation, "a.vb") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb") Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) Assert.Contains(expected_in_lookupNames(0), actual_lookupNames) Assert.DoesNotContain(not_expected_in_lookupNames(0), actual_lookupNames) Assert.Contains(expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) Assert.DoesNotContain(not_expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) End Sub <WorkItem(539234, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539234")> <Fact()> Public Sub LookupAtLocationInsideElsePartOfSingleLineElseStatement() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Module Program Sub Main() If True Then Dim me1 As Integer = 10 Else Dim me2 As Integer = 20 'BIND:"Dim me2 As Integer = 20" End Sub End Module </file> </compilation>) Dim expected_in_lookupNames = { "me2" } Dim not_expected_in_lookupNames = { "me1" } Dim expected_in_lookupSymbols = { "me2 As System.Int32" } Dim not_expected_in_lookupSymbols = { "me1 As System.Int32" } Dim actual_lookupNames = GetLookupNames(compilation, "a.vb") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb") Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) Assert.Contains(expected_in_lookupNames(0), actual_lookupNames) Assert.DoesNotContain(not_expected_in_lookupNames(0), actual_lookupNames) Assert.Contains(expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) Assert.DoesNotContain(not_expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) End Sub <WorkItem(542856, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542856")> <Fact()> Public Sub LookupParamSingleLineLambdaExpr() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Module Program Sub Main(args As String()) Dim x5 = Function(x1) x4 'BIND:" x4" End Sub End Module </file> </compilation>) Dim expected_in_lookupNames = { "x1" } Dim expected_in_lookupSymbols = { "x1 As System.Object" } Dim actual_lookupNames = GetLookupNames(compilation, "a.vb") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb") Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) Assert.Contains(expected_in_lookupNames(0), actual_lookupNames) Assert.Contains(expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) End Sub <Fact()> Public Sub Bug10272_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Module Program Sub Main(args As String()) Dim x5 = Sub(x1) x4 'BIND:" x4" End Sub End Module </file> </compilation>) Dim expected_in_lookupNames = { "x1" } Dim expected_in_lookupSymbols = { "x1 As System.Object" } Dim actual_lookupNames = GetLookupNames(compilation, "a.vb") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb") Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) Assert.Contains(expected_in_lookupNames(0), actual_lookupNames) Assert.Contains(expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) End Sub <Fact(), WorkItem(546400, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546400")> Public Sub Bug10272_3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Module Program Sub Main(args As String()) Dim x5 = Function(x1) x4 'BIND:" x4" End Function End Sub End Module </file> </compilation>) Dim expected_in_lookupNames = { "x1" } Dim expected_in_lookupSymbols = { "x1 As System.Object" } Dim actual_lookupNames = GetLookupNames(compilation, "a.vb") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb") Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) Assert.Contains(expected_in_lookupNames(0), actual_lookupNames) Assert.Contains(expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) End Sub <Fact(), WorkItem(546400, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546400")> Public Sub Bug10272_4() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="GetSemanticInfo"> <file name="a.vb"> Module Program Sub Main(args As String()) Dim x5 = Sub(x1) x4 'BIND:" x4" End Sub End Sub End Module </file> </compilation>) Dim expected_in_lookupNames = { "x1" } Dim expected_in_lookupSymbols = { "x1 As System.Object" } Dim actual_lookupNames = GetLookupNames(compilation, "a.vb") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb") Dim actual_lookupSymbols_as_string = actual_lookupSymbols.Select(Function(e) e.ToTestDisplayString()) Assert.Contains(expected_in_lookupNames(0), actual_lookupNames) Assert.Contains(expected_in_lookupSymbols(0), actual_lookupSymbols_as_string) End Sub <Fact()> Public Sub LookupSymbolsAtEOF() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C End Class </file> </compilation>) Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim eof = tree.GetCompilationUnitRoot().FullSpan.End Assert.NotEqual(eof, 0) Dim symbols = model.LookupSymbols(eof) CompilationUtils.CheckSymbols(symbols, "Microsoft", "C", "System") End Sub <Fact(), WorkItem(939844, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/939844")> Public Sub Bug939844_01() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module Program Sub Main(args As String()) Dim x = 1 If True Then Dim y = 1 x=y 'BIND:"y" End If End Sub End Module </file> </compilation>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim pos As Integer = FindBindingTextPosition(compilation, "a.vb") + 20 Dim symsX = semanticModel.LookupSymbols(pos, Nothing, "x") Assert.Equal(1, symsX.Length) Assert.Equal("x As System.Int32", symsX(0).ToTestDisplayString()) Dim symsY = semanticModel.LookupSymbols(pos, Nothing, "y") Assert.Equal(1, symsY.Length) Assert.Equal("y As System.Int32", symsY(0).ToTestDisplayString()) End Sub <Fact(), WorkItem(939844, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/939844")> Public Sub Bug939844_02() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module Program Sub Main(args As String()) Dim x = 1 Select Case 1 Case 1 Dim y = 1 x=y 'BIND:"y" End Select End Sub End Module </file> </compilation>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim pos As Integer = FindBindingTextPosition(compilation, "a.vb") + 20 Dim symsX = semanticModel.LookupSymbols(pos, Nothing, "x") Assert.Equal(1, symsX.Length) Assert.Equal("x As System.Int32", symsX(0).ToTestDisplayString()) Dim symsY = semanticModel.LookupSymbols(pos, Nothing, "y") Assert.Equal(1, symsY.Length) Assert.Equal("y As System.Int32", symsY(0).ToTestDisplayString()) End Sub #End Region End Class End Namespace
1
dotnet/roslyn
56,011
React to string comparison changing on .NET Core
The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
jaredpar
"2021-08-30T17:18:52Z"
"2021-08-30T20:20:04Z"
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
4d99cda6e446e77dbb302e26388c1093bd3ef569
React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
./src/Compilers/VisualBasic/Test/Semantic/ExtensionMethods/SemanticModelTests.vb
' 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.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.ExtensionMethods Public Class ExtendedSemanticInfoTests : Inherits SemanticModelTestBase <Fact> Public Sub Test_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Option Strict Off Imports System.Runtime.CompilerServices Module Module1 Sub Main() Dim x As New C1() x.F1()'BIND:"F1" End Sub <Extension()> Function F1(ByRef this As C1) As Integer Return 0 End Function End Module Class C1 End Class Namespace System.Runtime.CompilerServices <AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)> Class ExtensionAttribute Inherits Attribute End Class End Namespace ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticInfo.Type) Assert.Null(semanticInfo.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Dim method = DirectCast(semanticInfo.Symbol, MethodSymbol) Assert.Equal("Function C1.F1() As System.Int32", method.ToTestDisplayString()) Assert.Equal(SymbolKind.Method, method.Kind) Assert.Equal(MethodKind.ReducedExtension, method.MethodKind) Assert.Equal("C1", method.ReceiverType.ToTestDisplayString()) Assert.Equal("Function Module1.F1(ByRef this As C1) As System.Int32", method.ReducedFrom.ToTestDisplayString()) Assert.Equal(MethodKind.Ordinary, method.CallsiteReducedFromMethod.MethodKind) Assert.Equal("Function Module1.F1(ByRef this As C1) As System.Int32", method.CallsiteReducedFromMethod.ToTestDisplayString()) Dim reducedMethod As MethodSymbol = method.ReducedFrom.ReduceExtensionMethod(method.ReceiverType) Assert.Equal("Function C1.F1() As System.Int32", reducedMethod.ToTestDisplayString()) Assert.Equal(MethodKind.ReducedExtension, reducedMethod.MethodKind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(1, semanticInfo.MemberGroup.Length) Dim sortedMethodGroup = semanticInfo.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Function C1.F1() As System.Int32", sortedMethodGroup(0).ToTestDisplayString()) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact> Public Sub Test_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Option Strict Off Imports System.Runtime.CompilerServices Module Module1 Sub Main() Dim x As New C1() x.F1()'BIND:"F1" End Sub <Extension()> Function F1(this As C1) As Integer Return 0 End Function End Module Class C1 Function F1(x As Integer) As Integer Return 0 End Function End Class Namespace System.Runtime.CompilerServices <AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)> Class ExtensionAttribute Inherits Attribute End Class End Namespace ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticInfo.Type) Assert.Null(semanticInfo.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Function C1.F1() As System.Int32", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(2, semanticInfo.MemberGroup.Length) Dim sortedMethodGroup = semanticInfo.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Function C1.F1() As System.Int32", sortedMethodGroup(0).ToTestDisplayString()) Assert.Equal("Function C1.F1(x As System.Int32) As System.Int32", sortedMethodGroup(1).ToTestDisplayString()) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact> Public Sub Test_3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Option Strict Off Imports System.Runtime.CompilerServices Module Module1 Sub Main() Dim x As New C1() x.F1()'BIND:"x.F1()" End Sub <Extension()> Function F1(this As C1) As Integer Return 0 End Function End Module Class C1 Function F1(x As Integer) As Integer Return 0 End Function End Class Namespace System.Runtime.CompilerServices <AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)> Class ExtensionAttribute Inherits Attribute End Class End Namespace ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of InvocationExpressionSyntax)(compilation, "a.vb") Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Function C1.F1() As System.Int32", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub End Class End Namespace Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Partial Public Class SemanticModelTests <Fact> Public Sub ExtensionMethodsLookupSymbols1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Option Strict Off Imports System.Runtime.CompilerServices Module Module1 Sub Main() Dim x As New C1() x.F1()'BIND:"x" End Sub <Extension()> Function F1(this As C1) As Integer Return 0 End Function End Module Class C1 Function F1(x As Integer) As Integer Return 0 End Function End Class Namespace System.Runtime.CompilerServices <AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)> Class ExtensionAttribute Inherits Attribute End Class End Namespace ]]></file> </compilation>) Dim c1 = compilation.GetTypeByMetadataName("C1") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="F1", container:=c1, includeReducedExtensionMethods:=True) Assert.Equal(2, actual_lookupSymbols.Count) Dim sortedMethodGroup = actual_lookupSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Function C1.F1() As System.Int32", sortedMethodGroup(0).ToTestDisplayString()) Assert.Equal("Function C1.F1(x As System.Int32) As System.Int32", sortedMethodGroup(1).ToTestDisplayString()) actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="F1", container:=c1, includeReducedExtensionMethods:=False) Assert.Equal(1, actual_lookupSymbols.Count) Assert.Equal("Function C1.F1(x As System.Int32) As System.Int32", actual_lookupSymbols(0).ToTestDisplayString()) End Sub <Fact> Public Sub ExtensionMethodsLookupSymbols2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Option Strict Off Imports System.Runtime.CompilerServices Module Module1 Sub Main() End Sub <Extension()> Function F1(this As C1) As Integer Return 0 End Function End Module Class C1 Function F1(x As Integer) As Integer Return 0 End Function Shared Sub Main() F1()'BIND:"F1" End Sub End Class Namespace System.Runtime.CompilerServices <AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)> Class ExtensionAttribute Inherits Attribute End Class End Namespace ]]></file> </compilation>) Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="F1", includeReducedExtensionMethods:=True) Assert.Equal(2, actual_lookupSymbols.Count) Dim sortedMethodGroup = actual_lookupSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Function C1.F1() As System.Int32", sortedMethodGroup(0).ToTestDisplayString()) Assert.Equal("Function C1.F1(x As System.Int32) As System.Int32", sortedMethodGroup(1).ToTestDisplayString()) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:="https://github.com/dotnet/roslyn/issues/29531")> Public Sub ExtensionMethodsLookupSymbols3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System.Console Imports System.Runtime.CompilerServices Imports NS3.Module5 Imports NS3 Namespace NS1 Namespace NS2 Module Module1 Sub Main() Dim x As New C1() x.Test1() 'BIND:"Test1" End Sub &lt;Extension()&gt; Sub Test1(Of T1)(this As NS1.NS2.Module1.C1) End Sub Class C1 End Class End Module Module Module2 &lt;Extension()&gt; Sub Test1(Of T1, T2)(this As NS1.NS2.Module1.C1) End Sub End Module End Namespace Module Module3 &lt;Extension()&gt; Sub Test1(Of T1, T2, T3)(this As NS1.NS2.Module1.C1) End Sub End Module End Namespace Module Module4 &lt;Extension()&gt; Sub Test1(Of T1, T2, T3, T4)(this As NS1.NS2.Module1.C1) End Sub End Module Namespace NS3 Module Module5 &lt;Extension()&gt; Sub Test1(Of T1, T2, T3, T4, T5)(this As NS1.NS2.Module1.C1) End Sub End Module Module Module6 &lt;Extension()&gt; Sub Test1(Of T1, T2, T3, T4, T5, T6)(this As NS1.NS2.Module1.C1) End Sub End Module End Namespace Namespace NS4 Module Module7 &lt;Extension()&gt; Sub Test1(Of T1, T2, T3, T4, T5, T6, T7)(this As NS1.NS2.Module1.C1) End Sub End Module Module Module8 &lt;Extension()&gt; Sub Test1(Of T1, T2, T3, T4, T5, T6, T7, T8)(this As NS1.NS2.Module1.C1) End Sub End Module End Namespace Namespace NS5 Module Module9 &lt;Extension()&gt; Sub Test1(Of T1, T2, T3, T4, T5, T6, T7, T8, T9)(this As NS1.NS2.Module1.C1) End Sub End Module End Namespace Namespace System.Runtime.CompilerServices &lt;AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)&gt; Class ExtensionAttribute Inherits Attribute End Class End Namespace </file> </compilation>, options:=TestOptions.ReleaseExe.WithGlobalImports(GlobalImport.Parse({"NS4.Module7", "NS4"}))) Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="Test1", includeReducedExtensionMethods:=True) Assert.Equal(1, actual_lookupSymbols.Count) Assert.Equal("Sub NS1.NS2.Module1.Test1(Of T1)(this As NS1.NS2.Module1.C1)", actual_lookupSymbols(0).ToTestDisplayString()) Dim c1 = compilation.GetTypeByMetadataName("NS1.NS2.Module1+C1") actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="Test1", container:=c1, includeReducedExtensionMethods:=True) Assert.Equal(8, actual_lookupSymbols.Count) Dim sortedMethodGroup = actual_lookupSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Dim expected() As String = {"Sub NS1.NS2.Module1.C1.Test1(Of T1)()", "Sub NS1.NS2.Module1.C1.Test1(Of T1, T2)()", "Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3)()", "Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4)()", "Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4, T5)()", "Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4, T5, T6)()", "Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4, T5, T6, T7)()", "Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4, T5, T6, T7, T8)()"} For i As Integer = 0 To Math.Max(sortedMethodGroup.Length, expected.Length) - 1 Assert.Equal(expected(i), sortedMethodGroup(i).ToTestDisplayString()) Next actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="Test1", container:=c1) Assert.Equal(0, actual_lookupSymbols.Count) actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="Test1", container:=c1, arity:=4, includeReducedExtensionMethods:=True) Assert.Equal(1, actual_lookupSymbols.Count) Assert.Equal("Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4)()", actual_lookupSymbols(0).ToTestDisplayString()) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:="https://github.com/dotnet/roslyn/issues/29531")> Public Sub ExtensionMethodsLookupSymbols4() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System.Console Imports System.Runtime.CompilerServices Imports NS3.Module5 Imports NS3 Namespace NS1 Namespace NS2 Module Module1 Sub Main() End Sub &lt;Extension()&gt; Sub Test1(Of T1)(this As NS1.NS2.Module1.C1) End Sub Class C1 Sub Main() Test1() 'BIND:"Test1" End Sub End Class End Module Module Module2 &lt;Extension()&gt; Sub Test1(Of T1, T2)(this As NS1.NS2.Module1.C1) End Sub End Module End Namespace Module Module3 &lt;Extension()&gt; Sub Test1(Of T1, T2, T3)(this As NS1.NS2.Module1.C1) End Sub End Module End Namespace Module Module4 &lt;Extension()&gt; Sub Test1(Of T1, T2, T3, T4)(this As NS1.NS2.Module1.C1) End Sub End Module Namespace NS3 Module Module5 &lt;Extension()&gt; Sub Test1(Of T1, T2, T3, T4, T5)(this As NS1.NS2.Module1.C1) End Sub End Module Module Module6 &lt;Extension()&gt; Sub Test1(Of T1, T2, T3, T4, T5, T6)(this As NS1.NS2.Module1.C1) End Sub End Module End Namespace Namespace NS4 Module Module7 &lt;Extension()&gt; Sub Test1(Of T1, T2, T3, T4, T5, T6, T7)(this As NS1.NS2.Module1.C1) End Sub End Module Module Module8 &lt;Extension()&gt; Sub Test1(Of T1, T2, T3, T4, T5, T6, T7, T8)(this As NS1.NS2.Module1.C1) End Sub End Module End Namespace Namespace NS5 Module Module9 &lt;Extension()&gt; Sub Test1(Of T1, T2, T3, T4, T5, T6, T7, T8, T9)(this As NS1.NS2.Module1.C1) End Sub End Module End Namespace Namespace System.Runtime.CompilerServices &lt;AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)&gt; Class ExtensionAttribute Inherits Attribute End Class End Namespace </file> </compilation>, options:=TestOptions.ReleaseExe.WithGlobalImports(GlobalImport.Parse({"NS4.Module7", "NS4"}))) Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="Test1", includeReducedExtensionMethods:=True) Assert.Equal(8, actual_lookupSymbols.Count) Dim sortedMethodGroup = actual_lookupSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Dim expected() As String = {"Sub NS1.NS2.Module1.C1.Test1(Of T1)()", "Sub NS1.NS2.Module1.C1.Test1(Of T1, T2)()", "Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3)()", "Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4)()", "Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4, T5)()", "Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4, T5, T6)()", "Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4, T5, T6, T7)()", "Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4, T5, T6, T7, T8)()"} For i As Integer = 0 To Math.Max(sortedMethodGroup.Length, expected.Length) - 1 Assert.Equal(expected(i), sortedMethodGroup(i).ToTestDisplayString()) Next actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="Test1") Assert.Equal(1, actual_lookupSymbols.Count) Assert.Equal("Sub NS1.NS2.Module1.Test1(Of T1)(this As NS1.NS2.Module1.C1)", actual_lookupSymbols(0).ToTestDisplayString()) actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="Test1", arity:=4, includeReducedExtensionMethods:=True) Assert.Equal(1, actual_lookupSymbols.Count) Assert.Equal("Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4)()", actual_lookupSymbols(0).ToTestDisplayString()) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:="https://github.com/dotnet/roslyn/issues/29531")> Public Sub ExtensionMethodsLookupSymbols5() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System.Console Imports System.Runtime.CompilerServices Imports NS3.Module5 Imports NS3 Namespace NS1 Namespace NS2 Module Module1 Sub Main() Dim x As C1 = Nothing x.Test1() 'BIND:"Test1" End Sub &lt;Extension()&gt; Sub Test1(Of T1)(this As NS1.NS2.Module1.C1) End Sub Interface C1 End Interface End Module Module Module2 &lt;Extension()&gt; Sub Test1(Of T1, T2)(this As NS1.NS2.Module1.C1) End Sub End Module End Namespace Module Module3 &lt;Extension()&gt; Sub Test1(Of T1, T2, T3)(this As NS1.NS2.Module1.C1) End Sub End Module End Namespace Module Module4 &lt;Extension()&gt; Sub Test1(Of T1, T2, T3, T4)(this As NS1.NS2.Module1.C1) End Sub End Module Namespace NS3 Module Module5 &lt;Extension()&gt; Sub Test1(Of T1, T2, T3, T4, T5)(this As NS1.NS2.Module1.C1) End Sub End Module Module Module6 &lt;Extension()&gt; Sub Test1(Of T1, T2, T3, T4, T5, T6)(this As NS1.NS2.Module1.C1) End Sub End Module End Namespace Namespace NS4 Module Module7 &lt;Extension()&gt; Sub Test1(Of T1, T2, T3, T4, T5, T6, T7)(this As NS1.NS2.Module1.C1) End Sub End Module Module Module8 &lt;Extension()&gt; Sub Test1(Of T1, T2, T3, T4, T5, T6, T7, T8)(this As NS1.NS2.Module1.C1) End Sub End Module End Namespace Namespace NS5 Module Module9 &lt;Extension()&gt; Sub Test1(Of T1, T2, T3, T4, T5, T6, T7, T8, T9)(this As NS1.NS2.Module1.C1) End Sub End Module End Namespace Namespace System.Runtime.CompilerServices &lt;AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)&gt; Class ExtensionAttribute Inherits Attribute End Class End Namespace </file> </compilation>, options:=TestOptions.ReleaseExe.WithGlobalImports(GlobalImport.Parse({"NS4.Module7", "NS4"}))) Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="Test1", includeReducedExtensionMethods:=True) Assert.Equal(1, actual_lookupSymbols.Count) Assert.Equal("Sub NS1.NS2.Module1.Test1(Of T1)(this As NS1.NS2.Module1.C1)", actual_lookupSymbols(0).ToTestDisplayString()) Dim c1 = compilation.GetTypeByMetadataName("NS1.NS2.Module1+C1") actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="Test1", container:=c1, includeReducedExtensionMethods:=True) Assert.Equal(8, actual_lookupSymbols.Count) Dim sortedMethodGroup = actual_lookupSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Dim expected() As String = {"Sub NS1.NS2.Module1.C1.Test1(Of T1)()", "Sub NS1.NS2.Module1.C1.Test1(Of T1, T2)()", "Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3)()", "Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4)()", "Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4, T5)()", "Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4, T5, T6)()", "Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4, T5, T6, T7)()", "Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4, T5, T6, T7, T8)()"} For i As Integer = 0 To Math.Max(sortedMethodGroup.Length, expected.Length) - 1 Assert.Equal(expected(i), sortedMethodGroup(i).ToTestDisplayString()) Next actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="Test1", container:=c1) Assert.Equal(0, actual_lookupSymbols.Count) actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="Test1", container:=c1, arity:=4, includeReducedExtensionMethods:=True) Assert.Equal(1, actual_lookupSymbols.Count) Assert.Equal("Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4)()", actual_lookupSymbols(0).ToTestDisplayString()) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:="https://github.com/dotnet/roslyn/issues/29531")> Public Sub ExtensionMethodsLookupSymbols6() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System.Console Imports System.Runtime.CompilerServices Imports NS3.Module5 Imports NS3 Namespace NS1 Namespace NS2 Module Module1 Sub Main(Of T)(x as T) x.Test1() 'BIND:"Test1" End Sub &lt;Extension()&gt; Sub Test1(Of T, T1)(this As T) End Sub End Module Module Module2 &lt;Extension()&gt; Sub Test1(Of T, T1, T2)(this As T) End Sub End Module End Namespace Module Module3 &lt;Extension()&gt; Sub Test1(Of T, T1, T2, T3)(this As T) End Sub End Module End Namespace Module Module4 &lt;Extension()&gt; Sub Test1(Of T, T1, T2, T3, T4)(this As T) End Sub End Module Namespace NS3 Module Module5 &lt;Extension()&gt; Sub Test1(Of T, T1, T2, T3, T4, T5)(this As T) End Sub End Module Module Module6 &lt;Extension()&gt; Sub Test1(Of T, T1, T2, T3, T4, T5, T6)(this As T) End Sub End Module End Namespace Namespace NS4 Module Module7 &lt;Extension()&gt; Sub Test1(Of T, T1, T2, T3, T4, T5, T6, T7)(this As T) End Sub End Module Module Module8 &lt;Extension()&gt; Sub Test1(Of T, T1, T2, T3, T4, T5, T6, T7, T8)(this As T) End Sub End Module End Namespace Namespace NS5 Module Module9 &lt;Extension()&gt; Sub Test1(Of T, T1, T2, T3, T4, T5, T6, T7, T8, T9)(this As T) End Sub End Module End Namespace Namespace System.Runtime.CompilerServices &lt;AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)&gt; Class ExtensionAttribute Inherits Attribute End Class End Namespace </file> </compilation>, options:=TestOptions.ReleaseExe.WithGlobalImports(GlobalImport.Parse({"NS4.Module7", "NS4"}))) Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="Test1", includeReducedExtensionMethods:=True) Assert.Equal(1, actual_lookupSymbols.Count) Assert.Equal("Sub NS1.NS2.Module1.Test1(Of T, T1)(this As T)", actual_lookupSymbols(0).ToTestDisplayString()) Dim module1 = compilation.GetTypeByMetadataName("NS1.NS2.Module1") Dim main = DirectCast(module1.GetMember("Main"), MethodSymbol) Dim t = main.TypeParameters(0) actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="Test1", container:=t, includeReducedExtensionMethods:=True) Assert.Equal(8, actual_lookupSymbols.Count) Dim sortedMethodGroup = actual_lookupSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Dim expected() As String = {"Sub T.Test1(Of T1)()", "Sub T.Test1(Of T1, T2)()", "Sub T.Test1(Of T1, T2, T3)()", "Sub T.Test1(Of T1, T2, T3, T4)()", "Sub T.Test1(Of T1, T2, T3, T4, T5)()", "Sub T.Test1(Of T1, T2, T3, T4, T5, T6)()", "Sub T.Test1(Of T1, T2, T3, T4, T5, T6, T7)()", "Sub T.Test1(Of T1, T2, T3, T4, T5, T6, T7, T8)()"} For i As Integer = 0 To Math.Max(sortedMethodGroup.Length, expected.Length) - 1 Assert.Equal(expected(i), sortedMethodGroup(i).ToTestDisplayString()) Next actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="Test1", container:=t) Assert.Equal(0, actual_lookupSymbols.Count) actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="Test1", container:=t, arity:=4, includeReducedExtensionMethods:=True) Assert.Equal(1, actual_lookupSymbols.Count) Assert.Equal("Sub T.Test1(Of T1, T2, T3, T4)()", actual_lookupSymbols(0).ToTestDisplayString()) End Sub <Fact> Public Sub ExtensionMethodsLookupSymbols7() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System.Console Imports System.Runtime.CompilerServices Imports NS3.Module5 Imports NS3 Namespace NS1 Namespace NS2 Module Module1 Sub Main() Dim x As New C1() x.Test1() 'BIND:"Test1" End Sub &lt;Extension()&gt; Sub Test1(Of T1)(this As NS1.NS2.Module1.C1) End Sub Class C1 End Class End Module Module Module2 &lt;Extension()&gt; Sub Test2(Of T1, T2)(this As NS1.NS2.Module1.C1) End Sub End Module End Namespace Module Module3 &lt;Extension()&gt; Sub Test3(Of T1, T2, T3)(this As NS1.NS2.Module1.C1) End Sub End Module End Namespace Module Module4 &lt;Extension()&gt; Sub Test4(Of T1, T2, T3, T4)(this As NS1.NS2.Module1.C1) End Sub End Module Namespace NS3 Module Module5 &lt;Extension()&gt; Sub Test5(Of T1, T2, T3, T4, T5)(this As NS1.NS2.Module1.C1) End Sub End Module Module Module6 &lt;Extension()&gt; Sub Test6(Of T1, T2, T3, T4, T5, T6)(this As NS1.NS2.Module1.C1) End Sub End Module End Namespace Namespace NS4 Module Module7 &lt;Extension()&gt; Sub Test7(Of T1, T2, T3, T4, T5, T6, T7)(this As NS1.NS2.Module1.C1) End Sub End Module Module Module8 &lt;Extension()&gt; Sub Test8(Of T1, T2, T3, T4, T5, T6, T7, T8)(this As NS1.NS2.Module1.C1) End Sub End Module End Namespace Namespace NS5 Module Module9 &lt;Extension()&gt; Sub Test9(Of T1, T2, T3, T4, T5, T6, T7, T8, T9)(this As NS1.NS2.Module1.C1) End Sub End Module End Namespace Namespace System.Runtime.CompilerServices &lt;AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)&gt; Class ExtensionAttribute Inherits Attribute End Class End Namespace </file> </compilation>, options:=TestOptions.ReleaseExe.WithGlobalImports(GlobalImport.Parse({"NS4.Module7", "NS4"}))) Dim c1 = compilation.GetTypeByMetadataName("NS1.NS2.Module1+C1") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", container:=c1, includeReducedExtensionMethods:=True) Assert.Equal(14, actual_lookupSymbols.Count) Dim sortedMethodGroup = actual_lookupSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Dim expected() As String = {"Function System.Object.Equals(obj As System.Object) As System.Boolean", "Function System.Object.Equals(objA As System.Object, objB As System.Object) As System.Boolean", "Function System.Object.GetHashCode() As System.Int32", "Function System.Object.GetType() As System.Type", "Function System.Object.ReferenceEquals(objA As System.Object, objB As System.Object) As System.Boolean", "Function System.Object.ToString() As System.String", "Sub NS1.NS2.Module1.C1.Test1(Of T1)()", "Sub NS1.NS2.Module1.C1.Test2(Of T1, T2)()", "Sub NS1.NS2.Module1.C1.Test3(Of T1, T2, T3)()", "Sub NS1.NS2.Module1.C1.Test4(Of T1, T2, T3, T4)()", "Sub NS1.NS2.Module1.C1.Test5(Of T1, T2, T3, T4, T5)()", "Sub NS1.NS2.Module1.C1.Test6(Of T1, T2, T3, T4, T5, T6)()", "Sub NS1.NS2.Module1.C1.Test7(Of T1, T2, T3, T4, T5, T6, T7)()", "Sub NS1.NS2.Module1.C1.Test8(Of T1, T2, T3, T4, T5, T6, T7, T8)()"} For i As Integer = 0 To Math.Max(sortedMethodGroup.Length, expected.Length) - 1 Assert.Equal(expected(i), sortedMethodGroup(i).ToTestDisplayString()) Next actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", container:=c1) Assert.Equal(6, actual_lookupSymbols.Count) sortedMethodGroup = actual_lookupSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() For i As Integer = 0 To sortedMethodGroup.Length - 1 Assert.Equal(expected(i), sortedMethodGroup(i).ToTestDisplayString()) Next actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", container:=c1, name:="Test4", arity:=4, includeReducedExtensionMethods:=True) Assert.Equal(1, actual_lookupSymbols.Count) Assert.Equal("Sub NS1.NS2.Module1.C1.Test4(Of T1, T2, T3, T4)()", actual_lookupSymbols(0).ToTestDisplayString()) End Sub <Fact> Public Sub ExtensionMethodsLookupSymbols8() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System.Console Imports System.Runtime.CompilerServices Imports NS3.Module5 Imports NS3 Namespace NS1 Namespace NS2 Module Module1 Sub Main() End Sub &lt;Extension()&gt; Sub Test1(Of T1)(this As NS1.NS2.Module1.C1) End Sub Class C1 Sub Main() Test1() 'BIND:"Test1" End Sub End Class End Module Module Module2 &lt;Extension()&gt; Sub Test2(Of T1, T2)(this As NS1.NS2.Module1.C1) End Sub End Module End Namespace Module Module3 &lt;Extension()&gt; Sub Test3(Of T1, T2, T3)(this As NS1.NS2.Module1.C1) End Sub End Module End Namespace Module Module4 &lt;Extension()&gt; Sub Test4(Of T1, T2, T3, T4)(this As NS1.NS2.Module1.C1) End Sub End Module Namespace NS3 Module Module5 &lt;Extension()&gt; Sub Test5(Of T1, T2, T3, T4, T5)(this As NS1.NS2.Module1.C1) End Sub End Module Module Module6 &lt;Extension()&gt; Sub Test6(Of T1, T2, T3, T4, T5, T6)(this As NS1.NS2.Module1.C1) End Sub End Module End Namespace Namespace NS4 Module Module7 &lt;Extension()&gt; Sub Test7(Of T1, T2, T3, T4, T5, T6, T7)(this As NS1.NS2.Module1.C1) End Sub End Module Module Module8 &lt;Extension()&gt; Sub Test8(Of T1, T2, T3, T4, T5, T6, T7, T8)(this As NS1.NS2.Module1.C1) End Sub End Module End Namespace Namespace NS5 Module Module9 &lt;Extension()&gt; Sub Test9(Of T1, T2, T3, T4, T5, T6, T7, T8, T9)(this As NS1.NS2.Module1.C1) End Sub End Module End Namespace Namespace System.Runtime.CompilerServices &lt;AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)&gt; Class ExtensionAttribute Inherits Attribute End Class End Namespace </file> </compilation>, options:=TestOptions.ReleaseExe.WithGlobalImports(GlobalImport.Parse({"NS4.Module7", "NS4"}))) Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", includeReducedExtensionMethods:=True) Dim sortedMethodGroup = actual_lookupSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Dim expected() As String = {"Function System.Object.Equals(obj As System.Object) As System.Boolean", "Function System.Object.Equals(objA As System.Object, objB As System.Object) As System.Boolean", "Function System.Object.GetHashCode() As System.Int32", "Function System.Object.GetType() As System.Type", "Function System.Object.ReferenceEquals(objA As System.Object, objB As System.Object) As System.Boolean", "Function System.Object.ToString() As System.String", "Sub NS1.NS2.Module1.C1.Test1(Of T1)()", "Sub NS1.NS2.Module1.C1.Test2(Of T1, T2)()", "Sub NS1.NS2.Module1.C1.Test3(Of T1, T2, T3)()", "Sub NS1.NS2.Module1.C1.Test4(Of T1, T2, T3, T4)()", "Sub NS1.NS2.Module1.C1.Test5(Of T1, T2, T3, T4, T5)()", "Sub NS1.NS2.Module1.C1.Test6(Of T1, T2, T3, T4, T5, T6)()", "Sub NS1.NS2.Module1.C1.Test7(Of T1, T2, T3, T4, T5, T6, T7)()", "Sub NS1.NS2.Module1.C1.Test8(Of T1, T2, T3, T4, T5, T6, T7, T8)()"} Assert.Equal(expected.Length, Aggregate name In expected Join symbol In actual_lookupSymbols On symbol.ToTestDisplayString() Equals name Select name Distinct Into Count()) actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb") Assert.Equal(0, Aggregate symbol In actual_lookupSymbols Join name In expected.Skip(6) On symbol.ToTestDisplayString() Equals name Into Count()) actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="Test4", arity:=4, includeReducedExtensionMethods:=True) Assert.Equal(1, actual_lookupSymbols.Count) Assert.Equal("Sub NS1.NS2.Module1.C1.Test4(Of T1, T2, T3, T4)()", actual_lookupSymbols(0).ToTestDisplayString()) End Sub <Fact> Public Sub ExtensionMethodsLookupSymbols9() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System.Console Imports System.Runtime.CompilerServices Imports NS3.Module5 Imports NS3 Namespace NS1 Namespace NS2 Module Module1 Sub Main() Dim x As C1 = Nothing x.Test1() 'BIND:"Test1" End Sub &lt;Extension()&gt; Sub Test1(Of T1)(this As NS1.NS2.Module1.C1) End Sub Interface C1 End Interface End Module Module Module2 &lt;Extension()&gt; Sub Test2(Of T1, T2)(this As NS1.NS2.Module1.C1) End Sub End Module End Namespace Module Module3 &lt;Extension()&gt; Sub Test3(Of T1, T2, T3)(this As NS1.NS2.Module1.C1) End Sub End Module End Namespace Module Module4 &lt;Extension()&gt; Sub Test4(Of T1, T2, T3, T4)(this As NS1.NS2.Module1.C1) End Sub End Module Namespace NS3 Module Module5 &lt;Extension()&gt; Sub Test5(Of T1, T2, T3, T4, T5)(this As NS1.NS2.Module1.C1) End Sub End Module Module Module6 &lt;Extension()&gt; Sub Test6(Of T1, T2, T3, T4, T5, T6)(this As NS1.NS2.Module1.C1) End Sub End Module End Namespace Namespace NS4 Module Module7 &lt;Extension()&gt; Sub Test7(Of T1, T2, T3, T4, T5, T6, T7)(this As NS1.NS2.Module1.C1) End Sub End Module Module Module8 &lt;Extension()&gt; Sub Test8(Of T1, T2, T3, T4, T5, T6, T7, T8)(this As NS1.NS2.Module1.C1) End Sub End Module End Namespace Namespace NS5 Module Module9 &lt;Extension()&gt; Sub Test9(Of T1, T2, T3, T4, T5, T6, T7, T8, T9)(this As NS1.NS2.Module1.C1) End Sub End Module End Namespace Namespace System.Runtime.CompilerServices &lt;AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)&gt; Class ExtensionAttribute Inherits Attribute End Class End Namespace </file> </compilation>, options:=TestOptions.ReleaseExe.WithGlobalImports(GlobalImport.Parse({"NS4.Module7", "NS4"}))) Dim c1 = compilation.GetTypeByMetadataName("NS1.NS2.Module1+C1") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", container:=c1, includeReducedExtensionMethods:=True) Dim expected() As String = {"Sub NS1.NS2.Module1.C1.Test1(Of T1)()", "Sub NS1.NS2.Module1.C1.Test2(Of T1, T2)()", "Sub NS1.NS2.Module1.C1.Test3(Of T1, T2, T3)()", "Sub NS1.NS2.Module1.C1.Test4(Of T1, T2, T3, T4)()", "Sub NS1.NS2.Module1.C1.Test5(Of T1, T2, T3, T4, T5)()", "Sub NS1.NS2.Module1.C1.Test6(Of T1, T2, T3, T4, T5, T6)()", "Sub NS1.NS2.Module1.C1.Test7(Of T1, T2, T3, T4, T5, T6, T7)()", "Sub NS1.NS2.Module1.C1.Test8(Of T1, T2, T3, T4, T5, T6, T7, T8)()"} Assert.Equal(expected.Length, Aggregate name In expected Join symbol In actual_lookupSymbols On symbol.ToTestDisplayString() Equals name Select name Distinct Into Count()) actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", container:=c1) Assert.Equal(0, Aggregate name In expected Join symbol In actual_lookupSymbols On symbol.ToTestDisplayString() Equals name Select name Distinct Into Count()) actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", container:=c1, name:="Test4", arity:=4, includeReducedExtensionMethods:=True) Assert.Equal(1, actual_lookupSymbols.Count) Assert.Equal("Sub NS1.NS2.Module1.C1.Test4(Of T1, T2, T3, T4)()", actual_lookupSymbols(0).ToTestDisplayString()) End Sub <Fact> Public Sub ExtensionMethodsLookupSymbols10() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System.Console Imports System.Runtime.CompilerServices Imports NS3.Module5 Imports NS3 Namespace NS1 Namespace NS2 Module Module1 Sub Main(Of T)(x as T) x.Test1() 'BIND:"Test1" End Sub &lt;Extension()&gt; Sub Test1(Of T, T1)(this As T) End Sub End Module Module Module2 &lt;Extension()&gt; Sub Test2(Of T, T1, T2)(this As T) End Sub End Module End Namespace Module Module3 &lt;Extension()&gt; Sub Test3(Of T, T1, T2, T3)(this As T) End Sub End Module End Namespace Module Module4 &lt;Extension()&gt; Sub Test4(Of T, T1, T2, T3, T4)(this As T) End Sub End Module Namespace NS3 Module Module5 &lt;Extension()&gt; Sub Test5(Of T, T1, T2, T3, T4, T5)(this As T) End Sub End Module Module Module6 &lt;Extension()&gt; Sub Test6(Of T, T1, T2, T3, T4, T5, T6)(this As T) End Sub End Module End Namespace Namespace NS4 Module Module7 &lt;Extension()&gt; Sub Test7(Of T, T1, T2, T3, T4, T5, T6, T7)(this As T) End Sub End Module Module Module8 &lt;Extension()&gt; Sub Test8(Of T, T1, T2, T3, T4, T5, T6, T7, T8)(this As T) End Sub End Module End Namespace Namespace NS5 Module Module9 &lt;Extension()&gt; Sub Test9(Of T, T1, T2, T3, T4, T5, T6, T7, T8, T9)(this As T) End Sub End Module End Namespace Namespace System.Runtime.CompilerServices &lt;AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)&gt; Class ExtensionAttribute Inherits Attribute End Class End Namespace </file> </compilation>, options:=TestOptions.ReleaseExe.WithGlobalImports(GlobalImport.Parse({"NS4.Module7", "NS4"}))) Dim module1 = compilation.GetTypeByMetadataName("NS1.NS2.Module1") Dim main = DirectCast(module1.GetMember("Main"), MethodSymbol) Dim t = main.TypeParameters(0) Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", container:=t, includeReducedExtensionMethods:=True) Dim expected() As String = {"Sub T.Test1(Of T1)()", "Sub T.Test2(Of T1, T2)()", "Sub T.Test3(Of T1, T2, T3)()", "Sub T.Test4(Of T1, T2, T3, T4)()", "Sub T.Test5(Of T1, T2, T3, T4, T5)()", "Sub T.Test6(Of T1, T2, T3, T4, T5, T6)()", "Sub T.Test7(Of T1, T2, T3, T4, T5, T6, T7)()", "Sub T.Test8(Of T1, T2, T3, T4, T5, T6, T7, T8)()"} Assert.Equal(expected.Length, Aggregate name In expected Join symbol In actual_lookupSymbols On symbol.ToTestDisplayString() Equals name Select name Distinct Into Count()) actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", container:=t, includeReducedExtensionMethods:=False) Assert.Equal(0, Aggregate name In expected Join symbol In actual_lookupSymbols On symbol.ToTestDisplayString() Equals name Select name Distinct Into Count()) actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", container:=t, name:="Test4", arity:=4, includeReducedExtensionMethods:=True) Assert.Equal(1, actual_lookupSymbols.Count) Assert.Equal("Sub T.Test4(Of T1, T2, T3, T4)()", actual_lookupSymbols(0).ToTestDisplayString()) End Sub <Fact> Public Sub Bug8942_1() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System Imports System.Runtime.CompilerServices Module M &lt;Extension()&gt; Sub Goo(x As Exception) End Sub End Module Class E Inherits Exception Sub Bar() Me.Goo() 'BIND:"Goo" End Sub End Class Namespace System.Runtime.CompilerServices &lt;AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)&gt; Class ExtensionAttribute Inherits Attribute End Class End Namespace </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticInfo.Type) Assert.Null(semanticInfo.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Sub System.Exception.Goo()", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(1, semanticInfo.MemberGroup.Length) Dim sortedMethodGroup = semanticInfo.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub System.Exception.Goo()", sortedMethodGroup(0).ToTestDisplayString()) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact> Public Sub Bug8942_2() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System Imports System.Runtime.CompilerServices Module M &lt;Extension()&gt; Sub Goo(x As Exception) End Sub End Module Class E Inherits Exception Sub Bar() Goo() 'BIND:"Goo" End Sub End Class Namespace System.Runtime.CompilerServices &lt;AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)&gt; Class ExtensionAttribute Inherits Attribute End Class End Namespace </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticInfo.Type) Assert.Null(semanticInfo.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Sub System.Exception.Goo()", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(1, semanticInfo.MemberGroup.Length) Dim sortedMethodGroup = semanticInfo.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub System.Exception.Goo()", sortedMethodGroup(0).ToTestDisplayString()) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <WorkItem(544933, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544933")> <Fact> Public Sub LookupSymbolsGenericExtensionMethodWithConstraints() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="a.vb"><![CDATA[ Imports System.Runtime.CompilerServices Class A End Class Class B End Class Module E Sub M(_a As A, _b As B) _a.F() _b.F() End Sub <Extension()> Sub F(Of T As A)(o As T) End Sub End Module ]]></file> </compilation>, {TestMetadata.Net40.SystemCore}) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC30456: 'F' is not a member of 'B'. _b.F() ~~~~ ]]></errors>) Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim position = FindNodeFromText(tree, "_a.F()").SpanStart Dim method = compilation.GlobalNamespace.GetMember(Of NamedTypeSymbol)("E").GetMember(Of MethodSymbol)("M") ' No type. Dim symbols = model.LookupSymbols(position, container:=Nothing, name:="F", includeReducedExtensionMethods:=True) CheckSymbols(symbols, "Sub E.F(Of T)(o As T)") ' Type satisfying constraints. symbols = model.LookupSymbols(position, container:=method.Parameters(0).Type, name:="F", includeReducedExtensionMethods:=True) CheckSymbols(symbols, "Sub A.F()") ' Type not satisfying constraints. symbols = model.LookupSymbols(position, container:=method.Parameters(1).Type, name:="F", includeReducedExtensionMethods:=True) CheckSymbols(symbols) End Sub <Fact, WorkItem(963125, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/963125")> Public Sub Bug963125() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports alias2 = System Module Module1 Sub Main() alias1.Console.WriteLine() alias2.Console.WriteLine() End Sub End Module </file> </compilation>, options:=TestOptions.ReleaseExe.WithGlobalImports(GlobalImport.Parse({"alias1 = System"}))) compilation.AssertNoDiagnostics() Dim tree = compilation.SyntaxTrees.Single() Dim model = compilation.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes().OfType(Of IdentifierNameSyntax)().Where(Function(n) n.Identifier.ValueText = "alias1").Single() Dim alias1 = model.GetAliasInfo(node1) Assert.Equal("alias1=System", alias1.ToTestDisplayString()) Assert.Equal(LocationKind.None, alias1.Locations.Single().Kind) Dim node2 = tree.GetRoot().DescendantNodes().OfType(Of IdentifierNameSyntax)().Where(Function(n) n.Identifier.ValueText = "alias2").Single() Dim alias2 = model.GetAliasInfo(node2) Assert.Equal("alias2=System", alias2.ToTestDisplayString()) Assert.Equal(LocationKind.SourceFile, alias2.Locations.Single().Kind) End Sub End Class End Namespace
' 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.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.ExtensionMethods Public Class ExtendedSemanticInfoTests : Inherits SemanticModelTestBase <Fact> Public Sub Test_1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Option Strict Off Imports System.Runtime.CompilerServices Module Module1 Sub Main() Dim x As New C1() x.F1()'BIND:"F1" End Sub <Extension()> Function F1(ByRef this As C1) As Integer Return 0 End Function End Module Class C1 End Class Namespace System.Runtime.CompilerServices <AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)> Class ExtensionAttribute Inherits Attribute End Class End Namespace ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticInfo.Type) Assert.Null(semanticInfo.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Dim method = DirectCast(semanticInfo.Symbol, MethodSymbol) Assert.Equal("Function C1.F1() As System.Int32", method.ToTestDisplayString()) Assert.Equal(SymbolKind.Method, method.Kind) Assert.Equal(MethodKind.ReducedExtension, method.MethodKind) Assert.Equal("C1", method.ReceiverType.ToTestDisplayString()) Assert.Equal("Function Module1.F1(ByRef this As C1) As System.Int32", method.ReducedFrom.ToTestDisplayString()) Assert.Equal(MethodKind.Ordinary, method.CallsiteReducedFromMethod.MethodKind) Assert.Equal("Function Module1.F1(ByRef this As C1) As System.Int32", method.CallsiteReducedFromMethod.ToTestDisplayString()) Dim reducedMethod As MethodSymbol = method.ReducedFrom.ReduceExtensionMethod(method.ReceiverType) Assert.Equal("Function C1.F1() As System.Int32", reducedMethod.ToTestDisplayString()) Assert.Equal(MethodKind.ReducedExtension, reducedMethod.MethodKind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(1, semanticInfo.MemberGroup.Length) Dim sortedMethodGroup = semanticInfo.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Function C1.F1() As System.Int32", sortedMethodGroup(0).ToTestDisplayString()) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact> Public Sub Test_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Option Strict Off Imports System.Runtime.CompilerServices Module Module1 Sub Main() Dim x As New C1() x.F1()'BIND:"F1" End Sub <Extension()> Function F1(this As C1) As Integer Return 0 End Function End Module Class C1 Function F1(x As Integer) As Integer Return 0 End Function End Class Namespace System.Runtime.CompilerServices <AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)> Class ExtensionAttribute Inherits Attribute End Class End Namespace ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticInfo.Type) Assert.Null(semanticInfo.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Function C1.F1() As System.Int32", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(2, semanticInfo.MemberGroup.Length) Dim sortedMethodGroup = semanticInfo.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Function C1.F1() As System.Int32", sortedMethodGroup(0).ToTestDisplayString()) Assert.Equal("Function C1.F1(x As System.Int32) As System.Int32", sortedMethodGroup(1).ToTestDisplayString()) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact> Public Sub Test_3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Option Strict Off Imports System.Runtime.CompilerServices Module Module1 Sub Main() Dim x As New C1() x.F1()'BIND:"x.F1()" End Sub <Extension()> Function F1(this As C1) As Integer Return 0 End Function End Module Class C1 Function F1(x As Integer) As Integer Return 0 End Function End Class Namespace System.Runtime.CompilerServices <AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)> Class ExtensionAttribute Inherits Attribute End Class End Namespace ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of InvocationExpressionSyntax)(compilation, "a.vb") Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Function C1.F1() As System.Int32", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub End Class End Namespace Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Partial Public Class SemanticModelTests <Fact> Public Sub ExtensionMethodsLookupSymbols1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Option Strict Off Imports System.Runtime.CompilerServices Module Module1 Sub Main() Dim x As New C1() x.F1()'BIND:"x" End Sub <Extension()> Function F1(this As C1) As Integer Return 0 End Function End Module Class C1 Function F1(x As Integer) As Integer Return 0 End Function End Class Namespace System.Runtime.CompilerServices <AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)> Class ExtensionAttribute Inherits Attribute End Class End Namespace ]]></file> </compilation>) Dim c1 = compilation.GetTypeByMetadataName("C1") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="F1", container:=c1, includeReducedExtensionMethods:=True) Assert.Equal(2, actual_lookupSymbols.Count) Dim sortedMethodGroup = actual_lookupSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Function C1.F1() As System.Int32", sortedMethodGroup(0).ToTestDisplayString()) Assert.Equal("Function C1.F1(x As System.Int32) As System.Int32", sortedMethodGroup(1).ToTestDisplayString()) actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="F1", container:=c1, includeReducedExtensionMethods:=False) Assert.Equal(1, actual_lookupSymbols.Count) Assert.Equal("Function C1.F1(x As System.Int32) As System.Int32", actual_lookupSymbols(0).ToTestDisplayString()) End Sub <Fact> Public Sub ExtensionMethodsLookupSymbols2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Option Strict Off Imports System.Runtime.CompilerServices Module Module1 Sub Main() End Sub <Extension()> Function F1(this As C1) As Integer Return 0 End Function End Module Class C1 Function F1(x As Integer) As Integer Return 0 End Function Shared Sub Main() F1()'BIND:"F1" End Sub End Class Namespace System.Runtime.CompilerServices <AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)> Class ExtensionAttribute Inherits Attribute End Class End Namespace ]]></file> </compilation>) Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="F1", includeReducedExtensionMethods:=True) Assert.Equal(2, actual_lookupSymbols.Count) Dim sortedMethodGroup = actual_lookupSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString(), StringComparer.Ordinal).ToArray() Assert.Equal("Function C1.F1() As System.Int32", sortedMethodGroup(0).ToTestDisplayString()) Assert.Equal("Function C1.F1(x As System.Int32) As System.Int32", sortedMethodGroup(1).ToTestDisplayString()) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:="https://github.com/dotnet/roslyn/issues/29531")> Public Sub ExtensionMethodsLookupSymbols3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System.Console Imports System.Runtime.CompilerServices Imports NS3.Module5 Imports NS3 Namespace NS1 Namespace NS2 Module Module1 Sub Main() Dim x As New C1() x.Test1() 'BIND:"Test1" End Sub &lt;Extension()&gt; Sub Test1(Of T1)(this As NS1.NS2.Module1.C1) End Sub Class C1 End Class End Module Module Module2 &lt;Extension()&gt; Sub Test1(Of T1, T2)(this As NS1.NS2.Module1.C1) End Sub End Module End Namespace Module Module3 &lt;Extension()&gt; Sub Test1(Of T1, T2, T3)(this As NS1.NS2.Module1.C1) End Sub End Module End Namespace Module Module4 &lt;Extension()&gt; Sub Test1(Of T1, T2, T3, T4)(this As NS1.NS2.Module1.C1) End Sub End Module Namespace NS3 Module Module5 &lt;Extension()&gt; Sub Test1(Of T1, T2, T3, T4, T5)(this As NS1.NS2.Module1.C1) End Sub End Module Module Module6 &lt;Extension()&gt; Sub Test1(Of T1, T2, T3, T4, T5, T6)(this As NS1.NS2.Module1.C1) End Sub End Module End Namespace Namespace NS4 Module Module7 &lt;Extension()&gt; Sub Test1(Of T1, T2, T3, T4, T5, T6, T7)(this As NS1.NS2.Module1.C1) End Sub End Module Module Module8 &lt;Extension()&gt; Sub Test1(Of T1, T2, T3, T4, T5, T6, T7, T8)(this As NS1.NS2.Module1.C1) End Sub End Module End Namespace Namespace NS5 Module Module9 &lt;Extension()&gt; Sub Test1(Of T1, T2, T3, T4, T5, T6, T7, T8, T9)(this As NS1.NS2.Module1.C1) End Sub End Module End Namespace Namespace System.Runtime.CompilerServices &lt;AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)&gt; Class ExtensionAttribute Inherits Attribute End Class End Namespace </file> </compilation>, options:=TestOptions.ReleaseExe.WithGlobalImports(GlobalImport.Parse({"NS4.Module7", "NS4"}))) Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="Test1", includeReducedExtensionMethods:=True) Assert.Equal(1, actual_lookupSymbols.Count) Assert.Equal("Sub NS1.NS2.Module1.Test1(Of T1)(this As NS1.NS2.Module1.C1)", actual_lookupSymbols(0).ToTestDisplayString()) Dim c1 = compilation.GetTypeByMetadataName("NS1.NS2.Module1+C1") actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="Test1", container:=c1, includeReducedExtensionMethods:=True) Assert.Equal(8, actual_lookupSymbols.Count) Dim sortedMethodGroup = actual_lookupSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString(), StringComparer.Ordinal).ToArray() Dim expected() As String = {"Sub NS1.NS2.Module1.C1.Test1(Of T1)()", "Sub NS1.NS2.Module1.C1.Test1(Of T1, T2)()", "Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3)()", "Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4)()", "Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4, T5)()", "Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4, T5, T6)()", "Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4, T5, T6, T7)()", "Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4, T5, T6, T7, T8)()"} For i As Integer = 0 To Math.Max(sortedMethodGroup.Length, expected.Length) - 1 Assert.Equal(expected(i), sortedMethodGroup(i).ToTestDisplayString()) Next actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="Test1", container:=c1) Assert.Equal(0, actual_lookupSymbols.Count) actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="Test1", container:=c1, arity:=4, includeReducedExtensionMethods:=True) Assert.Equal(1, actual_lookupSymbols.Count) Assert.Equal("Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4)()", actual_lookupSymbols(0).ToTestDisplayString()) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:="https://github.com/dotnet/roslyn/issues/29531")> Public Sub ExtensionMethodsLookupSymbols4() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System.Console Imports System.Runtime.CompilerServices Imports NS3.Module5 Imports NS3 Namespace NS1 Namespace NS2 Module Module1 Sub Main() End Sub &lt;Extension()&gt; Sub Test1(Of T1)(this As NS1.NS2.Module1.C1) End Sub Class C1 Sub Main() Test1() 'BIND:"Test1" End Sub End Class End Module Module Module2 &lt;Extension()&gt; Sub Test1(Of T1, T2)(this As NS1.NS2.Module1.C1) End Sub End Module End Namespace Module Module3 &lt;Extension()&gt; Sub Test1(Of T1, T2, T3)(this As NS1.NS2.Module1.C1) End Sub End Module End Namespace Module Module4 &lt;Extension()&gt; Sub Test1(Of T1, T2, T3, T4)(this As NS1.NS2.Module1.C1) End Sub End Module Namespace NS3 Module Module5 &lt;Extension()&gt; Sub Test1(Of T1, T2, T3, T4, T5)(this As NS1.NS2.Module1.C1) End Sub End Module Module Module6 &lt;Extension()&gt; Sub Test1(Of T1, T2, T3, T4, T5, T6)(this As NS1.NS2.Module1.C1) End Sub End Module End Namespace Namespace NS4 Module Module7 &lt;Extension()&gt; Sub Test1(Of T1, T2, T3, T4, T5, T6, T7)(this As NS1.NS2.Module1.C1) End Sub End Module Module Module8 &lt;Extension()&gt; Sub Test1(Of T1, T2, T3, T4, T5, T6, T7, T8)(this As NS1.NS2.Module1.C1) End Sub End Module End Namespace Namespace NS5 Module Module9 &lt;Extension()&gt; Sub Test1(Of T1, T2, T3, T4, T5, T6, T7, T8, T9)(this As NS1.NS2.Module1.C1) End Sub End Module End Namespace Namespace System.Runtime.CompilerServices &lt;AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)&gt; Class ExtensionAttribute Inherits Attribute End Class End Namespace </file> </compilation>, options:=TestOptions.ReleaseExe.WithGlobalImports(GlobalImport.Parse({"NS4.Module7", "NS4"}))) Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="Test1", includeReducedExtensionMethods:=True) Assert.Equal(8, actual_lookupSymbols.Count) Dim sortedMethodGroup = actual_lookupSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString(), StringComparer.Ordinal).ToArray() Dim expected() As String = {"Sub NS1.NS2.Module1.C1.Test1(Of T1)()", "Sub NS1.NS2.Module1.C1.Test1(Of T1, T2)()", "Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3)()", "Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4)()", "Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4, T5)()", "Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4, T5, T6)()", "Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4, T5, T6, T7)()", "Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4, T5, T6, T7, T8)()"} For i As Integer = 0 To Math.Max(sortedMethodGroup.Length, expected.Length) - 1 Assert.Equal(expected(i), sortedMethodGroup(i).ToTestDisplayString()) Next actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="Test1") Assert.Equal(1, actual_lookupSymbols.Count) Assert.Equal("Sub NS1.NS2.Module1.Test1(Of T1)(this As NS1.NS2.Module1.C1)", actual_lookupSymbols(0).ToTestDisplayString()) actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="Test1", arity:=4, includeReducedExtensionMethods:=True) Assert.Equal(1, actual_lookupSymbols.Count) Assert.Equal("Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4)()", actual_lookupSymbols(0).ToTestDisplayString()) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:="https://github.com/dotnet/roslyn/issues/29531")> Public Sub ExtensionMethodsLookupSymbols5() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System.Console Imports System.Runtime.CompilerServices Imports NS3.Module5 Imports NS3 Namespace NS1 Namespace NS2 Module Module1 Sub Main() Dim x As C1 = Nothing x.Test1() 'BIND:"Test1" End Sub &lt;Extension()&gt; Sub Test1(Of T1)(this As NS1.NS2.Module1.C1) End Sub Interface C1 End Interface End Module Module Module2 &lt;Extension()&gt; Sub Test1(Of T1, T2)(this As NS1.NS2.Module1.C1) End Sub End Module End Namespace Module Module3 &lt;Extension()&gt; Sub Test1(Of T1, T2, T3)(this As NS1.NS2.Module1.C1) End Sub End Module End Namespace Module Module4 &lt;Extension()&gt; Sub Test1(Of T1, T2, T3, T4)(this As NS1.NS2.Module1.C1) End Sub End Module Namespace NS3 Module Module5 &lt;Extension()&gt; Sub Test1(Of T1, T2, T3, T4, T5)(this As NS1.NS2.Module1.C1) End Sub End Module Module Module6 &lt;Extension()&gt; Sub Test1(Of T1, T2, T3, T4, T5, T6)(this As NS1.NS2.Module1.C1) End Sub End Module End Namespace Namespace NS4 Module Module7 &lt;Extension()&gt; Sub Test1(Of T1, T2, T3, T4, T5, T6, T7)(this As NS1.NS2.Module1.C1) End Sub End Module Module Module8 &lt;Extension()&gt; Sub Test1(Of T1, T2, T3, T4, T5, T6, T7, T8)(this As NS1.NS2.Module1.C1) End Sub End Module End Namespace Namespace NS5 Module Module9 &lt;Extension()&gt; Sub Test1(Of T1, T2, T3, T4, T5, T6, T7, T8, T9)(this As NS1.NS2.Module1.C1) End Sub End Module End Namespace Namespace System.Runtime.CompilerServices &lt;AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)&gt; Class ExtensionAttribute Inherits Attribute End Class End Namespace </file> </compilation>, options:=TestOptions.ReleaseExe.WithGlobalImports(GlobalImport.Parse({"NS4.Module7", "NS4"}))) Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="Test1", includeReducedExtensionMethods:=True) Assert.Equal(1, actual_lookupSymbols.Count) Assert.Equal("Sub NS1.NS2.Module1.Test1(Of T1)(this As NS1.NS2.Module1.C1)", actual_lookupSymbols(0).ToTestDisplayString()) Dim c1 = compilation.GetTypeByMetadataName("NS1.NS2.Module1+C1") actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="Test1", container:=c1, includeReducedExtensionMethods:=True) Assert.Equal(8, actual_lookupSymbols.Count) Dim sortedMethodGroup = actual_lookupSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString(), StringComparer.Ordinal).ToArray() Dim expected() As String = {"Sub NS1.NS2.Module1.C1.Test1(Of T1)()", "Sub NS1.NS2.Module1.C1.Test1(Of T1, T2)()", "Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3)()", "Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4)()", "Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4, T5)()", "Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4, T5, T6)()", "Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4, T5, T6, T7)()", "Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4, T5, T6, T7, T8)()"} For i As Integer = 0 To Math.Max(sortedMethodGroup.Length, expected.Length) - 1 Assert.Equal(expected(i), sortedMethodGroup(i).ToTestDisplayString()) Next actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="Test1", container:=c1) Assert.Equal(0, actual_lookupSymbols.Count) actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="Test1", container:=c1, arity:=4, includeReducedExtensionMethods:=True) Assert.Equal(1, actual_lookupSymbols.Count) Assert.Equal("Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4)()", actual_lookupSymbols(0).ToTestDisplayString()) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:="https://github.com/dotnet/roslyn/issues/29531")> Public Sub ExtensionMethodsLookupSymbols6() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System.Console Imports System.Runtime.CompilerServices Imports NS3.Module5 Imports NS3 Namespace NS1 Namespace NS2 Module Module1 Sub Main(Of T)(x as T) x.Test1() 'BIND:"Test1" End Sub &lt;Extension()&gt; Sub Test1(Of T, T1)(this As T) End Sub End Module Module Module2 &lt;Extension()&gt; Sub Test1(Of T, T1, T2)(this As T) End Sub End Module End Namespace Module Module3 &lt;Extension()&gt; Sub Test1(Of T, T1, T2, T3)(this As T) End Sub End Module End Namespace Module Module4 &lt;Extension()&gt; Sub Test1(Of T, T1, T2, T3, T4)(this As T) End Sub End Module Namespace NS3 Module Module5 &lt;Extension()&gt; Sub Test1(Of T, T1, T2, T3, T4, T5)(this As T) End Sub End Module Module Module6 &lt;Extension()&gt; Sub Test1(Of T, T1, T2, T3, T4, T5, T6)(this As T) End Sub End Module End Namespace Namespace NS4 Module Module7 &lt;Extension()&gt; Sub Test1(Of T, T1, T2, T3, T4, T5, T6, T7)(this As T) End Sub End Module Module Module8 &lt;Extension()&gt; Sub Test1(Of T, T1, T2, T3, T4, T5, T6, T7, T8)(this As T) End Sub End Module End Namespace Namespace NS5 Module Module9 &lt;Extension()&gt; Sub Test1(Of T, T1, T2, T3, T4, T5, T6, T7, T8, T9)(this As T) End Sub End Module End Namespace Namespace System.Runtime.CompilerServices &lt;AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)&gt; Class ExtensionAttribute Inherits Attribute End Class End Namespace </file> </compilation>, options:=TestOptions.ReleaseExe.WithGlobalImports(GlobalImport.Parse({"NS4.Module7", "NS4"}))) Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="Test1", includeReducedExtensionMethods:=True) Assert.Equal(1, actual_lookupSymbols.Count) Assert.Equal("Sub NS1.NS2.Module1.Test1(Of T, T1)(this As T)", actual_lookupSymbols(0).ToTestDisplayString()) Dim module1 = compilation.GetTypeByMetadataName("NS1.NS2.Module1") Dim main = DirectCast(module1.GetMember("Main"), MethodSymbol) Dim t = main.TypeParameters(0) actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="Test1", container:=t, includeReducedExtensionMethods:=True) Assert.Equal(8, actual_lookupSymbols.Count) Dim sortedMethodGroup = actual_lookupSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString(), StringComparer.Ordinal).ToArray() Dim expected() As String = {"Sub T.Test1(Of T1)()", "Sub T.Test1(Of T1, T2)()", "Sub T.Test1(Of T1, T2, T3)()", "Sub T.Test1(Of T1, T2, T3, T4)()", "Sub T.Test1(Of T1, T2, T3, T4, T5)()", "Sub T.Test1(Of T1, T2, T3, T4, T5, T6)()", "Sub T.Test1(Of T1, T2, T3, T4, T5, T6, T7)()", "Sub T.Test1(Of T1, T2, T3, T4, T5, T6, T7, T8)()"} For i As Integer = 0 To Math.Max(sortedMethodGroup.Length, expected.Length) - 1 Assert.Equal(expected(i), sortedMethodGroup(i).ToTestDisplayString()) Next actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="Test1", container:=t) Assert.Equal(0, actual_lookupSymbols.Count) actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="Test1", container:=t, arity:=4, includeReducedExtensionMethods:=True) Assert.Equal(1, actual_lookupSymbols.Count) Assert.Equal("Sub T.Test1(Of T1, T2, T3, T4)()", actual_lookupSymbols(0).ToTestDisplayString()) End Sub <Fact> Public Sub ExtensionMethodsLookupSymbols7() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System.Console Imports System.Runtime.CompilerServices Imports NS3.Module5 Imports NS3 Namespace NS1 Namespace NS2 Module Module1 Sub Main() Dim x As New C1() x.Test1() 'BIND:"Test1" End Sub &lt;Extension()&gt; Sub Test1(Of T1)(this As NS1.NS2.Module1.C1) End Sub Class C1 End Class End Module Module Module2 &lt;Extension()&gt; Sub Test2(Of T1, T2)(this As NS1.NS2.Module1.C1) End Sub End Module End Namespace Module Module3 &lt;Extension()&gt; Sub Test3(Of T1, T2, T3)(this As NS1.NS2.Module1.C1) End Sub End Module End Namespace Module Module4 &lt;Extension()&gt; Sub Test4(Of T1, T2, T3, T4)(this As NS1.NS2.Module1.C1) End Sub End Module Namespace NS3 Module Module5 &lt;Extension()&gt; Sub Test5(Of T1, T2, T3, T4, T5)(this As NS1.NS2.Module1.C1) End Sub End Module Module Module6 &lt;Extension()&gt; Sub Test6(Of T1, T2, T3, T4, T5, T6)(this As NS1.NS2.Module1.C1) End Sub End Module End Namespace Namespace NS4 Module Module7 &lt;Extension()&gt; Sub Test7(Of T1, T2, T3, T4, T5, T6, T7)(this As NS1.NS2.Module1.C1) End Sub End Module Module Module8 &lt;Extension()&gt; Sub Test8(Of T1, T2, T3, T4, T5, T6, T7, T8)(this As NS1.NS2.Module1.C1) End Sub End Module End Namespace Namespace NS5 Module Module9 &lt;Extension()&gt; Sub Test9(Of T1, T2, T3, T4, T5, T6, T7, T8, T9)(this As NS1.NS2.Module1.C1) End Sub End Module End Namespace Namespace System.Runtime.CompilerServices &lt;AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)&gt; Class ExtensionAttribute Inherits Attribute End Class End Namespace </file> </compilation>, options:=TestOptions.ReleaseExe.WithGlobalImports(GlobalImport.Parse({"NS4.Module7", "NS4"}))) Dim c1 = compilation.GetTypeByMetadataName("NS1.NS2.Module1+C1") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", container:=c1, includeReducedExtensionMethods:=True) Assert.Equal(14, actual_lookupSymbols.Count) Dim sortedMethodGroup = actual_lookupSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Dim expected() As String = {"Function System.Object.Equals(obj As System.Object) As System.Boolean", "Function System.Object.Equals(objA As System.Object, objB As System.Object) As System.Boolean", "Function System.Object.GetHashCode() As System.Int32", "Function System.Object.GetType() As System.Type", "Function System.Object.ReferenceEquals(objA As System.Object, objB As System.Object) As System.Boolean", "Function System.Object.ToString() As System.String", "Sub NS1.NS2.Module1.C1.Test1(Of T1)()", "Sub NS1.NS2.Module1.C1.Test2(Of T1, T2)()", "Sub NS1.NS2.Module1.C1.Test3(Of T1, T2, T3)()", "Sub NS1.NS2.Module1.C1.Test4(Of T1, T2, T3, T4)()", "Sub NS1.NS2.Module1.C1.Test5(Of T1, T2, T3, T4, T5)()", "Sub NS1.NS2.Module1.C1.Test6(Of T1, T2, T3, T4, T5, T6)()", "Sub NS1.NS2.Module1.C1.Test7(Of T1, T2, T3, T4, T5, T6, T7)()", "Sub NS1.NS2.Module1.C1.Test8(Of T1, T2, T3, T4, T5, T6, T7, T8)()"} For i As Integer = 0 To Math.Max(sortedMethodGroup.Length, expected.Length) - 1 Assert.Equal(expected(i), sortedMethodGroup(i).ToTestDisplayString()) Next actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", container:=c1) Assert.Equal(6, actual_lookupSymbols.Count) sortedMethodGroup = actual_lookupSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() For i As Integer = 0 To sortedMethodGroup.Length - 1 Assert.Equal(expected(i), sortedMethodGroup(i).ToTestDisplayString()) Next actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", container:=c1, name:="Test4", arity:=4, includeReducedExtensionMethods:=True) Assert.Equal(1, actual_lookupSymbols.Count) Assert.Equal("Sub NS1.NS2.Module1.C1.Test4(Of T1, T2, T3, T4)()", actual_lookupSymbols(0).ToTestDisplayString()) End Sub <Fact> Public Sub ExtensionMethodsLookupSymbols8() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System.Console Imports System.Runtime.CompilerServices Imports NS3.Module5 Imports NS3 Namespace NS1 Namespace NS2 Module Module1 Sub Main() End Sub &lt;Extension()&gt; Sub Test1(Of T1)(this As NS1.NS2.Module1.C1) End Sub Class C1 Sub Main() Test1() 'BIND:"Test1" End Sub End Class End Module Module Module2 &lt;Extension()&gt; Sub Test2(Of T1, T2)(this As NS1.NS2.Module1.C1) End Sub End Module End Namespace Module Module3 &lt;Extension()&gt; Sub Test3(Of T1, T2, T3)(this As NS1.NS2.Module1.C1) End Sub End Module End Namespace Module Module4 &lt;Extension()&gt; Sub Test4(Of T1, T2, T3, T4)(this As NS1.NS2.Module1.C1) End Sub End Module Namespace NS3 Module Module5 &lt;Extension()&gt; Sub Test5(Of T1, T2, T3, T4, T5)(this As NS1.NS2.Module1.C1) End Sub End Module Module Module6 &lt;Extension()&gt; Sub Test6(Of T1, T2, T3, T4, T5, T6)(this As NS1.NS2.Module1.C1) End Sub End Module End Namespace Namespace NS4 Module Module7 &lt;Extension()&gt; Sub Test7(Of T1, T2, T3, T4, T5, T6, T7)(this As NS1.NS2.Module1.C1) End Sub End Module Module Module8 &lt;Extension()&gt; Sub Test8(Of T1, T2, T3, T4, T5, T6, T7, T8)(this As NS1.NS2.Module1.C1) End Sub End Module End Namespace Namespace NS5 Module Module9 &lt;Extension()&gt; Sub Test9(Of T1, T2, T3, T4, T5, T6, T7, T8, T9)(this As NS1.NS2.Module1.C1) End Sub End Module End Namespace Namespace System.Runtime.CompilerServices &lt;AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)&gt; Class ExtensionAttribute Inherits Attribute End Class End Namespace </file> </compilation>, options:=TestOptions.ReleaseExe.WithGlobalImports(GlobalImport.Parse({"NS4.Module7", "NS4"}))) Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", includeReducedExtensionMethods:=True) Dim sortedMethodGroup = actual_lookupSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Dim expected() As String = {"Function System.Object.Equals(obj As System.Object) As System.Boolean", "Function System.Object.Equals(objA As System.Object, objB As System.Object) As System.Boolean", "Function System.Object.GetHashCode() As System.Int32", "Function System.Object.GetType() As System.Type", "Function System.Object.ReferenceEquals(objA As System.Object, objB As System.Object) As System.Boolean", "Function System.Object.ToString() As System.String", "Sub NS1.NS2.Module1.C1.Test1(Of T1)()", "Sub NS1.NS2.Module1.C1.Test2(Of T1, T2)()", "Sub NS1.NS2.Module1.C1.Test3(Of T1, T2, T3)()", "Sub NS1.NS2.Module1.C1.Test4(Of T1, T2, T3, T4)()", "Sub NS1.NS2.Module1.C1.Test5(Of T1, T2, T3, T4, T5)()", "Sub NS1.NS2.Module1.C1.Test6(Of T1, T2, T3, T4, T5, T6)()", "Sub NS1.NS2.Module1.C1.Test7(Of T1, T2, T3, T4, T5, T6, T7)()", "Sub NS1.NS2.Module1.C1.Test8(Of T1, T2, T3, T4, T5, T6, T7, T8)()"} Assert.Equal(expected.Length, Aggregate name In expected Join symbol In actual_lookupSymbols On symbol.ToTestDisplayString() Equals name Select name Distinct Into Count()) actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb") Assert.Equal(0, Aggregate symbol In actual_lookupSymbols Join name In expected.Skip(6) On symbol.ToTestDisplayString() Equals name Into Count()) actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="Test4", arity:=4, includeReducedExtensionMethods:=True) Assert.Equal(1, actual_lookupSymbols.Count) Assert.Equal("Sub NS1.NS2.Module1.C1.Test4(Of T1, T2, T3, T4)()", actual_lookupSymbols(0).ToTestDisplayString()) End Sub <Fact> Public Sub ExtensionMethodsLookupSymbols9() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System.Console Imports System.Runtime.CompilerServices Imports NS3.Module5 Imports NS3 Namespace NS1 Namespace NS2 Module Module1 Sub Main() Dim x As C1 = Nothing x.Test1() 'BIND:"Test1" End Sub &lt;Extension()&gt; Sub Test1(Of T1)(this As NS1.NS2.Module1.C1) End Sub Interface C1 End Interface End Module Module Module2 &lt;Extension()&gt; Sub Test2(Of T1, T2)(this As NS1.NS2.Module1.C1) End Sub End Module End Namespace Module Module3 &lt;Extension()&gt; Sub Test3(Of T1, T2, T3)(this As NS1.NS2.Module1.C1) End Sub End Module End Namespace Module Module4 &lt;Extension()&gt; Sub Test4(Of T1, T2, T3, T4)(this As NS1.NS2.Module1.C1) End Sub End Module Namespace NS3 Module Module5 &lt;Extension()&gt; Sub Test5(Of T1, T2, T3, T4, T5)(this As NS1.NS2.Module1.C1) End Sub End Module Module Module6 &lt;Extension()&gt; Sub Test6(Of T1, T2, T3, T4, T5, T6)(this As NS1.NS2.Module1.C1) End Sub End Module End Namespace Namespace NS4 Module Module7 &lt;Extension()&gt; Sub Test7(Of T1, T2, T3, T4, T5, T6, T7)(this As NS1.NS2.Module1.C1) End Sub End Module Module Module8 &lt;Extension()&gt; Sub Test8(Of T1, T2, T3, T4, T5, T6, T7, T8)(this As NS1.NS2.Module1.C1) End Sub End Module End Namespace Namespace NS5 Module Module9 &lt;Extension()&gt; Sub Test9(Of T1, T2, T3, T4, T5, T6, T7, T8, T9)(this As NS1.NS2.Module1.C1) End Sub End Module End Namespace Namespace System.Runtime.CompilerServices &lt;AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)&gt; Class ExtensionAttribute Inherits Attribute End Class End Namespace </file> </compilation>, options:=TestOptions.ReleaseExe.WithGlobalImports(GlobalImport.Parse({"NS4.Module7", "NS4"}))) Dim c1 = compilation.GetTypeByMetadataName("NS1.NS2.Module1+C1") Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", container:=c1, includeReducedExtensionMethods:=True) Dim expected() As String = {"Sub NS1.NS2.Module1.C1.Test1(Of T1)()", "Sub NS1.NS2.Module1.C1.Test2(Of T1, T2)()", "Sub NS1.NS2.Module1.C1.Test3(Of T1, T2, T3)()", "Sub NS1.NS2.Module1.C1.Test4(Of T1, T2, T3, T4)()", "Sub NS1.NS2.Module1.C1.Test5(Of T1, T2, T3, T4, T5)()", "Sub NS1.NS2.Module1.C1.Test6(Of T1, T2, T3, T4, T5, T6)()", "Sub NS1.NS2.Module1.C1.Test7(Of T1, T2, T3, T4, T5, T6, T7)()", "Sub NS1.NS2.Module1.C1.Test8(Of T1, T2, T3, T4, T5, T6, T7, T8)()"} Assert.Equal(expected.Length, Aggregate name In expected Join symbol In actual_lookupSymbols On symbol.ToTestDisplayString() Equals name Select name Distinct Into Count()) actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", container:=c1) Assert.Equal(0, Aggregate name In expected Join symbol In actual_lookupSymbols On symbol.ToTestDisplayString() Equals name Select name Distinct Into Count()) actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", container:=c1, name:="Test4", arity:=4, includeReducedExtensionMethods:=True) Assert.Equal(1, actual_lookupSymbols.Count) Assert.Equal("Sub NS1.NS2.Module1.C1.Test4(Of T1, T2, T3, T4)()", actual_lookupSymbols(0).ToTestDisplayString()) End Sub <Fact> Public Sub ExtensionMethodsLookupSymbols10() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System.Console Imports System.Runtime.CompilerServices Imports NS3.Module5 Imports NS3 Namespace NS1 Namespace NS2 Module Module1 Sub Main(Of T)(x as T) x.Test1() 'BIND:"Test1" End Sub &lt;Extension()&gt; Sub Test1(Of T, T1)(this As T) End Sub End Module Module Module2 &lt;Extension()&gt; Sub Test2(Of T, T1, T2)(this As T) End Sub End Module End Namespace Module Module3 &lt;Extension()&gt; Sub Test3(Of T, T1, T2, T3)(this As T) End Sub End Module End Namespace Module Module4 &lt;Extension()&gt; Sub Test4(Of T, T1, T2, T3, T4)(this As T) End Sub End Module Namespace NS3 Module Module5 &lt;Extension()&gt; Sub Test5(Of T, T1, T2, T3, T4, T5)(this As T) End Sub End Module Module Module6 &lt;Extension()&gt; Sub Test6(Of T, T1, T2, T3, T4, T5, T6)(this As T) End Sub End Module End Namespace Namespace NS4 Module Module7 &lt;Extension()&gt; Sub Test7(Of T, T1, T2, T3, T4, T5, T6, T7)(this As T) End Sub End Module Module Module8 &lt;Extension()&gt; Sub Test8(Of T, T1, T2, T3, T4, T5, T6, T7, T8)(this As T) End Sub End Module End Namespace Namespace NS5 Module Module9 &lt;Extension()&gt; Sub Test9(Of T, T1, T2, T3, T4, T5, T6, T7, T8, T9)(this As T) End Sub End Module End Namespace Namespace System.Runtime.CompilerServices &lt;AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)&gt; Class ExtensionAttribute Inherits Attribute End Class End Namespace </file> </compilation>, options:=TestOptions.ReleaseExe.WithGlobalImports(GlobalImport.Parse({"NS4.Module7", "NS4"}))) Dim module1 = compilation.GetTypeByMetadataName("NS1.NS2.Module1") Dim main = DirectCast(module1.GetMember("Main"), MethodSymbol) Dim t = main.TypeParameters(0) Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", container:=t, includeReducedExtensionMethods:=True) Dim expected() As String = {"Sub T.Test1(Of T1)()", "Sub T.Test2(Of T1, T2)()", "Sub T.Test3(Of T1, T2, T3)()", "Sub T.Test4(Of T1, T2, T3, T4)()", "Sub T.Test5(Of T1, T2, T3, T4, T5)()", "Sub T.Test6(Of T1, T2, T3, T4, T5, T6)()", "Sub T.Test7(Of T1, T2, T3, T4, T5, T6, T7)()", "Sub T.Test8(Of T1, T2, T3, T4, T5, T6, T7, T8)()"} Assert.Equal(expected.Length, Aggregate name In expected Join symbol In actual_lookupSymbols On symbol.ToTestDisplayString() Equals name Select name Distinct Into Count()) actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", container:=t, includeReducedExtensionMethods:=False) Assert.Equal(0, Aggregate name In expected Join symbol In actual_lookupSymbols On symbol.ToTestDisplayString() Equals name Select name Distinct Into Count()) actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", container:=t, name:="Test4", arity:=4, includeReducedExtensionMethods:=True) Assert.Equal(1, actual_lookupSymbols.Count) Assert.Equal("Sub T.Test4(Of T1, T2, T3, T4)()", actual_lookupSymbols(0).ToTestDisplayString()) End Sub <Fact> Public Sub Bug8942_1() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System Imports System.Runtime.CompilerServices Module M &lt;Extension()&gt; Sub Goo(x As Exception) End Sub End Module Class E Inherits Exception Sub Bar() Me.Goo() 'BIND:"Goo" End Sub End Class Namespace System.Runtime.CompilerServices &lt;AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)&gt; Class ExtensionAttribute Inherits Attribute End Class End Namespace </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticInfo.Type) Assert.Null(semanticInfo.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Sub System.Exception.Goo()", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(1, semanticInfo.MemberGroup.Length) Dim sortedMethodGroup = semanticInfo.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub System.Exception.Goo()", sortedMethodGroup(0).ToTestDisplayString()) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact> Public Sub Bug8942_2() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System Imports System.Runtime.CompilerServices Module M &lt;Extension()&gt; Sub Goo(x As Exception) End Sub End Module Class E Inherits Exception Sub Bar() Goo() 'BIND:"Goo" End Sub End Class Namespace System.Runtime.CompilerServices &lt;AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)&gt; Class ExtensionAttribute Inherits Attribute End Class End Namespace </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticInfo.Type) Assert.Null(semanticInfo.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Sub System.Exception.Goo()", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(1, semanticInfo.MemberGroup.Length) Dim sortedMethodGroup = semanticInfo.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub System.Exception.Goo()", sortedMethodGroup(0).ToTestDisplayString()) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <WorkItem(544933, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544933")> <Fact> Public Sub LookupSymbolsGenericExtensionMethodWithConstraints() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="a.vb"><![CDATA[ Imports System.Runtime.CompilerServices Class A End Class Class B End Class Module E Sub M(_a As A, _b As B) _a.F() _b.F() End Sub <Extension()> Sub F(Of T As A)(o As T) End Sub End Module ]]></file> </compilation>, {TestMetadata.Net40.SystemCore}) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC30456: 'F' is not a member of 'B'. _b.F() ~~~~ ]]></errors>) Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim position = FindNodeFromText(tree, "_a.F()").SpanStart Dim method = compilation.GlobalNamespace.GetMember(Of NamedTypeSymbol)("E").GetMember(Of MethodSymbol)("M") ' No type. Dim symbols = model.LookupSymbols(position, container:=Nothing, name:="F", includeReducedExtensionMethods:=True) CheckSymbols(symbols, "Sub E.F(Of T)(o As T)") ' Type satisfying constraints. symbols = model.LookupSymbols(position, container:=method.Parameters(0).Type, name:="F", includeReducedExtensionMethods:=True) CheckSymbols(symbols, "Sub A.F()") ' Type not satisfying constraints. symbols = model.LookupSymbols(position, container:=method.Parameters(1).Type, name:="F", includeReducedExtensionMethods:=True) CheckSymbols(symbols) End Sub <Fact, WorkItem(963125, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/963125")> Public Sub Bug963125() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports alias2 = System Module Module1 Sub Main() alias1.Console.WriteLine() alias2.Console.WriteLine() End Sub End Module </file> </compilation>, options:=TestOptions.ReleaseExe.WithGlobalImports(GlobalImport.Parse({"alias1 = System"}))) compilation.AssertNoDiagnostics() Dim tree = compilation.SyntaxTrees.Single() Dim model = compilation.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes().OfType(Of IdentifierNameSyntax)().Where(Function(n) n.Identifier.ValueText = "alias1").Single() Dim alias1 = model.GetAliasInfo(node1) Assert.Equal("alias1=System", alias1.ToTestDisplayString()) Assert.Equal(LocationKind.None, alias1.Locations.Single().Kind) Dim node2 = tree.GetRoot().DescendantNodes().OfType(Of IdentifierNameSyntax)().Where(Function(n) n.Identifier.ValueText = "alias2").Single() Dim alias2 = model.GetAliasInfo(node2) Assert.Equal("alias2=System", alias2.ToTestDisplayString()) Assert.Equal(LocationKind.SourceFile, alias2.Locations.Single().Kind) End Sub End Class End Namespace
1
dotnet/roslyn
56,011
React to string comparison changing on .NET Core
The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
jaredpar
"2021-08-30T17:18:52Z"
"2021-08-30T20:20:04Z"
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
4d99cda6e446e77dbb302e26388c1093bd3ef569
React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
./src/Compilers/VisualBasic/Test/Semantic/Semantics/GetExtendedSemanticInfoTests.vb
' 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.IO Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.SpecialType Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.OverloadResolution Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Partial Public Class GetExtendedSemanticInfoTests : Inherits SemanticModelTestBase <Fact> Public Sub LambdaInInitializer() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C Private Shared AmbiguousInNSError As Func(Of C, D) = Function(syms As C) As D If C IsNot Nothing Return New D()'BIND:"D" Else Return New D() End If End Function End Class </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") 'simply not crashing is the goal for now. End Sub <Fact> Public Sub BindLambdasInArgsOfBadParent() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> 'note that T is not defined which causes the object creation expression 'to be bad. This test ensures that the arguments are still bound and analyzable. Module M Private Shared Function Meth() As T Return New T(Function() String.Empty)'BIND:"String" End Function End Module </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of PredefinedTypeSyntax)(compilation, "a.vb") 'not crashing End Sub <Fact> Public Sub RunningAfoulOfExtensions() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System.Runtime.CompilerServices Imports System.Linq.Expressions Module M Private Shared Function GetExpressionType(x As Symbol) As TypeSymbol Select Case x.Kind Case Else Dim type = TryCast(x, TypeSymbol)'BIND:"x" If type IsNot Nothing Then Return type End If End Select Return Nothing End Function &lt;Extension()&gt; Sub Type(ByVal x As Integer) End Sub &lt;Extension()&gt; Sub Type(x As String) End Sub End Module </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") 'not crashing End Sub <Fact> Public Sub BindPredefinedTypeOutsideMethodBody() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String())'BIND:"String" End Sub End Module </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of PredefinedTypeSyntax)(compilation, "a.vb") Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("System.String", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact> Public Sub BindPredefinedTypeInsideMethodBody() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Dim x = String.Empty 'BIND:"String" End Sub End Module </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of PredefinedTypeSyntax)(compilation, "a.vb") Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("System.String", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact> Public Sub ConvertedLocal() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Dim x As Integer Dim y As Long y = x'BIND:"x" End Sub End Module </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int64", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.WideningNumeric, semanticInfo.ImplicitConversion.Kind) Assert.Equal("x As System.Int32", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact> Public Sub InaccessibleType1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System Module Program Dim a As A.B'BIND:"B" Sub Main(args As String()) End Sub End Module Class A Private Class B Public Sub f() End Sub End Class End Class </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("A.B", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("A.B", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason) Assert.Equal(1, semanticInfo.CandidateSymbols.Length) Dim sortedCandidates = semanticInfo.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("A.B", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, sortedCandidates(0).Kind) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact> Public Sub InaccessibleType2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System Module Program Sub Main(args As String()) A.B.f()'BIND:"B" End Sub End Module Class A Private Class B Public Sub f() End Sub End Class End Class </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("A.B", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("A.B", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason) Assert.Equal(1, semanticInfo.CandidateSymbols.Length) Dim sortedCandidates = semanticInfo.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("A.B", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, sortedCandidates(0).Kind) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact> Public Sub InaccessibleType3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System Module Program Sub Main(args As String()) Dim z As A.B'BIND:"B" End Sub End Module Class A Private Class B Public Sub f() End Sub End Class End Class </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("A.B", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("A.B", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason) Assert.Equal(1, semanticInfo.CandidateSymbols.Length) Dim sortedCandidates = semanticInfo.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("A.B", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, sortedCandidates(0).Kind) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact> Public Sub AmbiguousType1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System Imports N1, N2 Module Program Dim x As A'BIND:"A" Sub Main(args As String()) End Sub End Module Namespace N1 Class A End Class End Namespace Namespace N2 Class A End Class End Namespace </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("A", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind) Assert.Equal("A", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.Ambiguous, semanticInfo.CandidateReason) Assert.Equal(2, semanticInfo.CandidateSymbols.Length) Dim sortedCandidates = semanticInfo.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("N1.A", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, sortedCandidates(0).Kind) Assert.Equal("N2.A", sortedCandidates(1).ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, sortedCandidates(1).Kind) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact> Public Sub AmbiguousType2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System Imports N1, N2 Module Program Sub Main(args As String()) Dim x As A'BIND:"A" End Sub End Module Namespace N1 Class A End Class End Namespace Namespace N2 Class A End Class End Namespace </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("A", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind) Assert.Equal("A", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.Ambiguous, semanticInfo.CandidateReason) Assert.Equal(2, semanticInfo.CandidateSymbols.Length) Dim sortedCandidates = semanticInfo.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("N1.A", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, sortedCandidates(0).Kind) Assert.Equal("N2.A", sortedCandidates(1).ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, sortedCandidates(1).Kind) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact> Public Sub AmbiguousType3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System Imports N1, N2 Module Program Sub Main(args As String()) A.goo()'BIND:"A" End Sub End Module Namespace N1 Class A End Class End Namespace Namespace N2 Class A End Class End Namespace </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("A", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind) Assert.Equal("A", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.Ambiguous, semanticInfo.CandidateReason) Assert.Equal(2, semanticInfo.CandidateSymbols.Length) Dim sortedCandidates = semanticInfo.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("N1.A", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, sortedCandidates(0).Kind) Assert.Equal("N2.A", sortedCandidates(1).ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, sortedCandidates(1).Kind) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact> Public Sub InaccessibleSharedField() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System Module Program Sub Main(args As String()) Dim z As Integer = A.fi'BIND:"fi" End Sub End Module Class A Private Shared fi As Integer End Class </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason) Assert.Equal(1, semanticInfo.CandidateSymbols.Length) Dim sortedCandidates = semanticInfo.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("A.fi As System.Int32", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.Field, sortedCandidates(0).Kind) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact> Public Sub MethodGroup1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System Module Program Sub Main(args As String()) f(3)'BIND:"f" End Sub Sub f() End Sub Sub f(x As Integer) End Sub Function f(ByVal a As Integer, b As Long) As String Return "hi" End Function End Module </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticInfo.Type) Assert.Null(semanticInfo.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Sub Program.f(x As System.Int32)", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(3, semanticInfo.MemberGroup.Length) Dim sortedMethodGroup = semanticInfo.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Function Program.f(a As System.Int32, b As System.Int64) As System.String", sortedMethodGroup(0).ToTestDisplayString()) Assert.Equal("Sub Program.f()", sortedMethodGroup(1).ToTestDisplayString()) Assert.Equal("Sub Program.f(x As System.Int32)", sortedMethodGroup(2).ToTestDisplayString()) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact> Public Sub MethodGroup2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System Module Program Sub Main(args As String()) Dim x As New Class1() x.f(3, 7)'BIND:"x.f" End Sub End Module Class Class1 Public Sub f() End Sub Public Sub f(x As Integer) End Sub Public Function f(ByVal a As Integer, b As Long) As String Return "hi" End Function End Class </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of MemberAccessExpressionSyntax)(compilation, "a.vb") Assert.Null(semanticInfo.Type) Assert.Null(semanticInfo.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Function Class1.f(a As System.Int32, b As System.Int64) As System.String", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(3, semanticInfo.MemberGroup.Length) Dim sortedMethodGroup = semanticInfo.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Function Class1.f(a As System.Int32, b As System.Int64) As System.String", sortedMethodGroup(0).ToTestDisplayString()) Assert.Equal("Sub Class1.f()", sortedMethodGroup(1).ToTestDisplayString()) Assert.Equal("Sub Class1.f(x As System.Int32)", sortedMethodGroup(2).ToTestDisplayString()) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact> Public Sub InaccessibleMethodGroup() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System Module Program Sub Main(args As String()) Dim x As New Class1() x.f(3, 7)'BIND:"x.f" End Sub End Module Class Class1 Protected Sub f() End Sub Protected Sub f(x As Integer) End Sub Private Function f(ByVal a As Integer, b As Long) As String Return "hi" End Function End Class </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of MemberAccessExpressionSyntax)(compilation, "a.vb") ' This test should return all three inaccessible methods. I am ' leaving it in so it doesn't regress further, but it should be ' better. Assert.Null(semanticInfo.Type) Assert.Null(semanticInfo.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason) Assert.Equal(1, semanticInfo.CandidateSymbols.Length) Dim sortedCandidates = semanticInfo.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Function Class1.f(a As System.Int32, b As System.Int64) As System.String", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(0).Kind) Assert.Equal(3, semanticInfo.MemberGroup.Length) Dim sortedMethodGroup = semanticInfo.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Function Class1.f(a As System.Int32, b As System.Int64) As System.String", sortedMethodGroup(0).ToTestDisplayString()) Assert.Equal("Sub Class1.f()", sortedMethodGroup(1).ToTestDisplayString()) Assert.Equal("Sub Class1.f(x As System.Int32)", sortedMethodGroup(2).ToTestDisplayString()) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact> Public Sub InaccessibleMethodGroup_Constructors_ObjectCreationExpressionSyntax() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Module Program Sub Main(args As String()) Dim x As New Class1(3, 7)'BIND:"New Class1(3, 7)" End Sub End Module Class Class1 Protected Sub New() End Sub Protected Sub New(x As Integer) End Sub Private Sub New(ByVal a As Integer, b As Long) End Sub End Class ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of ObjectCreationExpressionSyntax)(compilation, "a.vb") Assert.Equal("Class1", semanticSummary.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.Type.TypeKind) Assert.Equal("Class1", semanticSummary.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Null(semanticSummary.Symbol) Assert.Equal(CandidateReason.Inaccessible, semanticSummary.CandidateReason) Assert.Equal(1, semanticSummary.CandidateSymbols.Length) Assert.Equal("Sub Class1..ctor(a As System.Int32, b As System.Int64)", semanticSummary.CandidateSymbols(0).ToTestDisplayString()) Assert.Null(semanticSummary.Alias) Assert.Equal(3, semanticSummary.MemberGroup.Length) Dim sortedMethodGroup = semanticSummary.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub Class1..ctor()", sortedMethodGroup(0).ToTestDisplayString()) Assert.Equal("Sub Class1..ctor(a As System.Int32, b As System.Int64)", sortedMethodGroup(1).ToTestDisplayString()) Assert.Equal("Sub Class1..ctor(x As System.Int32)", sortedMethodGroup(2).ToTestDisplayString()) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact> Public Sub InaccessibleMethodGroup_Constructors_IdentifierNameSyntax() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Module Program Sub Main(args As String()) Dim x As New Class1(3, 7)'BIND:"Class1" End Sub End Module Class Class1 Protected Sub New() End Sub Protected Sub New(x As Integer) End Sub Private Sub New(ByVal a As Integer, b As Long) End Sub End Class ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticSummary.Type) Assert.Null(semanticSummary.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Equal("Class1", semanticSummary.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, semanticSummary.CandidateReason) Assert.Equal(0, semanticSummary.CandidateSymbols.Length) Assert.Null(semanticSummary.Alias) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact> Public Sub InaccessibleMethodGroup_AttributeSyntax() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Module Program <Class1(3, 7)>'BIND:"Class1(3, 7)" Sub Main(args As String()) End Sub End Module Class Class1 Inherits Attribute Protected Sub New() End Sub Protected Sub New(x As Integer) End Sub Private Sub New(ByVal a As Integer, b As Long) End Sub End Class ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of AttributeSyntax)(compilation, "a.vb") Assert.Equal("Class1", semanticSummary.Type.ToTestDisplayString()) Assert.Equal(TypeKind.[Class], semanticSummary.Type.TypeKind) Assert.Equal("Class1", semanticSummary.ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Null(semanticSummary.Symbol) Assert.Equal(CandidateReason.Inaccessible, semanticSummary.CandidateReason) Assert.Equal(3, semanticSummary.CandidateSymbols.Length) Dim sortedCandidates = semanticSummary.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub Class1..ctor()", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(0).Kind) Assert.Equal("Sub Class1..ctor(a As System.Int32, b As System.Int64)", sortedCandidates(1).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(1).Kind) Assert.Equal("Sub Class1..ctor(x As System.Int32)", sortedCandidates(2).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(2).Kind) Assert.Null(semanticSummary.Alias) Assert.Equal(3, semanticSummary.MemberGroup.Length) Dim sortedMethodGroup = semanticSummary.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub Class1..ctor()", sortedMethodGroup(0).ToTestDisplayString()) Assert.Equal("Sub Class1..ctor(a As System.Int32, b As System.Int64)", sortedMethodGroup(1).ToTestDisplayString()) Assert.Equal("Sub Class1..ctor(x As System.Int32)", sortedMethodGroup(2).ToTestDisplayString()) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact> Public Sub InaccessibleMethodGroup_Attribute_IdentifierNameSyntax() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Module Program <Class1(3, 7)>'BIND:"Class1" Sub Main(args As String()) End Sub End Module Class Class1 Inherits Attribute Protected Sub New() End Sub Protected Sub New(x As Integer) End Sub Private Sub New(ByVal a As Integer, b As Long) End Sub End Class ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("Class1", semanticSummary.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.Type.TypeKind) Assert.Equal("Class1", semanticSummary.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Null(semanticSummary.Symbol) Assert.Equal(CandidateReason.Inaccessible, semanticSummary.CandidateReason) Assert.Equal(3, semanticSummary.CandidateSymbols.Length) Dim sortedCandidates = semanticSummary.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub Class1..ctor()", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(0).Kind) Assert.Equal("Sub Class1..ctor(a As System.Int32, b As System.Int64)", sortedCandidates(1).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(1).Kind) Assert.Equal("Sub Class1..ctor(x As System.Int32)", sortedCandidates(2).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(2).Kind) Assert.Null(semanticSummary.Alias) Assert.Equal(3, semanticSummary.MemberGroup.Length) Dim sortedMethodGroup = semanticSummary.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub Class1..ctor()", sortedMethodGroup(0).ToTestDisplayString()) Assert.Equal("Sub Class1..ctor(a As System.Int32, b As System.Int64)", sortedMethodGroup(1).ToTestDisplayString()) Assert.Equal("Sub Class1..ctor(x As System.Int32)", sortedMethodGroup(2).ToTestDisplayString()) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact> Public Sub InaccessibleConstructorsFiltered_ObjectCreationExpressionSyntax() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Module Program Sub Main(args As String()) Dim x As New Class1(3, 7)'BIND:"New Class1(3, 7)" End Sub End Module Class Class1 Protected Sub New() End Sub Public Sub New(x As Integer) End Sub Public Sub New(ByVal a As Integer, b As Long) End Sub End Class ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of ObjectCreationExpressionSyntax)(compilation, "a.vb") Assert.Equal("Class1", semanticSummary.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.Type.TypeKind) Assert.Equal("Class1", semanticSummary.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Equal("Sub Class1..ctor(a As System.Int32, b As System.Int64)", semanticSummary.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Method, semanticSummary.Symbol.Kind) Assert.Equal(0, semanticSummary.CandidateSymbols.Length) Assert.Null(semanticSummary.Alias) Assert.Equal(2, semanticSummary.MemberGroup.Length) Dim sortedMethodGroup = semanticSummary.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub Class1..ctor(a As System.Int32, b As System.Int64)", sortedMethodGroup(0).ToTestDisplayString()) Assert.Equal("Sub Class1..ctor(x As System.Int32)", sortedMethodGroup(1).ToTestDisplayString()) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact> Public Sub InaccessibleConstructorsFiltered_IdentifierNameSyntax() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Module Program Sub Main(args As String()) Dim x As New Class1(3, 7)'BIND:"Class1" End Sub End Module Class Class1 Protected Sub New() End Sub Public Sub New(x As Integer) End Sub Public Sub New(ByVal a As Integer, b As Long) End Sub End Class ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticSummary.Type) Assert.Null(semanticSummary.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Equal("Class1", semanticSummary.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, semanticSummary.Symbol.Kind) Assert.Equal(0, semanticSummary.CandidateSymbols.Length) Assert.Null(semanticSummary.Alias) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact> Public Sub InaccessibleConstructorsFiltered_IdentifierNameSyntax2() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Module Program Sub Main(args As String()) Dim x As New Class1(3, 7)'BIND:"New Class1(3, 7)" End Sub End Module Class Class1 Protected Sub New() End Sub Public Sub New(x As Integer) End Sub Public Sub New(ByVal a As Integer, b As Long) End Sub End Class ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of ObjectCreationExpressionSyntax)(compilation, "a.vb") Assert.Equal("Class1", semanticSummary.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.Type.TypeKind) Assert.Equal("Class1", semanticSummary.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Equal("Sub Class1..ctor(a As System.Int32, b As System.Int64)", semanticSummary.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Method, semanticSummary.Symbol.Kind) Assert.Equal(0, semanticSummary.CandidateSymbols.Length) Assert.Null(semanticSummary.Alias) Assert.Equal(2, semanticSummary.MemberGroup.Length) Dim sortedMethodGroup = semanticSummary.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub Class1..ctor(a As System.Int32, b As System.Int64)", sortedMethodGroup(0).ToTestDisplayString()) Assert.Equal("Sub Class1..ctor(x As System.Int32)", sortedMethodGroup(1).ToTestDisplayString()) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact> Public Sub InaccessibleConstructorsFiltered_AttributeSyntax() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Module Program <Class1(3, 7)>'BIND:"Class1(3, 7)" Sub Main(args As String()) End Sub End Module Class Class1 Inherits Attribute Protected Sub New() End Sub Public Sub New(x As Integer) End Sub Public Sub New(ByVal a As Integer, b As Long) End Sub End Class ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of AttributeSyntax)(compilation, "a.vb") Assert.Equal("Class1", semanticSummary.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.Type.TypeKind) Assert.Equal("Class1", semanticSummary.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Equal("Sub Class1..ctor(a As System.Int32, b As System.Int64)", semanticSummary.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Method, semanticSummary.Symbol.Kind) Assert.Equal(0, semanticSummary.CandidateSymbols.Length) Assert.Null(semanticSummary.Alias) Assert.Equal(2, semanticSummary.MemberGroup.Length) Dim sortedMethodGroup = semanticSummary.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub Class1..ctor(a As System.Int32, b As System.Int64)", sortedMethodGroup(0).ToTestDisplayString()) Assert.Equal("Sub Class1..ctor(x As System.Int32)", sortedMethodGroup(1).ToTestDisplayString()) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact> Public Sub InaccessibleConstructorsFiltered_Attribute_IdentifierNameSyntax() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Module Program <Class1(3, 7)>'BIND:"Class1" Sub Main(args As String()) End Sub End Module Class Class1 Inherits Attribute Protected Sub New() End Sub Public Sub New(x As Integer) End Sub Public Sub New(ByVal a As Integer, b As Long) End Sub End Class ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("Class1", semanticSummary.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.Type.TypeKind) Assert.Equal("Class1", semanticSummary.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Equal("Sub Class1..ctor(a As System.Int32, b As System.Int64)", semanticSummary.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Method, semanticSummary.Symbol.Kind) Assert.Equal(0, semanticSummary.CandidateSymbols.Length) Assert.Null(semanticSummary.Alias) Assert.Equal(2, semanticSummary.MemberGroup.Length) Dim sortedMethodGroup = semanticSummary.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub Class1..ctor(a As System.Int32, b As System.Int64)", sortedMethodGroup(0).ToTestDisplayString()) Assert.Equal("Sub Class1..ctor(x As System.Int32)", sortedMethodGroup(1).ToTestDisplayString()) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact> Public Sub Invocation1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System Module Program Sub Main(args As String()) f(3, 7)'BIND:"f(3, 7)" End Sub Sub f() End Sub Sub f(x As Integer) End Sub Function f(ByVal a As Integer, b As Long) As String Return "hi" End Function End Module </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of InvocationExpressionSyntax)(compilation, "a.vb") Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Function Program.f(a As System.Int32, b As System.Int64) As System.String", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact> Public Sub Invocation2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System Module Program Sub Main(args As String()) Dim x As New Class1() x.f(3, 7)'BIND:"x.f(3, 7)" End Sub End Module Class Class1 Public Sub f() End Sub Public Sub f(x As Integer) End Sub Public Function f(ByVal a As Integer, b As Long) As String Return "hi" End Function End Class </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of InvocationExpressionSyntax)(compilation, "a.vb") Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Function Class1.f(a As System.Int32, b As System.Int64) As System.String", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact> Public Sub InaccessibleInvocation() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System Module Program Sub Main(args As String()) Dim x As New Class1() x.f(3, 7)'BIND:"x.f(3, 7)" End Sub End Module Class Class1 Protected Sub f() End Sub Protected Sub f(x As Integer) End Sub Private Function f(ByVal a As Integer, b As Long) As String Return "hi" End Function End Class </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of InvocationExpressionSyntax)(compilation, "a.vb") Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason) Assert.Equal(1, semanticInfo.CandidateSymbols.Length) Dim sortedCandidates = semanticInfo.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Function Class1.f(a As System.Int32, b As System.Int64) As System.String", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(0).Kind) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact> Public Sub Property1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Dim a As New X a.Prop = 4'BIND:"Prop" End Sub End Module Class X Public Property Prop As String Get Return "" End Get Set End Set End Property End Class </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Property X.Prop As System.String", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Property, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact> Public Sub Property2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Dim a As New X Dim u As String = a.Prop'BIND:"a.Prop" End Sub End Module Class X Public Property Prop As String Get Return "" End Get Set End Set End Property End Class </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of MemberAccessExpressionSyntax)(compilation, "a.vb") Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Property X.Prop As System.String", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Property, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact> Public Sub SimpleConstantExpression() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Dim i As Integer = 10 * 10'BIND:"10 * 10" End Sub End Module Class X End Class </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of BinaryExpressionSyntax)(compilation, "a.vb") Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Function System.Int32.op_Multiply(left As System.Int32, right As System.Int32) As System.Int32", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.True(semanticInfo.ConstantValue.HasValue) Assert.Equal(100, semanticInfo.ConstantValue.Value) End Sub <Fact> Public Sub InaccessibleParameter() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub goo(a As Outer.Inner) Dim q As Integer q = a.x'BIND:"a" End Sub End Module Class Outer Private Class Inner Public x As Integer End Class End Class </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("Outer.Inner", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("Outer.Inner", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("a As Outer.Inner", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Parameter, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim paramSym As ParameterSymbol = DirectCast(semanticInfo.Symbol, ParameterSymbol) Assert.Equal(TypeKind.Error, paramSym.Type.TypeKind) End Sub <WorkItem(538447, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538447")> <Fact> Public Sub CastInterfaceToArray() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim i As ICloneable = New Integer() {} Dim arr() As Integer arr = CType(i, Integer())'BIND:"CType(i, Integer())" arr = DirectCast(i, Integer()) arr = TryCast(i, Integer()) End Sub End Module </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of CastExpressionSyntax)(compilation, "a.vb") Assert.Equal("System.Int32()", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Array, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32()", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Array, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact> Public Sub ImplementsClause1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Interface IA(Of T) Overloads Sub Goo(ByVal x As T) Overloads Sub Goo(ByVal x As String) End Interface Interface IC(Of T) Inherits IA(Of T) End Interface Interface IB Overloads Sub Bar(x As String) ReadOnly Property P As Long Property R(x As String) As Long End Interface Class K Implements IC(Of Integer) Implements IB Public Overloads Sub F(x As String) Implements IB.Bar, IC(Of Integer).Goo 'BIND1:"IB.Bar" 'BIND2:"Goo" End Sub Public Overloads Sub F(x As Integer) Implements IA(Of Integer).Goo 'BIND3:"IA(Of Integer).Goo" End Sub Public Property Q(x As String) As Long Implements IB.R 'BIND4:"IB.R" Get Return 0 End Get Set End Set End Property Public Property Q As Long Implements IB.P 'BIND5:"IB" Get Return 0 End Get Set End Set End Property End Class </file> </compilation>) 'IB.Bar Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of QualifiedNameSyntax)(compilation, "a.vb", 1) Assert.Null(semanticInfo.Type) Assert.Null(semanticInfo.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Sub IB.Bar(x As System.String)", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) 'Goo semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb", 2) Assert.Null(semanticInfo.Type) Assert.Null(semanticInfo.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Sub IA(Of System.Int32).Goo(x As System.String)", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) ' IA(Of Integer).Goo semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of QualifiedNameSyntax)(compilation, "a.vb", 3) Assert.Null(semanticInfo.Type) Assert.Null(semanticInfo.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Sub IA(Of System.Int32).Goo(x As System.Int32)", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) ' IB.R semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of QualifiedNameSyntax)(compilation, "a.vb", 4) Assert.Null(semanticInfo.Type) Assert.Null(semanticInfo.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Property IB.R(x As System.String) As System.Int64", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Property, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) ' IB semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb", 5) Assert.Equal("IB", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Interface, semanticInfo.Type.TypeKind) Assert.Equal("IB", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Interface, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("IB", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact> Public Sub ImplementsClause2() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports System Interface I1 Sub goo(x As Integer) End Interface Class C1 Implements I1 Public Function goo(x As Integer) As String Implements I1.goo'BIND:"I1.goo" Throw New NotImplementedException() End Function End Class ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of QualifiedNameSyntax)(compilation, "a.vb") Assert.Null(semanticSummary.Type) Assert.Null(semanticSummary.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Null(semanticSummary.Symbol) Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticSummary.CandidateReason) Assert.Equal(1, semanticSummary.CandidateSymbols.Length) Dim sortedCandidates = semanticSummary.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub I1.goo(x As System.Int32)", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(0).Kind) Assert.Null(semanticSummary.Alias) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:="https://github.com/dotnet/roslyn/issues/29531")> Public Sub ImplementsClause3() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports System Interface I1 Sub goo(x As Integer) Sub goo(x As Integer, y As Integer) End Interface Class C1 Implements I1 Public Sub goo(x As Long) Implements I1.goo'BIND:"I1.goo" Throw New NotImplementedException() End Sub End Class ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of QualifiedNameSyntax)(compilation, "a.vb") Assert.Null(semanticSummary.Type) Assert.Null(semanticSummary.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Null(semanticSummary.Symbol) Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticSummary.CandidateReason) Assert.Equal(2, semanticSummary.CandidateSymbols.Length) Dim sortedCandidates = semanticSummary.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub I1.goo(x As System.Int32)", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(0).Kind) Assert.Equal("Sub I1.goo(x As System.Int32, y As System.Int32)", sortedCandidates(1).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(1).Kind) Assert.Null(semanticSummary.Alias) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact> Public Sub ImplementsClause4() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports System Interface I1 Sub goo(x As Integer) Sub goo(x As Integer, y As Integer) End Interface Class C1 Public Sub goo(x As Integer) Implements I1.goo 'BIND:"I1.goo"'BIND:"I1.goo" Throw New NotImplementedException() End Sub End Class ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of QualifiedNameSyntax)(compilation, "a.vb") Assert.Null(semanticSummary.Type) Assert.Null(semanticSummary.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Null(semanticSummary.Symbol) Assert.Equal(CandidateReason.NotReferencable, semanticSummary.CandidateReason) Assert.Equal(1, semanticSummary.CandidateSymbols.Length) Dim sortedCandidates = semanticSummary.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub I1.goo(x As System.Int32)", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(0).Kind) Assert.Null(semanticSummary.Alias) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact> Public Sub ImplementsClause5() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports System Interface I1 Private Sub goo(x As Integer) End Interface Class C1 Implements I1 Public Sub goo(x As Integer) Implements I1.goo 'BIND:"I1.goo"'BIND:"I1.goo" Throw New NotImplementedException() End Sub End Class ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of QualifiedNameSyntax)(compilation, "a.vb") Assert.Null(semanticSummary.Type) Assert.Null(semanticSummary.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Null(semanticSummary.Symbol) Assert.Equal(CandidateReason.Inaccessible, semanticSummary.CandidateReason) Assert.Equal(1, semanticSummary.CandidateSymbols.Length) Dim sortedCandidates = semanticSummary.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub I1.goo(x As System.Int32)", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(0).Kind) Assert.Null(semanticSummary.Alias) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact> Public Sub ImplementsClause6() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports System Interface I1 Inherits I2, I3 End Interface Interface I2 Sub goo(x As Integer, z As String) End Interface Interface I3 Sub goo(x As Integer, y As Integer) End Interface Class C1 Public Sub goo(x As Integer) Implements I1.goo 'BIND:"I1.goo"'BIND:"I1.goo" Throw New NotImplementedException() End Sub End Class ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of QualifiedNameSyntax)(compilation, "a.vb") Assert.Null(semanticSummary.Type) Assert.Null(semanticSummary.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Null(semanticSummary.Symbol) Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticSummary.CandidateReason) Assert.Equal(2, semanticSummary.CandidateSymbols.Length) Dim sortedCandidates = semanticSummary.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub I2.goo(x As System.Int32, z As System.String)", sortedCandidates(0).ToTestDisplayString()) Assert.Equal("Sub I3.goo(x As System.Int32, y As System.Int32)", sortedCandidates(1).ToTestDisplayString()) Assert.Null(semanticSummary.Alias) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact> Public Sub ImplementsClause7() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports System Module m1 Public Sub main() End Sub End Module Interface I1 Inherits I2, I3 End Interface Interface I2 Event E1() End Interface Interface I3 Event E2 As I1.E1EventHandler End Interface Class C1 Implements I1 Public Event E3() Implements I2.E1, I3.E2'BIND:"I3.E2" End Class ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of QualifiedNameSyntax)(compilation, "a.vb") Assert.Null(semanticSummary.Type) Assert.Null(semanticSummary.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Equal("Event I3.E2 As I2.E1EventHandler", semanticSummary.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Event, semanticSummary.Symbol.Kind) Assert.Equal(0, semanticSummary.CandidateSymbols.Length) Assert.Null(semanticSummary.Alias) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact()> Public Sub InterfaceImplementationCantFindMatching() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Interface IA Overloads Sub Goo(ByVal x As Long) Overloads Sub Goo(ByVal x As String) End Interface Class K Implements IA Public Overloads Sub F(x As Integer) Implements IA.Goo'BIND:"IA.Goo" End Sub End Class </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of QualifiedNameSyntax)(compilation, "a.vb") Assert.Null(semanticInfo.Type) Assert.Null(semanticInfo.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.True(semanticInfo.CandidateSymbols.Length > 0, "Should have candidate symbols") Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason) Assert.False(semanticInfo.MemberGroup.Length > 0, "Shouldn't have member group") Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <WorkItem(539111, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539111")> <Fact> Public Sub MethodReferenceWithImplicitTypeArguments() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System Module Module1 Sub Main() Goo(Of Integer)'BIND:"Goo(Of Integer)" End Sub Sub Goo(a As String) End Sub Sub Goo(ByRef a As String, b As String) End Sub Sub Goo(Of T)(a As String, b As String) End Sub End Module </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of GenericNameSyntax)(compilation, "a.vb") Assert.Null(semanticInfo.Type) Assert.Null(semanticInfo.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason) Assert.Equal(1, semanticInfo.CandidateSymbols.Length) Dim sortedCandidates = semanticInfo.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub Module1.Goo(Of System.Int32)(a As System.String, b As System.String)", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(0).Kind) Assert.Equal(1, semanticInfo.MemberGroup.Length) Dim sortedMethodGroup = semanticInfo.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub Module1.Goo(Of System.Int32)(a As System.String, b As System.String)", sortedMethodGroup(0).ToTestDisplayString()) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <WorkItem(538452, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538452")> <Fact> Public Sub InvalidMethodInvocationExpr() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Sub Main() T()'BIND:"T()" End Sub Sub T() End Sub </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of InvocationExpressionSyntax)(compilation, "a.vb") Assert.Equal(SpecialType.System_Void, semanticInfo.Type.SpecialType) Assert.Equal(SpecialType.System_Void, semanticInfo.ConvertedType.SpecialType) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("T", semanticInfo.Symbol.Name) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact> Public Sub UnaryPlusExprWithoutMsCorlibRef() Dim compilation = CreateEmptyCompilationWithReferences( <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim count As Integer count = +10 'BIND:"+10"'BIND:"+10" End Sub End Module </file> </compilation>, {}) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of UnaryExpressionSyntax)(compilation, "a.vb") Assert.Equal("System.Int32[missing]", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32[missing]", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Function System.Int32[missing].op_UnaryPlus(value As System.Int32[missing]) As System.Int32[missing]", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <WorkItem(4280, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub BindingIsNothingFunc() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports Microsoft.VisualBasic Module Module1 Sub Main() Dim var1 As Object If IsNothing(var1) Then'BIND:"IsNothing(var1)" End If End Sub End Module </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of InvocationExpressionSyntax)(compilation, "a.vb") Assert.Equal("System.Boolean", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) End Sub <Fact> Public Sub MaxIntPlusOneHexLiteralConst() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim lngPass As Integer lngPass = &amp;H80000000'BIND:"&amp;H80000000" End Sub End Module </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of LiteralExpressionSyntax)(compilation, "a.vb") Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.True(semanticInfo.ConstantValue.HasValue) Assert.Equal(CInt(-2147483648), semanticInfo.ConstantValue.Value) End Sub <WorkItem(539017, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539017")> <Fact> Public Sub ParenExprInMultiDimArrayDeclWithError() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Module Mod1 Sub Main() Dim scen3(, 5,6,) As Integer Dim x((,)) As Integer 'BIND:"(,)" End Sub End Module ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of TupleExpressionSyntax)(compilation, "a.vb") Assert.Equal("(?, ?)", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(Nothing, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact> Public Sub InvocExprWithImplicitlyTypedArgument() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Module Module1 Sub VerifyByteArray(ByRef arry() As Byte, ByRef lbnd As Integer) End Sub Sub Main() Dim vsarry() As Byte Dim Max = 140000 VerifyByteArray(vsarry, Max)'BIND:"VerifyByteArray(vsarry, Max)" End Sub End Module </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of InvocationExpressionSyntax)(compilation, "a.vb") Assert.Equal("System.Void", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Void", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Sub Module1.VerifyByteArray(ByRef arry As System.Byte(), ByRef lbnd As System.Int32)", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <WorkItem(4512, "DevDiv_Projects/Roslyn")> <Fact> Public Sub MultiDimArrayCreationExpr() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim y = New Object() {1, 2} Dim x As Object = New Object()() {y, y}'BIND:"New Object()() {y, y}" End Sub End Module </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of ArrayCreationExpressionSyntax)(compilation, "a.vb") Assert.Equal("System.Object()()", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Array, semanticInfo.Type.TypeKind) Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.WideningReference, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <WorkItem(527716, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527716")> <Fact> Public Sub EmptyParenExprInArrayDeclWithError() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Module Mod1 Sub Main() Dim x1 = New Single(0, (* ) - 1) {{2}, {4}}'BIND:"(* )" End Sub End Module </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of ParenthesizedExpressionSyntax)(compilation, "a.vb") Assert.Equal("?", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind) Assert.Equal("?", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <WorkItem(538918, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538918")> <Fact> Public Sub MeSymbol() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C Sub Test() Me.Test()'BIND:"Me" End Sub End Class </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of MeExpressionSyntax)(compilation, "a.vb") Assert.Equal("C", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("C", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Me As C", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Parameter, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.True(DirectCast(semanticInfo.Symbol, ParameterSymbol).IsMe, "should be Me symbol") Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <WorkItem(527818, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527818")> <Fact> Public Sub BindingFuncNoBracket() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System Imports Microsoft.VisualBasic Namespace VBNS Class Test Function MyFunc() As Byte Return Nothing End Function Sub MySub() Dim ret As Byte = MyFunc'BIND:"MyFunc" End Sub End Class End Namespace </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("System.Byte", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Byte", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Function VBNS.Test.MyFunc() As System.Byte", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact> Public Sub NamespaceAlias() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports S = System Namespace NS Class Test Dim x As S.Exception'BIND:"S" End Class End Namespace </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticInfo.Type) Assert.Null(semanticInfo.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.NotNull(semanticInfo.Symbol) Assert.NotNull(semanticInfo.Alias) Assert.Equal("S=System", semanticInfo.Alias.ToTestDisplayString()) Assert.Equal(SymbolKind.Alias, semanticInfo.Alias.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Dim ns = DirectCast(semanticInfo.Alias.Target, NamespaceSymbol) Assert.Equal(ns.Name, "System") Assert.Equal(compilation.SourceModule, semanticInfo.Alias.ContainingModule) Assert.Equal(compilation.Assembly, semanticInfo.Alias.ContainingAssembly) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact> Public Sub NamespaceAlias2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System Imports N = NS1.NS2 Namespace NS1.NS2 Public Class A Public Shared Sub M Dim o As N.A'BIND:"N" End Sub End Class End Namespace </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticInfo.Type) Assert.Null(semanticInfo.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.NotNull(semanticInfo.Symbol) Assert.NotNull(semanticInfo.Alias) Assert.Equal("N=NS1.NS2", semanticInfo.Alias.ToTestDisplayString()) Assert.Equal(SymbolKind.Alias, semanticInfo.Alias.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Dim ns = DirectCast(semanticInfo.Alias.Target, NamespaceSymbol) Assert.Equal("NS1.NS2", ns.ToTestDisplayString()) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact> Public Sub TypeAlias() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports S = System.String Namespace NS Class Test Sub Goo Dim x As String x = S.Empty'BIND:"S" End Sub End Class End Namespace </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.NotNull(semanticInfo.Symbol) Assert.NotNull(semanticInfo.Alias) Assert.Equal("S=System.String", semanticInfo.Alias.ToTestDisplayString()) Assert.Equal(SymbolKind.Alias, semanticInfo.Alias.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal("String", semanticInfo.Alias.Target.Name) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact> Public Sub TypeAlias2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Imports System.Linq Imports T = System.Guid Module Program Sub Main(args As String()) Dim a As Type a = GetType(T)'BIND:"T" End Sub End Module </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("System.Guid", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Guid", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.NotNull(semanticInfo.Symbol) Assert.NotNull(semanticInfo.Alias) Assert.Equal("T=System.Guid", semanticInfo.Alias.ToTestDisplayString()) Assert.Equal(SymbolKind.Alias, semanticInfo.Alias.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact> Public Sub TypeAlias3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Imports System.Linq Imports T = System.Guid Module Program Dim a As T'BIND:"T" Sub Main(args As String()) End Sub End Module </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("System.Guid", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Guid", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.NotNull(semanticInfo.Symbol) Assert.NotNull(semanticInfo.Alias) Assert.Equal("T=System.Guid", semanticInfo.Alias.ToTestDisplayString()) Assert.Equal(SymbolKind.Alias, semanticInfo.Alias.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <WorkItem(540279, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540279")> <Fact> Public Sub NoMembersForVoidReturnType() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C Sub Test() System.Console.WriteLine()'BIND:"System.Console.WriteLine()" End Sub End Class </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of InvocationExpressionSyntax)(compilation, "a.vb") Assert.Equal("System.Void", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Void", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Sub System.Console.WriteLine()", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim semanticModel = compilation.GetSemanticModel(CompilationUtils.GetTree(compilation, "a.vb")) Dim methodSymbol As MethodSymbol = DirectCast(semanticInfo.Symbol, MethodSymbol) Dim returnType = methodSymbol.ReturnType Dim symbols = semanticModel.LookupSymbols(0, returnType) Assert.Equal(0, symbols.Length) End Sub <Fact> Public Sub EnumMember1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Enum filePermissions create = 1 read = create'BIND:"create" write = 4 delete = 8 End Enum Class c1 Public Shared Sub Main(args As String()) Dim file1Perm As filePermissions file1Perm = filePermissions.create Or filePermissions.read End Sub End Class </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("filePermissions", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Enum, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.WideningNumeric Or ConversionKind.InvolvesEnumTypeConversions, semanticInfo.ImplicitConversion.Kind) Assert.Equal("filePermissions.create", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Field, semanticInfo.Symbol.Kind) Assert.True(TypeOf semanticInfo.Symbol Is SourceEnumConstantSymbol, "Should have bound to synthesized enum constant") Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.True(semanticInfo.ConstantValue.HasValue) Assert.Equal(1, semanticInfo.ConstantValue.Value) End Sub <Fact> Public Sub CatchVariable() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class c1 Public Shared Sub Main() Try Catch ex as Exception 'BIND:"ex" End Try End Sub End Class </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("Exception", semanticInfo.Type.ToTestDisplayString()) End Sub <Fact> Public Sub CatchVariable1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class c1 Public Shared Sub Main() dim a as Action = Sub() Try Catch ex as Exception 'BIND:"ex" End Try End Sub End Sub End Class </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("Exception", semanticInfo.Type.ToTestDisplayString()) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <WorkItem(540050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540050")> <Fact> Public Sub StaticLocalSymbol() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C Public Function goo() As Integer Static i As Integer = 23 i = i + 1'BIND:"i" Return i End Function Public Shared Sub Main() End Sub End Class </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("i As System.Int32", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim iSymbol = DirectCast(semanticInfo.Symbol, LocalSymbol) Assert.True(iSymbol.IsStatic) Assert.False(iSymbol.IsShared) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:="https://github.com/dotnet/roslyn/issues/29531")> Public Sub IncompleteWriteLine() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Console.WriteLine( 'BIND:"WriteLine" End Sub End Module </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticInfo.Type) Assert.Null(semanticInfo.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason) Assert.Equal(12, semanticInfo.CandidateSymbols.Length) Dim sortedCandidates = semanticInfo.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString(), StringComparer.InvariantCulture).ToArray() Assert.Equal("Sub System.Console.WriteLine(buffer As System.Char())", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(0).Kind) Assert.Equal("Sub System.Console.WriteLine(value As System.Boolean)", sortedCandidates(1).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(1).Kind) Assert.Equal("Sub System.Console.WriteLine(value As System.Char)", sortedCandidates(2).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(2).Kind) Assert.Equal("Sub System.Console.WriteLine(value As System.Decimal)", sortedCandidates(3).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(3).Kind) Assert.Equal("Sub System.Console.WriteLine(value As System.Double)", sortedCandidates(4).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(4).Kind) Assert.Equal("Sub System.Console.WriteLine(value As System.Int32)", sortedCandidates(5).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(5).Kind) Assert.Equal("Sub System.Console.WriteLine(value As System.Int64)", sortedCandidates(6).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(6).Kind) Assert.Equal("Sub System.Console.WriteLine(value As System.Object)", sortedCandidates(7).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(7).Kind) Assert.Equal("Sub System.Console.WriteLine(value As System.Single)", sortedCandidates(8).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(8).Kind) Assert.Equal("Sub System.Console.WriteLine(value As System.String)", sortedCandidates(9).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(9).Kind) Assert.Equal("Sub System.Console.WriteLine(value As System.UInt32)", sortedCandidates(10).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(10).Kind) Assert.Equal("Sub System.Console.WriteLine(value As System.UInt64)", sortedCandidates(11).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(11).Kind) Assert.Equal(19, semanticInfo.MemberGroup.Length) Dim sortedMethodGroup = semanticInfo.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString(), StringComparer.InvariantCulture).ToArray() Assert.Equal("Sub System.Console.WriteLine()", sortedMethodGroup(0).ToTestDisplayString()) Assert.Equal("Sub System.Console.WriteLine(buffer As System.Char())", sortedMethodGroup(1).ToTestDisplayString()) Assert.Equal("Sub System.Console.WriteLine(buffer As System.Char(), index As System.Int32, count As System.Int32)", sortedMethodGroup(2).ToTestDisplayString()) Assert.Equal("Sub System.Console.WriteLine(format As System.String, arg0 As System.Object)", sortedMethodGroup(3).ToTestDisplayString()) Assert.Equal("Sub System.Console.WriteLine(format As System.String, arg0 As System.Object, arg1 As System.Object)", sortedMethodGroup(4).ToTestDisplayString()) Assert.Equal("Sub System.Console.WriteLine(format As System.String, arg0 As System.Object, arg1 As System.Object, arg2 As System.Object)", sortedMethodGroup(5).ToTestDisplayString()) Assert.Equal("Sub System.Console.WriteLine(format As System.String, arg0 As System.Object, arg1 As System.Object, arg2 As System.Object, arg3 As System.Object)", sortedMethodGroup(6).ToTestDisplayString()) Assert.Equal("Sub System.Console.WriteLine(format As System.String, ParamArray arg As System.Object())", sortedMethodGroup(7).ToTestDisplayString()) Assert.Equal("Sub System.Console.WriteLine(value As System.Boolean)", sortedMethodGroup(8).ToTestDisplayString()) Assert.Equal("Sub System.Console.WriteLine(value As System.Char)", sortedMethodGroup(9).ToTestDisplayString()) Assert.Equal("Sub System.Console.WriteLine(value As System.Decimal)", sortedMethodGroup(10).ToTestDisplayString()) Assert.Equal("Sub System.Console.WriteLine(value As System.Double)", sortedMethodGroup(11).ToTestDisplayString()) Assert.Equal("Sub System.Console.WriteLine(value As System.Int32)", sortedMethodGroup(12).ToTestDisplayString()) Assert.Equal("Sub System.Console.WriteLine(value As System.Int64)", sortedMethodGroup(13).ToTestDisplayString()) Assert.Equal("Sub System.Console.WriteLine(value As System.Object)", sortedMethodGroup(14).ToTestDisplayString()) Assert.Equal("Sub System.Console.WriteLine(value As System.Single)", sortedMethodGroup(15).ToTestDisplayString()) Assert.Equal("Sub System.Console.WriteLine(value As System.String)", sortedMethodGroup(16).ToTestDisplayString()) Assert.Equal("Sub System.Console.WriteLine(value As System.UInt32)", sortedMethodGroup(17).ToTestDisplayString()) Assert.Equal("Sub System.Console.WriteLine(value As System.UInt64)", sortedMethodGroup(18).ToTestDisplayString()) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact> Public Sub ReturnedNothingLiteral() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System Module Program Function Main(args As String()) As String Return Nothing'BIND:"Nothing" End Function End Module </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of LiteralExpressionSyntax)(compilation, "a.vb") Assert.Null(semanticInfo.Type) Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.WideningNothingLiteral, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.True(semanticInfo.ConstantValue.HasValue) Assert.Null(semanticInfo.ConstantValue.Value) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:="https://github.com/dotnet/roslyn/issues/29531")> Public Sub FailedConstructorCall() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System Class C End Class Class V Sub goo Dim c As C c = New C(13)'BIND:"C" End Sub End Class </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticInfo.Type) Assert.Null(semanticInfo.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("C", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:="https://github.com/dotnet/roslyn/issues/29531")> Public Sub FailedConstructorCall2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System Class C End Class Class V Sub goo Dim c As C c = New C(13)'BIND:"New C(13)" End Sub End Class </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of ObjectCreationExpressionSyntax)(compilation, "a.vb") Assert.Equal("C", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("C", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason) Assert.Equal(1, semanticInfo.CandidateSymbols.Length) Dim sortedCandidates = semanticInfo.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub C..ctor()", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(0).Kind) Assert.Equal(1, semanticInfo.MemberGroup.Length) Dim sortedMethodGroup = semanticInfo.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub C..ctor()", sortedMethodGroup(0).ToTestDisplayString()) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact> Public Sub ExplicitCallToDefaultProperty1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class X Public ReadOnly Property Goo As Y Get Return Nothing End Get End Property End Class Class Y Public Default ReadOnly Property Item(ByVal a As Integer) As String Get Return "hi" End Get End Property End Class Module M1 Sub Main() Dim a As String Dim b As X b = New X() a = b.Goo.Item(4)'BIND:"Item" End Sub End Module </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticInfo.Type) Assert.Null(semanticInfo.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("ReadOnly Property Y.Item(a As System.Int32) As System.String", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Property, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(1, semanticInfo.MemberGroup.Length) Dim sortedMethodGroup = semanticInfo.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("ReadOnly Property Y.Item(a As System.Int32) As System.String", sortedMethodGroup(0).ToTestDisplayString()) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub ExplicitCallToDefaultProperty2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class X Public ReadOnly Property Goo As Y Get Return Nothing End Get End Property End Class Class Y Public Default ReadOnly Property Item(ByVal a As Integer) As String Get Return "hi" End Get End Property End Class Module M1 Sub Main() Dim a As String Dim b As X b = New X() a = b.Goo.Item(4)'BIND:"b.Goo.Item(4)" End Sub End Module </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of InvocationExpressionSyntax)(compilation, "a.vb") Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("ReadOnly Property Y.Item(a As System.Int32) As System.String", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Property, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <WorkItem(541240, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541240")> <Fact()> Public Sub ConstFieldInitializer() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C Public Const ClassId As String = Nothing 'BIND:"Nothing" End Class </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of ExpressionSyntax)(compilation, "a.vb") Assert.Null(semanticInfo.Type) Assert.True(semanticInfo.ConstantValue.HasValue) Assert.Null(semanticInfo.ConstantValue.Value) End Sub <Fact()> Public Sub ConstFieldInitializer2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C Public Const ClassId As Integer = 23 'BIND:"23" End Class </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of ExpressionSyntax)(compilation, "a.vb") Assert.NotNull(semanticInfo.Type) Assert.Equal(System_Int32, semanticInfo.Type.SpecialType) Assert.Equal(semanticInfo.ConstantValue.Value, 23) Assert.True(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub ConstFieldInitializer3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C Public Const ClassDate As DateTime = #11/04/2008# 'BIND:"#11/04/2008#" End Class </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of ExpressionSyntax)(compilation, "a.vb") Assert.NotNull(semanticInfo.Type) Assert.Equal(System_DateTime, semanticInfo.Type.SpecialType) Assert.True(semanticInfo.ConstantValue.HasValue) Assert.Equal(#11/4/2008#, semanticInfo.ConstantValue.Value) End Sub <Fact()> Public Sub ConstFieldInitializer4() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C Public Const ClassId As Integer = 2 + 2 'BIND:"2 + 2" End Class </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of ExpressionSyntax)(compilation, "a.vb") Assert.NotNull(semanticInfo.Type) Assert.Equal(System_Int32, semanticInfo.Type.SpecialType) Assert.Equal(semanticInfo.ConstantValue.Value, 4) Assert.True(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub ConstFieldInitializer5() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C Public Const A As Integer = 4 Public Const B As Integer = 7 + 2 * A 'BIND:"2 * A" End Class </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of ExpressionSyntax)(compilation, "a.vb") Assert.NotNull(semanticInfo.Type) Assert.Equal(System_Int32, semanticInfo.Type.SpecialType) Assert.Equal(semanticInfo.ConstantValue.Value, 8) Assert.True(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub ConstFieldInitializersMultipleSymbols() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C Const X, Y As Integer = 6 Const Z As Integer = Y End Class </file> </compilation>) Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim node = FindNodeFromText(tree, "X") Dim symbol = DirectCast(model.GetDeclaredSymbol(node), FieldSymbol) Assert.Equal(symbol.Name, "X") Assert.Equal(System_Int32, symbol.Type.SpecialType) Assert.Equal(symbol.ConstantValue, 6) End Sub <Fact()> Public Sub FieldInitializer1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C Public ClassId As Integer = 23 'BIND:"23" End Class </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of ExpressionSyntax)(compilation, "a.vb") Assert.NotNull(semanticInfo.Type) Assert.Equal(System_Int32, semanticInfo.Type.SpecialType) Assert.Equal(semanticInfo.ConstantValue.Value, 23) Assert.True(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub FieldInitializer2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C Public ClassId As Integer = C.goo() 'BIND:"goo" shared Function goo() as Integer return 23 End Function End Class </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of ExpressionSyntax)(compilation, "a.vb") Assert.Null(semanticInfo.Type) Assert.Equal(1, semanticInfo.MemberGroup.Length) Assert.Equal("Function C.goo() As System.Int32", semanticInfo.MemberGroup(0).ToDisplayString(SymbolDisplayFormat.TestFormat)) End Sub <WorkItem(541243, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541243")> <Fact()> Public Sub CollectionInitializerNoMscorlibRef() Dim compilation = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim numbers() As Integer = New Integer() {0, 1, 2, 3, 4} 'BIND:"{0, 1, 2, 3, 4}" End Sub End Module </file> </compilation>, {}) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of ExpressionSyntax)(compilation, "a.vb") Assert.Equal("System.Int32[missing]()", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Array, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32[missing]()", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Array, semanticInfo.ConvertedType.TypeKind) End Sub <Fact()> Public Sub CollectionInitializerWithoutConversion() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Option Strict On Class C Shared Sub M(s as string) Dim s = New String() {s} 'BIND:"{s}" End Sub End Class </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of ExpressionSyntax)(compilation, "a.vb") Assert.Equal("System.String()", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Array, semanticInfo.Type.TypeKind) Assert.Equal("System.String()", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Array, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) End Sub <WorkItem(541422, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541422")> <Fact()> Public Sub CollectionInitializerWithConversion() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Option Strict On Class C Shared Sub M(o As Object) Dim s = New String() {o} 'BIND:"{o}" End Sub End Class </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of ExpressionSyntax)(compilation, "a.vb") Assert.Equal("System.String()", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Array, semanticInfo.Type.TypeKind) Assert.Equal("System.String()", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Array, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) End Sub <Fact()> Public Sub ArrayInitializerMemberWithConversion() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Dim s As String Dim x As Object() = New Object() {s}'BIND:"s" End Sub End Module ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.WideningReference, semanticInfo.ImplicitConversion.Kind) Assert.Equal("s As System.String", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub TwoDArrayInitializerMember() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Module Program Sub Main() Dim s1 As String = "hi" Dim s2 As String = "hello" Dim o1 As Object = Nothing Dim o2 As Object = Nothing Dim arr As Object(,) = New Object(,) {{o1, o2}, {s1, s2}}'BIND:"s2" End Sub End Module ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.WideningReference, semanticInfo.ImplicitConversion.Kind) Assert.Equal("s2 As System.String", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub PartialArrayInitializer() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Module Program Sub Main() Dim s1 As String = "hi" Dim s2 As String = "hello" Dim o1 As Object = Nothing Dim o2 As Object = Nothing Dim arr As Object(,) = New Object(,) {{o1, o2}, {s1, s2}}'BIND:"{s1, s2}" End Sub End Module ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of CollectionInitializerSyntax)(compilation, "a.vb") Assert.Null(semanticInfo.Type) Assert.Null(semanticInfo.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <WorkItem(541270, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541270")> <Fact()> Public Sub GetSemanticInfoOfNothing() Dim compilation = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation> <file name="a.vb"> Module Module1 Sub Main() End Sub End Module </file> </compilation>, {}) Dim semanticModel = compilation.GetSemanticModel(compilation.SyntaxTrees(0)) Assert.Throws(Of ArgumentNullException)(Function() Return semanticModel.GetAliasInfo(Nothing) End Function ) Assert.Throws(Of ArgumentNullException)(Function() Return semanticModel.GetSymbolInfo(DirectCast(Nothing, AttributeSyntax)) End Function ) Assert.Throws(Of ArgumentNullException)(Function() Return semanticModel.GetSymbolInfo(DirectCast(Nothing, ExpressionRangeVariableSyntax)) End Function ) Assert.Throws(Of ArgumentNullException)(Function() Return semanticModel.GetSymbolInfo(DirectCast(Nothing, ExpressionSyntax)) End Function ) Assert.Throws(Of ArgumentNullException)(Function() Return semanticModel.GetSymbolInfo(DirectCast(Nothing, FunctionAggregationSyntax)) End Function ) Assert.Throws(Of ArgumentNullException)(Function() Return semanticModel.GetSymbolInfo(DirectCast(Nothing, OrderingSyntax)) End Function ) Assert.Throws(Of ArgumentNullException)(Function() Return semanticModel.GetSymbolInfo(DirectCast(Nothing, QueryClauseSyntax)) End Function ) Assert.Throws(Of ArgumentNullException)(Function() Return semanticModel.GetTypeInfo(DirectCast(Nothing, AttributeSyntax)) End Function ) Assert.Throws(Of ArgumentNullException)(Function() Return semanticModel.GetTypeInfo(DirectCast(Nothing, ExpressionSyntax)) End Function ) Assert.Throws(Of ArgumentNullException)(Function() Return semanticModel.GetConstantValue(DirectCast(Nothing, ExpressionSyntax)) End Function ) Assert.Throws(Of ArgumentNullException)(Function() Return semanticModel.GetMemberGroup(DirectCast(Nothing, ExpressionSyntax)) End Function ) End Sub <WorkItem(541390, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541390")> <Fact()> Public Sub ErrorLambdaParamInsideFieldInitializer() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module Module1 Dim f1 As Func(Of Integer, Integer) = Function(lambdaParam As Integer) Return lambdaParam + 1 'BIND:"lambdaParam" End Function End Module </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of ExpressionSyntax)(compilation, "a.vb") Assert.NotNull(semanticInfo) Assert.NotNull(semanticInfo.Type) Assert.Equal(System_Int32, semanticInfo.Type.SpecialType) End Sub <Fact()> Public Sub ErrorLambdaParamInsideLocalInitializer() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim f1 As Func(Of Integer, Integer) = Function(lambdaParam As Integer) Return lambdaParam + 1 'BIND:"lambdaParam" End Function End Sub End Module </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of ExpressionSyntax)(compilation, "a.vb") Assert.NotNull(semanticInfo) Assert.NotNull(semanticInfo.Type) Assert.Equal(System_Int32, semanticInfo.Type.SpecialType) End Sub <WorkItem(541390, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541390")> <Fact()> Public Sub LambdaParamInsideFieldInitializer() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Module Module1 Dim f1 As Func(Of Integer, Integer) = Function(lambdaParam) Return lambdaParam + 1 'BIND:"lambdaParam" End Function End Module </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of ExpressionSyntax)(compilation, "a.vb") Assert.NotNull(semanticInfo) Assert.NotNull(semanticInfo.Type) Assert.Equal(System_Int32, semanticInfo.Type.SpecialType) End Sub <Fact()> Public Sub LambdaParamInsideLocalInitializer() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Module Module1 Sub Main() Dim f1 As Func(Of Integer, Integer) = Function(lambdaParam) Return lambdaParam + 1 'BIND:"lambdaParam" End Function End Sub End Module </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of ExpressionSyntax)(compilation, "a.vb") Assert.NotNull(semanticInfo) Assert.NotNull(semanticInfo.Type) Assert.Equal(System_Int32, semanticInfo.Type.SpecialType) End Sub <WorkItem(541418, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541418")> <Fact()> Public Sub BindAttributeInstanceWithoutAttributeSuffix() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ <Assembly: My> 'BIND:"My" Class MyAttribute : Inherits System.Attribute End Class]]> </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of ExpressionSyntax)(compilation, "a.vb") Assert.NotNull(semanticInfo) Assert.NotNull(semanticInfo.Symbol) Assert.Equal("Sub MyAttribute..ctor()", semanticInfo.Symbol.ToDisplayString(SymbolDisplayFormat.TestFormat)) Assert.Equal("MyAttribute", semanticInfo.Type.ToDisplayString(SymbolDisplayFormat.TestFormat)) End Sub <WorkItem(541401, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541401")> <Fact()> Public Sub BindingAttributeParameter() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class MineAttribute Inherits Attribute Public Sub New(p As Short) End Sub End Class <Mine(123)> 'BIND:"123" Class C End Class ]]> </file> </compilation>) ' NOTE: VB doesn't allow same line comments after attribute Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of LiteralExpressionSyntax)(compilation, "a.vb") Assert.NotNull(semanticInfo.Type) Assert.Equal(System_Int32, semanticInfo.Type.SpecialType) Assert.Equal(System_Int16, semanticInfo.ConvertedType.SpecialType) Assert.Equal(semanticInfo.ConstantValue.Value, 123) Assert.True(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub BindAttributeNamespace() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> <![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Namespace n1 Module Program <n1.Program.Test1(1)>'BIND:"n1" Class A End Class <AttributeUsageAttribute(AttributeTargets.All, AllowMultiple:=True)> Class Test1 Inherits Attribute Public Sub New(i As Integer) End Sub End Class End Module End Namespace ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticInfo.Type) Assert.Null(semanticInfo.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("n1", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Namespace, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <WorkItem(541418, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541418")> <Fact()> Public Sub BindingAttributeClassName() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System <System.AttributeUsage(AttributeTargets.All, AllowMultiple:=true)> _ 'BIND:"AttributeUsage" Class ZAttribute Inherits Attribute End Class <ZAttribute()> Class scen1 Shared Sub Main() Dim x = 1 Console.WriteLine(x) End Sub End Class ]]> </file> </compilation>) ' NOTE: VB doesn't allow same line comments after attribute Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.NotNull(semanticInfo.Type) Assert.Equal("System.AttributeUsageAttribute", semanticInfo.Type.ToString()) Assert.False(DirectCast(semanticInfo.Type, TypeSymbol).IsErrorType) End Sub <Fact()> Public Sub TestAttributeFieldName() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Namespace n1 Module Program <Test1(fi:=10)>'BIND:"fi" Class A End Class <AttributeUsageAttribute(AttributeTargets.All, AllowMultiple:=True)> Class Test1 Inherits Attribute Public Sub New(i As Integer) End Sub Public fi As Integer End Class End Module End Namespace]]> </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("n1.Program.Test1.fi As System.Int32", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Field, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub TestAttributePropertyName() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Namespace n1 Module Program Class A <Test1(1, Pi:=2)>'BIND:"Pi" Sub s End Sub End Class <AttributeUsageAttribute(AttributeTargets.All, AllowMultiple:=True)> Class Test1 Inherits Attribute Public Sub New() End Sub Public Sub New(i As Integer) End Sub Public fi As Integer Public Property Pi As Integer End Class End Module End Namespace ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Property n1.Program.Test1.Pi As System.Int32", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Property, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub TestAttributePositionalArgOnParameter() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Namespace n1 Module Program Class A Function f( <Test1("parameter")> x As Integer) As Integer'BIND:""parameter"" Return 0 End Function End Class <AttributeUsageAttribute(AttributeTargets.All, AllowMultiple:=True)> Class Test1 Inherits Attribute Public Sub New(i As String) End Sub End Class End Module End Namespace ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of LiteralExpressionSyntax)(compilation, "a.vb") Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.True(semanticInfo.ConstantValue.HasValue) Assert.Equal("parameter", semanticInfo.ConstantValue.Value) End Sub <Fact()> Public Sub TestAttributeClassNameOnReturnValue() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Namespace n1 Module Program Class A Function f(x As Integer) As <Test1(4)> Integer'BIND:"Test1" Return 0 End Function End Class <AttributeUsageAttribute(AttributeTargets.All, AllowMultiple:=True)> Class Test1 Inherits Attribute Public Sub New(i As Integer) End Sub End Class End Module End Namespace ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("n1.Program.Test1", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("n1.Program.Test1", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Sub n1.Program.Test1..ctor(i As System.Int32)", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(1, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub TestAttributeCannotBindToUnqualifiedClassMember() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Namespace n1 Module Program <Test1(C1)>'BIND:"C1" Class A Public Const C1 As Integer = 99 End Class <AttributeUsageAttribute(AttributeTargets.All, AllowMultiple:=True)> Class Test1 Inherits Attribute Public Sub New(i As Integer) End Sub End Class End Module End Namespace ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("?", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind) Assert.Equal("?", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:="https://github.com/dotnet/roslyn/issues/29531")> Public Sub AttributeSemanticInfo_OverloadResolutionFailure_01() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System <Module: ObsoleteAttribute(GetType())>'BIND:"ObsoleteAttribute" ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("System.ObsoleteAttribute", semanticSummary.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.Type.TypeKind) Assert.Equal("System.ObsoleteAttribute", semanticSummary.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Null(semanticSummary.Symbol) Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticSummary.CandidateReason) Assert.Equal(3, semanticSummary.CandidateSymbols.Length) Dim sortedCandidates = semanticSummary.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub System.ObsoleteAttribute..ctor()", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(0).Kind) Assert.Equal("Sub System.ObsoleteAttribute..ctor(message As System.String)", sortedCandidates(1).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(1).Kind) Assert.Equal("Sub System.ObsoleteAttribute..ctor(message As System.String, [error] As System.Boolean)", sortedCandidates(2).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(2).Kind) Assert.Null(semanticSummary.Alias) Assert.Equal(3, semanticSummary.MemberGroup.Length) Dim sortedMethodGroup = semanticSummary.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub System.ObsoleteAttribute..ctor()", sortedMethodGroup(0).ToTestDisplayString()) Assert.Equal("Sub System.ObsoleteAttribute..ctor(message As System.String)", sortedMethodGroup(1).ToTestDisplayString()) Assert.Equal("Sub System.ObsoleteAttribute..ctor(message As System.String, [error] As System.Boolean)", sortedMethodGroup(2).ToTestDisplayString()) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:="https://github.com/dotnet/roslyn/issues/29531")> Public Sub AttributeSemanticInfo_OverloadResolutionFailure_02() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System <Module: Obsolete(GetType())>'BIND:"Module: Obsolete(GetType())" ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of AttributeSyntax)(compilation, "a.vb") Assert.Equal("System.ObsoleteAttribute", semanticSummary.Type.ToTestDisplayString()) Assert.Equal("System.ObsoleteAttribute", semanticSummary.ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Null(semanticSummary.Symbol) Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticSummary.CandidateReason) Assert.Equal(3, semanticSummary.CandidateSymbols.Length) Dim sortedCandidates = semanticSummary.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub System.ObsoleteAttribute..ctor()", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(0).Kind) Assert.Equal("Sub System.ObsoleteAttribute..ctor(message As System.String)", sortedCandidates(1).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(1).Kind) Assert.Equal("Sub System.ObsoleteAttribute..ctor(message As System.String, [error] As System.Boolean)", sortedCandidates(2).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(2).Kind) Assert.Null(semanticSummary.Alias) Assert.Equal(3, semanticSummary.MemberGroup.Length) Dim sortedMethodGroup = semanticSummary.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub System.ObsoleteAttribute..ctor()", sortedMethodGroup(0).ToTestDisplayString()) Assert.Equal("Sub System.ObsoleteAttribute..ctor(message As System.String)", sortedMethodGroup(1).ToTestDisplayString()) Assert.Equal("Sub System.ObsoleteAttribute..ctor(message As System.String, [error] As System.Boolean)", sortedMethodGroup(2).ToTestDisplayString()) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <WorkItem(541481, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541481")> <Fact()> Public Sub BindingPredefinedCastExpression() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports Microsoft.VisualBasic Module Test Sub Main() Dim exp As Integer = 123 Dim act As String = CStr(exp) 'BIND:"CStr(exp)" End Sub End Module ]]> </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of PredefinedCastExpressionSyntax)(compilation, "a.vb") Assert.NotNull(semanticInfo.Type) Assert.Equal("String", semanticInfo.Type.ToString()) End Sub <WorkItem(541498, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541498")> <Fact()> Public Sub DictionaryAccessExpressionErrorType() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Module Module1 Sub Main() Dim c As Collection Dim b = c!A 'BIND:"c!A" End Sub End Module ]]> </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of MemberAccessExpressionSyntax)(compilation, "a.vb") Assert.NotNull(semanticInfo) Assert.Null(semanticInfo.Symbol) Assert.Equal(semanticInfo.Type.TypeKind, TypeKind.Error) End Sub <Fact()> Public Sub DictionaryAccessExpressionErrorExpr() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Class A Private Shared F As System.Collections.Generic.Dictionary(Of String, Integer) End Class Class B Shared Sub M() Dim o = A.F!x 'BIND:"A.F!x" End Sub End Class ]]> </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of MemberAccessExpressionSyntax)(compilation, "a.vb") Assert.NotNull(semanticInfo) CompilationUtils.CheckSymbol(semanticInfo.Symbol, "Property Dictionary(Of String, Integer).Item(key As String) As Integer") Assert.Equal(semanticInfo.Type.SpecialType, System_Int32) End Sub <Fact()> Public Sub DictionaryAccessExpressionNoType() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Class C Shared Sub M() Dim o = (AddressOf M)!x 'BIND:"(AddressOf M)!x" End Sub End Class ]]> </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of MemberAccessExpressionSyntax)(compilation, "a.vb") Assert.NotNull(semanticInfo) Assert.Null(semanticInfo.Symbol) Assert.Equal(semanticInfo.Type.TypeKind, TypeKind.Error) End Sub <Fact()> Public Sub DictionaryAccessExpression() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Class A Friend Shared F As System.Collections.Generic.Dictionary(Of String, Integer) End Class Class B Shared Sub M() Dim o = A.F!x 'BIND:"A.F!x" End Sub End Class ]]> </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of MemberAccessExpressionSyntax)(compilation, "a.vb") Assert.NotNull(semanticInfo) CompilationUtils.CheckSymbol(semanticInfo.Symbol, "Property Dictionary(Of String, Integer).Item(key As String) As Integer") Assert.Equal(semanticInfo.Type.SpecialType, System_Int32) End Sub <WorkItem(541384, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541384")> <Fact()> Public Sub DictionaryAccessKey() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Class C Shared Function M(d As System.Collections.Generic.Dictionary(Of String, Integer)) As Integer Return d!key 'BIND:"key" End Function End Class ]]> </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.NotNull(semanticInfo) Assert.NotNull(semanticInfo.Type) Assert.Equal(semanticInfo.Type.SpecialType, System_String) Assert.Equal(semanticInfo.ConstantValue.Value, "key") Assert.Null(semanticInfo.Symbol) End Sub <WorkItem(541518, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541518")> <Fact()> Public Sub AssignAddressOfPropertyToDelegate() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Module Module1 Delegate Function del2() As Integer Property p() As Integer Get Return 10 End Get Set(ByVal Value As Integer) End Set End Property Sub Main() Dim var2 = New del2(AddressOf p)'BIND:"p" End Sub End Module ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticInfo.Type) Assert.Null(semanticInfo.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason) Assert.Equal(1, semanticInfo.CandidateSymbols.Length) Dim sortedCandidates = semanticInfo.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Property Module1.p As System.Int32", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.Property, sortedCandidates(0).Kind) Assert.Equal(1, semanticInfo.MemberGroup.Length) Dim sortedMethodGroup = semanticInfo.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Property Module1.p As System.Int32", sortedMethodGroup(0).ToTestDisplayString()) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub FieldAccess() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Class B Public f1 As Integer End Class Class M Public Sub Main() Dim bInstance As B bInstance = New B() Console.WriteLine(bInstance.f1)'BIND:"f1" End Sub End Class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("B.f1 As System.Int32", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Field, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub LocalVariable() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Class B Public f1 As Integer End Class Class M Public Sub Main() Dim bInstance As B bInstance = New B() Console.WriteLine(bInstance.f1)'BIND:"bInstance" End Sub End Class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("B", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("B", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("bInstance As B", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub NotFunctionReturnLocal() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Class M Public Function Goo() As Integer Goo()'BIND:"Goo" End Function End Class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticInfo.Type) Assert.Null(semanticInfo.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Function M.Goo() As System.Int32", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(1, semanticInfo.MemberGroup.Length) Dim sortedMethodGroup = semanticInfo.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Function M.Goo() As System.Int32", sortedMethodGroup(0).ToTestDisplayString()) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub FunctionReturnLocal() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Class M Public Function Goo() As Integer Goo = 4'BIND:"Goo" End Function End Class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Goo As System.Int32", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub MeSemanticInfo() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Class M Public x As Integer Public Function Goo() As Integer Me.x = 5'BIND:"Me" End Function End Class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of MeExpressionSyntax)(compilation, "a.vb") Assert.Equal("M", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("M", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Me As M", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Parameter, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.True(DirectCast(semanticInfo.Symbol, ParameterSymbol).IsMe) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub LocalVariableInConstructor() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Class B Public f1 As Integer End Class Class M Public Sub New() Dim bInstance As B bInstance = New B() Console.WriteLine(bInstance.f1)'BIND:"bInstance" End Sub End Class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("B", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("B", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("bInstance As B", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub LocalVariableInSharedConstructor() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Class B Public f1 As Integer End Class Class M Shared Sub New() Dim bInstance As B bInstance = New B() Console.WriteLine(bInstance.f1)'BIND:"bInstance" End Sub End Class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("B", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("B", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("bInstance As B", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub LocalVariableInModuleConstructor() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Class B Public f1 As Integer End Class Module M Sub New() Dim bInstance As B bInstance = New B() Console.WriteLine(bInstance.f1)'BIND:"bInstance" End Sub End Module ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("B", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("B", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("bInstance As B", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub ConstructorConstructorCall_Structure_Me_New_WithParameters() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Structure Program Public Sub New(i As Integer) End Sub Public Sub New(s As String) Me.New(1)'BIND:"Me.New(1)" End Sub End Structure ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of InvocationExpressionSyntax)(compilation, "a.vb") Assert.Equal("System.Void", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Void", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Sub Program..ctor(i As System.Int32)", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim method = DirectCast(semanticInfo.Symbol, MethodSymbol) Assert.Equal(MethodKind.Constructor, method.MethodKind) Assert.False(method.IsShared) Assert.False(method.IsImplicitlyDeclared) End Sub <Fact()> Public Sub ConstructorConstructorCall_Class_Me_New_WithParameters() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Class Program Public Sub New(i As Integer) End Sub Public Sub New(s As String) Me.New(1)'BIND:"Me.New(1)" End Sub End Class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of InvocationExpressionSyntax)(compilation, "a.vb") Assert.Equal("System.Void", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Void", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Sub Program..ctor(i As System.Int32)", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim method = DirectCast(semanticInfo.Symbol, MethodSymbol) Assert.Equal(MethodKind.Constructor, method.MethodKind) Assert.False(method.IsShared) Assert.False(method.IsImplicitlyDeclared) End Sub <Fact()> Public Sub ConstructorConstructorCall_Structure_Me_New_NoParameters() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Structure Program Public Sub New(s As String) Me.New()'BIND:"Me.New()" End Sub End Structure ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of InvocationExpressionSyntax)(compilation, "a.vb") Assert.Equal("System.Void", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Void", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Sub Program..ctor()", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim method = DirectCast(semanticInfo.Symbol, MethodSymbol) Assert.Equal(MethodKind.Constructor, method.MethodKind) Assert.False(method.IsShared) Assert.True(method.IsImplicitlyDeclared) End Sub <Fact()> Public Sub ConstructorConstructorCall_Class_Me_New_NoParameters() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Class Program Public Sub New() End Sub Public Sub New(s As String) Me.New()'BIND:"Me.New()" End Sub End Class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of InvocationExpressionSyntax)(compilation, "a.vb") Assert.Equal("System.Void", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Void", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Sub Program..ctor()", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim method = DirectCast(semanticInfo.Symbol, MethodSymbol) Assert.Equal(MethodKind.Constructor, method.MethodKind) Assert.False(method.IsShared) Assert.False(method.IsImplicitlyDeclared) End Sub <Fact()> Public Sub Invocation() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class C Private Sub M() Dim x As String = F()'BIND:"F()" End Sub Private Function F() As String Return "Hello" End Function End Class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of InvocationExpressionSyntax)(compilation, "a.vb") Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Function C.F() As System.String", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub MethodGroup() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class C Private Sub M() Dim x As String = F()'BIND:"F" End Sub Private Function F() As String Return "Hello" End Function Private Function F(arg As String) As String Return "Goodbye" End Function End Class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticInfo.Type) Assert.Null(semanticInfo.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Function C.F() As System.String", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(2, semanticInfo.MemberGroup.Length) Dim sortedMethodGroup = semanticInfo.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Function C.F() As System.String", sortedMethodGroup(0).ToTestDisplayString()) Assert.Equal("Function C.F(arg As System.String) As System.String", sortedMethodGroup(1).ToTestDisplayString()) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub InvocationNoMatchingOverloads() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class C Private Sub M() Dim x As String = F()'BIND:"F()" End Sub Private Function F(arg As Integer) As String Return "Hello" End Function Private Function F(arg As String) As String Return "Goodbye" End Function End Class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of InvocationExpressionSyntax)(compilation, "a.vb") Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason) Assert.Equal(2, semanticInfo.CandidateSymbols.Length) Dim sortedCandidates = semanticInfo.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Function C.F(arg As System.Int32) As System.String", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(0).Kind) Assert.Equal("Function C.F(arg As System.String) As System.String", sortedCandidates(1).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(1).Kind) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <WorkItem(540580, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540580")> <WorkItem(541567, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541567")> <ConditionalFact(GetType(WindowsOnly), Reason:="https://github.com/dotnet/roslyn/issues/29531")> Public Sub NoMatchingOverloads2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class C Private Sub M() Dim x As String = F(6, 3)'BIND:"F(6, 3)" End Sub Private Function F() As String Return "Hello" End Function End Class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of InvocationExpressionSyntax)(compilation, "a.vb") Assert.Equal("System.Char", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason) Assert.Equal(1, semanticInfo.CandidateSymbols.Length) Dim sortedCandidates = semanticInfo.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("ReadOnly Property System.String.Chars(index As System.Int32) As System.Char", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.Property, sortedCandidates(0).Kind) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub NoMatchingOverloads3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class C Private Sub M() Dim x As String = F.Chars(6, 3)'BIND:"F.Chars(6, 3)" End Sub Private Function F() As String Return "Hello" End Function End Class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of InvocationExpressionSyntax)(compilation, "a.vb") Assert.Equal("System.Char", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason) Assert.Equal(1, semanticInfo.CandidateSymbols.Length) Dim sortedCandidates = semanticInfo.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("ReadOnly Property System.String.Chars(index As System.Int32) As System.Char", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.Property, sortedCandidates(0).Kind) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <WorkItem(541567, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541567")> <ConditionalFact(GetType(WindowsOnly), Reason:="https://github.com/dotnet/roslyn/issues/29531")> Public Sub NoMatchingOverloads4() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Module Program Sub Main(args As String()) Dim a As New C1() Dim b As Integer b = a(5, 6, 7)'BIND:"a(5, 6, 7)" b = a.P1(5, 6, 7) End Sub End Module Class C1 Public Default Property P1(x As Integer) As String Get Return "hello" End Get Set(ByVal value As String) End Set End Property Public Default Property P1(x As Integer, y As Integer) As String Get Return "hi" End Get Set(ByVal value As String) End Set End Property End Class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of InvocationExpressionSyntax)(compilation, "a.vb") Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.NarrowingString, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason) Assert.Equal(2, semanticInfo.CandidateSymbols.Length) Dim sortedCandidates = semanticInfo.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Property C1.P1(x As System.Int32) As System.String", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.Property, sortedCandidates(0).Kind) Assert.Equal("Property C1.P1(x As System.Int32, y As System.Int32) As System.String", sortedCandidates(1).ToTestDisplayString()) Assert.Equal(SymbolKind.Property, sortedCandidates(1).Kind) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <WorkItem(540580, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540580")> <Fact()> Public Sub PropertyPassedByRef() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Class C Private Sub M() S(P)'BIND:"P" End Sub Public Property P As String Private Sub S(ByRef a As String) End Sub End Class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Property C.P As System.String", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Property, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub InvocationWithNoMatchingOverloadsAndNonMatchingReturnTypes() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class C Private Sub M() Dim x As String = F()'BIND:"F()" End Sub Private Function F(arg As Integer) As String Return "Hello" End Function Private Function F(arg As String) As Integer Return "Goodbye" End Function End Class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of InvocationExpressionSyntax)(compilation, "a.vb") Assert.Equal("?", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind) Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.DelegateRelaxationLevelNone, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason) Assert.Equal(2, semanticInfo.CandidateSymbols.Length) Dim sortedCandidates = semanticInfo.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Function C.F(arg As System.Int32) As System.String", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(0).Kind) Assert.Equal("Function C.F(arg As System.String) As System.Int32", sortedCandidates(1).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(1).Kind) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub IncompleteInvocation() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class C Private Sub M() Dim x As String = F(:'BIND:"F(" End Sub Private Function F(arg As Integer) As String Return "Hello" End Function Private Function F(arg As String) As String Return "Goodbye" End Function End Class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of InvocationExpressionSyntax)(compilation, "a.vb") Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason) Assert.Equal(2, semanticInfo.CandidateSymbols.Length) Dim sortedCandidates = semanticInfo.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Function C.F(arg As System.Int32) As System.String", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(0).Kind) Assert.Equal("Function C.F(arg As System.String) As System.String", sortedCandidates(1).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(1).Kind) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub TypeNameInsideMethod() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class C Public Sub Main() Dim cInstance As C'BIND:"C" End Sub End Class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("C", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("C", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("C", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub TypeNameInsideMethodWithConflictingLocal() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class C Public Sub Main() Dim cInstance As C'BIND:"C" Dim C As String End Sub End Class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("C", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("C", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("C", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub TypeNameOutsideMethod() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class C Public Sub Main(ByVal arg As D)'BIND:"D" End Sub End Class Class D End Class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("D", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("D", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("D", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub NamespaceName() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class C Private Sub M() Dim x As System.String = F()'BIND:"System" End Sub Private Function F() As String Return "Hello" End Function End Class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticInfo.Type) Assert.Null(semanticInfo.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("System", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Namespace, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub NamespaceNameInDeclaration() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class C Private Sub M(arg As System.String)'BIND:"System" End Sub End Class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticInfo.Type) Assert.Null(semanticInfo.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("System", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Namespace, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub NamespaceNameWithConflictingField() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class C Private Sub M() Dim x As System.String = F()'BIND:"System" End Sub Private Function F() As String Return "Hello" End Function Public System As Integer End Class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticInfo.Type) Assert.Null(semanticInfo.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("System", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Namespace, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub MissingNamespaceName() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class C Private Sub M() Dim x As Baz.Goo.String'BIND:"Goo" End Sub Private Function F() As String Return "Hello" End Function End Class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("Baz.Goo", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind) Assert.Equal("Baz.Goo", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub RightSideOfQualifiedName() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Public Class C Sub M() Dim x As N.D = Nothing'BIND:"D" End Sub End Class Public Class D End Class Namespace N Public Class D End Class End Namespace ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("N.D", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("N.D", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("N.D", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub RHSInDeclaration() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class C Private Sub M(arg As System.String)'BIND:"String" End Sub End Class Class [String] End Class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("System.String", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub ImportsRHS() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports NS1.NS2'BIND:"NS2" ]]></file> <file name="b.vb"><![CDATA[ Namespace NS1 Namespace NS2 Class X End Class End Namespace End Namespace ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticInfo.Type) Assert.Null(semanticInfo.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("NS1.NS2", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Namespace, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub ImportsLHS() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports NS1.NS2'BIND:"NS1" ]]></file> <file name="b.vb"><![CDATA[ Namespace NS1 Namespace NS2 Class X End Class End Namespace End Namespace ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticInfo.Type) Assert.Null(semanticInfo.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("NS1", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Namespace, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub AmbiguousType() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Public Class C Sub M() Dim x As AAA'BIND:"AAA" End Sub End Class ]]></file> <file name="b.vb"><![CDATA[ Module Q Class AAA End Class End Module Module R Class AAA End Class End Module ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("AAA", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind) Assert.Equal("AAA", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.Ambiguous, semanticInfo.CandidateReason) Assert.Equal(2, semanticInfo.CandidateSymbols.Length) Dim sortedCandidates = semanticInfo.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Q.AAA", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, sortedCandidates(0).Kind) Assert.Equal("R.AAA", sortedCandidates(1).ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, sortedCandidates(1).Kind) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub AmbiguousField() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Public Class C Sub M() Dim x As String x = elvis'BIND:"elvis" End Sub End Class ]]></file> <file name="b.vb"><![CDATA[ Module Q Public elvis As Integer End Module Module R Public elvis As String End Module ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("?", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind) Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(Nothing, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.Ambiguous, semanticInfo.CandidateReason) Assert.Equal(2, semanticInfo.CandidateSymbols.Length) Dim sortedCandidates = semanticInfo.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Q.elvis As System.Int32", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.Field, sortedCandidates(0).Kind) Assert.Equal("R.elvis As System.String", sortedCandidates(1).ToTestDisplayString()) Assert.Equal(SymbolKind.Field, sortedCandidates(1).Kind) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub InNamespaceDeclaration() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Namespace AAA.BBB'BIND:"AAA" Class AAA End Class End Namespace ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticInfo.Type) Assert.Null(semanticInfo.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("AAA", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Namespace, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub LocalInitializerWithConversion() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Public Class C Sub M() Dim x As Long = 5, y As Double = 17'BIND:"5" End Sub End Class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of LiteralExpressionSyntax)(compilation, "a.vb") Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int64", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.WideningNumeric, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.True(semanticInfo.ConstantValue.HasValue) Assert.Equal(5, semanticInfo.ConstantValue.Value) End Sub <Fact()> Public Sub LocalInitializerWithConversion2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Public Class C Sub M() Dim x As Long = 5, y As Double = 17'BIND:"17" End Sub End Class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of LiteralExpressionSyntax)(compilation, "a.vb") Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Double", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.WideningNumeric, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.True(semanticInfo.ConstantValue.HasValue) Assert.Equal(17, semanticInfo.ConstantValue.Value) End Sub <Fact()> Public Sub ArgumentWithParentConversion() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Public Class C Sub M() Dim x As Integer = 5 Dim y As Long = func(x)'BIND:"x" End Sub Function func(x As Long) As Long Return x End Function End Class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int64", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.WideningNumeric, semanticInfo.ImplicitConversion.Kind) Assert.Equal("x As System.Int32", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub LocalWithConversionInParent() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Public Class C Sub M() Dim x As Integer = 5 Dim y As Long = x'BIND:"x" End Sub End Class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int64", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.WideningNumeric, semanticInfo.ImplicitConversion.Kind) Assert.Equal("x As System.Int32", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <WorkItem(539179, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539179")> <Fact()> Public Sub LocalWithConversionInParent2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Public Class C Sub M() Dim x As UShort = 99 + 1 Dim y As ULong y = x'BIND:"x" End Sub End Class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("System.UInt16", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.UInt64", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.WideningNumeric, semanticInfo.ImplicitConversion.Kind) Assert.Equal("x As System.UInt16", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub FieldInitializer() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class C Private F = 1 + G()'BIND:"1 + G()" Shared Function G() As Integer Return 1 End Function End Class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of BinaryExpressionSyntax)(compilation, "a.vb") Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.WideningValue, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Function System.Int32.op_Addition(left As System.Int32, right As System.Int32) As System.Int32", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub AutoPropertyInitializers() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class C Private Const F As Integer = 1 Property P = 1 + F'BIND:"1 + F" End Class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of BinaryExpressionSyntax)(compilation, "a.vb") Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.WideningValue, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Function System.Int32.op_Addition(left As System.Int32, right As System.Int32) As System.Int32", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.True(semanticInfo.ConstantValue.HasValue) Assert.Equal(2, semanticInfo.ConstantValue.Value) End Sub <WorkItem(541562, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541562")> <Fact()> Public Sub ObjectCreationInAsNew() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Class C1 Dim Scen2 As New C2() 'BIND:"New C2()" Class C2 Class C3 End Class End Class End Class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of ObjectCreationExpressionSyntax)(compilation, "a.vb") Assert.NotNull(semanticInfo.Type) Assert.Equal("C1.C2", semanticInfo.Type.ToString()) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.False(semanticInfo.ConstantValue.HasValue) CompilationUtils.AssertNoErrors(compilation) End Sub <WorkItem(541563, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541563")> <Fact()> Public Sub NewDelegateCreation() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Module Test Delegate Sub DSub() Sub DMethod() End Sub Sub Main() Dim dd As DSub = New DSub(AddressOf DMethod) 'BIND:"New DSub(AddressOf DMethod)" End Sub End Module ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of ObjectCreationExpressionSyntax)(compilation, "a.vb") Assert.NotNull(semanticInfo.Type) Assert.Equal("Test.DSub", semanticInfo.Type.ToString()) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.False(semanticInfo.ConstantValue.HasValue) CompilationUtils.AssertNoErrors(compilation) End Sub <WorkItem(541581, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541581")> <Fact()> Public Sub ImplicitConversionTestFieldInit() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Module Module1 Dim x1 As Long = 44 'BIND:"44" Sub Main(ByVal args As String()) End Sub End Module ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of LiteralExpressionSyntax)(compilation, "a.vb") Assert.Equal(System_Int32, semanticInfo.Type.SpecialType) Assert.True(semanticInfo.ConstantValue.HasValue) Assert.Equal(44, semanticInfo.ConstantValue.Value) Assert.True(semanticInfo.ImplicitConversion.IsWidening) Assert.Equal(ConversionKind.WideningNumeric, semanticInfo.ImplicitConversion.Kind) Assert.Equal(System_Int64, semanticInfo.ConvertedType.SpecialType) End Sub <Fact()> Public Sub IdentityCIntConversion() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Module Program Sub Main(args As String()) Dim x As Integer = 7 Dim y As Integer y = CInt(x)'BIND:"CInt(x)" End Sub End Module ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of PredefinedCastExpressionSyntax)(compilation, "a.vb") Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <WorkItem(528541, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528541")> <Fact()> Public Sub ImplicitConversionTestLongNumericToInteger() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Module Program Sub Main(args As String()) Dim x1 As Integer = 45L 'BIND:"45L" End Sub End Module ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of LiteralExpressionSyntax)(compilation, "a.vb") Assert.Equal(System_Int64, semanticInfo.Type.SpecialType) Assert.True(semanticInfo.ConstantValue.HasValue) Assert.Equal(45L, semanticInfo.ConstantValue.Value) Assert.Equal(System_Int32, semanticInfo.ConvertedType.SpecialType) ' Perhaps surprisingly, this is a widening conversion. ' Section 8.8: Widening conversions: ' From a constant expression of type ULong, Long, UInteger, Integer, UShort, Short, Byte, or SByte ' to a narrower type, provided the value of the constant expression is within the range of the destination type. Assert.True(semanticInfo.ImplicitConversion.IsNumeric) Assert.False(semanticInfo.ImplicitConversion.IsNarrowing) Assert.True(semanticInfo.ImplicitConversion.IsWidening) Assert.True((semanticInfo.ImplicitConversion.Kind And ConversionKind.InvolvesNarrowingFromNumericConstant) <> 0, "includes bit InvolvesNarrowingFromNumericConstant") End Sub <WorkItem(541596, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541596")> <Fact()> Public Sub ImplicitConversionExprReturnedByLambda() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Module Program Dim x1 As Func(Of Long) = Function() 45 'BIND:"45" End Module ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of LiteralExpressionSyntax)(compilation, "a.vb") Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int64", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.WideningNumeric, semanticInfo.ImplicitConversion.Kind) Assert.False(semanticInfo.ImplicitConversion.IsIdentity) Assert.False(semanticInfo.ImplicitConversion.IsNarrowing) Assert.True(semanticInfo.ImplicitConversion.IsNumeric) Assert.True(semanticInfo.ImplicitConversion.IsWidening) Assert.True(semanticInfo.ConstantValue.HasValue) Assert.Equal(45, semanticInfo.ConstantValue.Value) End Sub <WorkItem(541608, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541608")> <Fact()> Public Sub IncompleteAttributeOnMethod() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class B <A( Sub Main() 'BIND:"Main" End Sub End Class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.NotNull(semanticInfo) Assert.Equal(SymbolKind.ErrorType, semanticInfo.Type.Kind) End Sub <WorkItem(541625, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541625")> <Fact()> Public Sub ImplicitConvExtensionMethodReceiver() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndReferences( <compilation> <file name="a.vb"><![CDATA[ Imports System.Runtime.CompilerServices Module StringExtensions <Extension()> Public Sub Print(ByVal aString As Object) End Sub End Module Module Program Sub Main(args As String()) Dim example As String = "Hello" example.Print()'BIND:"example" End Sub End Module ]]></file> </compilation>, {TestMetadata.Net40.SystemCore}) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.WideningReference, semanticInfo.ImplicitConversion.Kind) Assert.True(semanticInfo.ImplicitConversion.IsReference) Assert.True(semanticInfo.ImplicitConversion.IsWidening) Assert.Equal("example As System.String", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind) End Sub <Fact()> Public Sub NamedArgument1() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Public Class Class1 Public Sub f(a As Integer) End Sub Public Sub f(b As Integer, a As String) End Sub End Class Public Module M1 Sub goo() Dim x As New Class1 x.f(4, a:="hello")'BIND:"a" End Sub End Module ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticInfo.Type) Assert.Null(semanticInfo.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("a As System.String", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Parameter, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub NamedArgument2() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Public Class Class1 Public Sub f(a As Integer) End Sub Public Sub f(b As Integer, a As String) End Sub Public Sub f(q As Integer, b As String, c As Integer) End Sub Public Sub f(q As Integer, b As String, c As Guid) End Sub End Class Public Module M1 Sub goo() Dim x As New Class1 x.f(4, "hithere", b:="hello")'BIND:"b" End Sub End Module ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticInfo.Type) Assert.Null(semanticInfo.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason) Assert.Equal(2, semanticInfo.CandidateSymbols.Length) Dim sortedCandidates = semanticInfo.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString() & s.ContainingSymbol.ToTestDisplayString()).ToArray() Assert.Equal("b As System.String", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.Parameter, sortedCandidates(0).Kind) Assert.Equal("Sub Class1.f(q As System.Int32, b As System.String, c As System.Guid)", sortedCandidates(0).ContainingSymbol.ToTestDisplayString()) Assert.Equal("b As System.String", sortedCandidates(1).ToTestDisplayString()) Assert.Equal(SymbolKind.Parameter, sortedCandidates(1).Kind) Assert.Equal("Sub Class1.f(q As System.Int32, b As System.String, c As System.Int32)", sortedCandidates(1).ContainingSymbol.ToTestDisplayString()) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub NamedArgument3() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Public Class Class1 Public Sub f(a As Integer) End Sub Public Sub f(b As Integer, a As String) End Sub Public Sub f(q As Integer, b As String, c As Integer) End Sub Public Sub f(q As Integer, b As String, c As Guid) End Sub End Class Public Module M1 Sub goo() Dim x As New Class1 x.f(4, "hithere", zappa:="hello")'BIND:"zappa" End Sub End Module ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticInfo.Type) Assert.Null(semanticInfo.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub NamedArgumentInOnProperty() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Public Class Class1 Public ReadOnly Property f(a As Integer) As Integer Get Return 1 End Get End Property Public ReadOnly Property f(b As Integer, a As String) Get Return 1 End Get End Property Public ReadOnly Property f(q As Integer, b As String, c As Integer) Get Return 1 End Get End Property Public ReadOnly Property f(q As Integer, b As String, c As Guid) Get Return 1 End Get End Property End Class Public Module M1 Sub goo() Dim x As New Class1 Dim y As Integer = x.f(4, c:=12, b:="hi") 'BIND:"c"'BIND:"c" End Sub End Module ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticInfo.Type) Assert.Null(semanticInfo.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("c As System.Int32", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Parameter, semanticInfo.Symbol.Kind) Assert.Equal("ReadOnly Property Class1.f(q As System.Int32, b As System.String, c As System.Int32) As System.Object", semanticInfo.Symbol.ContainingSymbol.ToTestDisplayString()) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <WorkItem(541412, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541412")> <Fact()> Public Sub TestGetSemanticInfoFromAttributeSyntax_Error_MissingSystemImport() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class AAttribute Inherits Attribute Public Sub New() End Sub End Class Class B <A()> 'BIND:"A()" Sub S() End Sub End Class ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of AttributeSyntax)(compilation, "a.vb") Assert.Equal("AAttribute", semanticSummary.Type.ToTestDisplayString()) Assert.Equal("AAttribute", semanticSummary.ConvertedType.ToTestDisplayString()) Assert.Null(semanticSummary.Symbol) Assert.Equal(CandidateReason.NotAnAttributeType, semanticSummary.CandidateReason) Assert.Equal(1, semanticSummary.CandidateSymbols.Length) Dim sortedCandidates = semanticSummary.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString() & s.ContainingSymbol.ToTestDisplayString()).ToArray() Assert.Equal("Sub AAttribute..ctor()", sortedCandidates(0).ToTestDisplayString()) Assert.Null(semanticSummary.Alias) Assert.Equal(1, semanticSummary.MemberGroup.Length) Dim sortedMethodGroup = semanticSummary.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub AAttribute..ctor()", sortedMethodGroup(0).ToTestDisplayString()) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact()> Public Sub TestGetSemanticInfoFromAttributeSyntax_Error_MustInheritAttributeClass() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System MustInherit Class AAttribute Inherits Attribute Public Sub New() End Sub ' Inaccessible constructors shouldn't appear in semantic info method group. Private Sub New(x as Integer) End Sub End Class Class B <A()>'BIND:"A()" Sub S() End Sub End Class ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of AttributeSyntax)(compilation, "a.vb") Assert.Equal("AAttribute", semanticSummary.Type.ToTestDisplayString()) Assert.Equal("AAttribute", semanticSummary.ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Null(semanticSummary.Symbol) Assert.Equal(CandidateReason.NotAnAttributeType, semanticSummary.CandidateReason) Assert.Equal(1, semanticSummary.CandidateSymbols.Length) Dim sortedCandidates = semanticSummary.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub AAttribute..ctor()", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(0).Kind) Assert.Null(semanticSummary.Alias) Assert.Equal(1, semanticSummary.MemberGroup.Length) Dim sortedMethodGroup = semanticSummary.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub AAttribute..ctor()", sortedMethodGroup(0).ToTestDisplayString()) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact()> Public Sub TestGetSemanticInfoFromIdentifierSyntax_Error_MustInheritAttributeClass() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System MustInherit Class AAttribute Inherits Attribute Public Sub New() End Sub End Class Class B <A()>'BIND:"A" Sub S() End Sub End Class ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("AAttribute", semanticSummary.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.Type.TypeKind) Assert.Equal("AAttribute", semanticSummary.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Null(semanticSummary.Symbol) Assert.Equal(CandidateReason.NotAnAttributeType, semanticSummary.CandidateReason) Assert.Equal(1, semanticSummary.CandidateSymbols.Length) Dim sortedCandidates = semanticSummary.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub AAttribute..ctor()", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(0).Kind) Assert.Null(semanticSummary.Alias) Assert.Equal(1, semanticSummary.MemberGroup.Length) Dim sortedMethodGroup = semanticSummary.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub AAttribute..ctor()", sortedMethodGroup(0).ToTestDisplayString()) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact()> Public Sub TestGetSemanticInfoFromAttributeSyntax_Error_GenericAttributeClass() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Class AAttribute(Of T) Public Sub New() End Sub End Class Class B <AAttribute()>'BIND:"AAttribute()" Sub S() End Sub End Class ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of AttributeSyntax)(compilation, "a.vb") Assert.Equal("AAttribute(Of T)", semanticSummary.Type.ToTestDisplayString()) Assert.Equal("AAttribute(Of T)", semanticSummary.ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Null(semanticSummary.Symbol) Assert.Equal(CandidateReason.WrongArity, semanticSummary.CandidateReason) Assert.Equal(1, semanticSummary.CandidateSymbols.Length) Dim sortedCandidates = semanticSummary.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub AAttribute(Of T)..ctor()", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(0).Kind) Assert.Null(semanticSummary.Alias) Assert.Equal(1, semanticSummary.MemberGroup.Length) Dim sortedMethodGroup = semanticSummary.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub AAttribute(Of T)..ctor()", sortedMethodGroup(0).ToTestDisplayString()) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <WorkItem(539822, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539822")> <Fact()> Public Sub UseTypeAsVariable() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Module Program Sub Main(args As String()) [String] = "hello"'BIND:"[String]" End Sub End Module ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.NotAValue, semanticInfo.CandidateReason) Assert.Equal(1, semanticInfo.CandidateSymbols.Length) Dim sortedCandidates = semanticInfo.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("System.String", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, sortedCandidates(0).Kind) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub ForEachWithOneDimensionalArray() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports System Class C1 Public Shared Sub Main() Dim arr As Integer() = New Integer(1) {} arr(0) = 23 arr(1) = 42 For Each element as Integer In arr 'BIND:"For Each element as Integer In arr" Console.WriteLine(element) Next End Sub End Class ]]></file> </compilation>) Dim getEnumerator = DirectCast(DirectCast(compilation.GetSpecialType(System_Array), TypeSymbol).GetMember("GetEnumerator"), MethodSymbol) Dim moveNext = DirectCast(compilation.GetSpecialType(System_Object).ContainingAssembly.GetSpecialTypeMember(SpecialMember.System_Collections_IEnumerator__MoveNext), MethodSymbol) Dim current = DirectCast(compilation.GetSpecialType(System_Object).ContainingAssembly.GetSpecialTypeMember(SpecialMember.System_Collections_IEnumerator__Current), PropertySymbol) Dim dispose = DirectCast(compilation.GetSpecialType(System_Object).ContainingAssembly.GetSpecialTypeMember(SpecialMember.System_IDisposable__Dispose), MethodSymbol) For Each useInterface In {True, False} For Each useBlock In {True, False} Dim semanticInfoEx As ForEachStatementInfo If useInterface Then semanticInfoEx = DirectCast(GetBlockOrStatementInfoForTest(Of ForEachStatementSyntax, SemanticModel)(compilation, "a.vb", useParent:=useBlock), ForEachStatementInfo) Else semanticInfoEx = DirectCast(GetBlockOrStatementInfoForTest(Of ForEachStatementSyntax, VBSemanticModel)(compilation, "a.vb", useParent:=useBlock), ForEachStatementInfo) End If Assert.Equal(getEnumerator, semanticInfoEx.GetEnumeratorMethod) Assert.Equal(moveNext, semanticInfoEx.MoveNextMethod) Assert.Equal(current, semanticInfoEx.CurrentProperty) Assert.Equal(dispose, semanticInfoEx.DisposeMethod) Next Next End Sub <Fact()> Public Sub ForEachWithMultiDimensionalArray() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports System Class C1 Public Shared Sub Main() Dim arr(1,1) As Integer arr(0,0) = 1 arr(0,1) = 2 arr(1,0) = 3 arr(1,1) = 4 For Each element as Integer In arr 'BIND:"For Each element as Integer In arr" Console.WriteLine(element) Next End Sub End Class ]]></file> </compilation>) Dim getEnumerator = DirectCast(DirectCast(compilation.GetSpecialType(System_Array), TypeSymbol).GetMember("GetEnumerator"), MethodSymbol) Dim moveNext = DirectCast(compilation.GetSpecialType(System_Object).ContainingAssembly.GetSpecialTypeMember(SpecialMember.System_Collections_IEnumerator__MoveNext), MethodSymbol) Dim current = DirectCast(compilation.GetSpecialType(System_Object).ContainingAssembly.GetSpecialTypeMember(SpecialMember.System_Collections_IEnumerator__Current), PropertySymbol) Dim dispose = DirectCast(compilation.GetSpecialType(System_Object).ContainingAssembly.GetSpecialTypeMember(SpecialMember.System_IDisposable__Dispose), MethodSymbol) For Each useInterface In {True, False} For Each useBlock In {True, False} Dim semanticInfoEx As ForEachStatementInfo If useInterface Then semanticInfoEx = DirectCast(GetBlockOrStatementInfoForTest(Of ForEachStatementSyntax, SemanticModel)(compilation, "a.vb", useParent:=useBlock), ForEachStatementInfo) Else semanticInfoEx = DirectCast(GetBlockOrStatementInfoForTest(Of ForEachStatementSyntax, VBSemanticModel)(compilation, "a.vb", useParent:=useBlock), ForEachStatementInfo) End If Assert.Equal(getEnumerator, semanticInfoEx.GetEnumeratorMethod) Assert.Equal(moveNext, semanticInfoEx.MoveNextMethod) Assert.Equal(current, semanticInfoEx.CurrentProperty) Assert.Equal(dispose, semanticInfoEx.DisposeMethod) Next Next End Sub <Fact()> Public Sub ForEachOverString() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Option Infer On Imports System Class C1 Public Shared Sub Main() Dim coll as String = "Hello!" For Each element In coll 'BIND:"For Each element In coll" Console.WriteLine(element) Next End Sub End Class ]]></file> </compilation>) Dim getEnumerator = DirectCast(DirectCast(compilation.GetSpecialType(System_String), TypeSymbol).GetMember("GetEnumerator"), MethodSymbol) Dim moveNext = DirectCast(getEnumerator.ReturnType.GetMember("MoveNext"), MethodSymbol) Dim current = DirectCast(getEnumerator.ReturnType.GetMember("get_Current"), MethodSymbol) Dim dispose = DirectCast(compilation.GetSpecialType(System_Object).ContainingAssembly.GetSpecialTypeMember(SpecialMember.System_IDisposable__Dispose), MethodSymbol) For Each useInterface In {True, False} For Each useBlock In {True, False} Dim semanticInfoEx As ForEachStatementInfo If useInterface Then semanticInfoEx = DirectCast(GetBlockOrStatementInfoForTest(Of ForEachStatementSyntax, SemanticModel)(compilation, "a.vb", useParent:=useBlock), ForEachStatementInfo) Else semanticInfoEx = DirectCast(GetBlockOrStatementInfoForTest(Of ForEachStatementSyntax, VBSemanticModel)(compilation, "a.vb", useParent:=useBlock), ForEachStatementInfo) End If Assert.Equal(getEnumerator, semanticInfoEx.GetEnumeratorMethod) Assert.Equal(moveNext, semanticInfoEx.MoveNextMethod) Assert.Equal(DirectCast(current.AssociatedSymbol, PropertySymbol), semanticInfoEx.CurrentProperty) Assert.Equal(dispose, semanticInfoEx.DisposeMethod) Next Next End Sub <Fact()> Public Sub ForEachCustomCollection() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports System Imports System.Collections Class Custom Public Function GetEnumerator() As CustomEnumerator Return Nothing End Function Public Class CustomEnumerator Public Function MoveNext() As Boolean Return False End Function Public ReadOnly Property Current As Custom Get Return Nothing End Get End Property End Class End Class Class C1 Public Shared Sub Main() Dim myCustomCollection As Custom = nothing For Each element as Custom In myCustomCollection 'BIND:"For Each element as Custom In myCustomCollection" Console.WriteLine("goo") Next End Sub End Class ]]></file> </compilation>) Dim getEnumerator = DirectCast(compilation.GlobalNamespace.GetTypeMember("Custom").GetMember("GetEnumerator"), MethodSymbol) Dim moveNext = DirectCast(compilation.GlobalNamespace.GetTypeMember("Custom").GetTypeMember("CustomEnumerator").GetMember("MoveNext"), MethodSymbol) Dim current = DirectCast(compilation.GlobalNamespace.GetTypeMember("Custom").GetTypeMember("CustomEnumerator").GetMember("Current"), PropertySymbol) For Each useInterface In {True, False} For Each useBlock In {True, False} Dim semanticInfoEx As ForEachStatementInfo If useInterface Then semanticInfoEx = DirectCast(GetBlockOrStatementInfoForTest(Of ForEachStatementSyntax, SemanticModel)(compilation, "a.vb", useParent:=useBlock), ForEachStatementInfo) Else semanticInfoEx = DirectCast(GetBlockOrStatementInfoForTest(Of ForEachStatementSyntax, VBSemanticModel)(compilation, "a.vb", useParent:=useBlock), ForEachStatementInfo) End If Assert.Equal(getEnumerator, semanticInfoEx.GetEnumeratorMethod) Assert.Equal(moveNext, semanticInfoEx.MoveNextMethod) Assert.Equal(current, semanticInfoEx.CurrentProperty) Assert.Null(semanticInfoEx.DisposeMethod) Next Next End Sub <Fact()> Public Sub ForEachCustomCollectionWithDispose() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports System Imports System.Collections Class Custom Public Function GetEnumerator() As CustomEnumerator Return Nothing End Function Public Class CustomEnumerator Implements IDisposable Public Function MoveNext() As Boolean Return False End Function Public ReadOnly Property Current As Custom Get Return Nothing End Get End Property Public Sub Dispose() implements IDisposable.Dispose End Sub End Class End Class Class C1 Public Shared Sub Main() Dim myCustomCollection As Custom = nothing For Each element as Custom In myCustomCollection 'BIND:"For Each element as Custom In myCustomCollection" Console.WriteLine("goo") Next End Sub End Class ]]></file> </compilation>) Dim getEnumerator = DirectCast(compilation.GlobalNamespace.GetTypeMember("Custom").GetMember("GetEnumerator"), MethodSymbol) Dim moveNext = DirectCast(compilation.GlobalNamespace.GetTypeMember("Custom").GetTypeMember("CustomEnumerator").GetMember("MoveNext"), MethodSymbol) Dim current = DirectCast(compilation.GlobalNamespace.GetTypeMember("Custom").GetTypeMember("CustomEnumerator").GetMember("Current"), PropertySymbol) Dim dispose = DirectCast(compilation.GetSpecialType(System_Object).ContainingAssembly.GetSpecialTypeMember(SpecialMember.System_IDisposable__Dispose), MethodSymbol) For Each useInterface In {True, False} For Each useBlock In {True, False} Dim semanticInfoEx As ForEachStatementInfo If useInterface Then semanticInfoEx = DirectCast(GetBlockOrStatementInfoForTest(Of ForEachStatementSyntax, SemanticModel)(compilation, "a.vb", useParent:=useBlock), ForEachStatementInfo) Else semanticInfoEx = DirectCast(GetBlockOrStatementInfoForTest(Of ForEachStatementSyntax, VBSemanticModel)(compilation, "a.vb", useParent:=useBlock), ForEachStatementInfo) End If Assert.Equal(getEnumerator, semanticInfoEx.GetEnumeratorMethod) Assert.Equal(moveNext, semanticInfoEx.MoveNextMethod) Assert.Equal(current, semanticInfoEx.CurrentProperty) Assert.Equal(dispose, semanticInfoEx.DisposeMethod) Next Next End Sub <Fact()> Public Sub ForEachCustomCollectionWithDisposeError() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports System Imports System.Collections Class Custom Public Function GetEnumerator() As CustomEnumerator Return Nothing End Function Public Class CustomEnumerator Implements IDisposable Public Function MoveNext() As Boolean Return False End Function Public ReadOnly Property Current As Custom Get Return Nothing End Get End Property End Class End Class Class C1 Public Shared Sub Main() Dim myCustomCollection As Custom = nothing For Each element as Custom In myCustomCollection 'BIND:"For Each element as Custom In myCustomCollection" Console.WriteLine("goo") Next End Sub End Class ]]></file> </compilation>) AssertTheseDiagnostics(compilation, <expected> BC30149: Class 'CustomEnumerator' must implement 'Sub Dispose()' for interface 'IDisposable'. Implements IDisposable ~~~~~~~~~~~ </expected>) Dim getEnumerator = DirectCast(compilation.GlobalNamespace.GetTypeMember("Custom").GetMember("GetEnumerator"), MethodSymbol) Dim moveNext = DirectCast(compilation.GlobalNamespace.GetTypeMember("Custom").GetTypeMember("CustomEnumerator").GetMember("MoveNext"), MethodSymbol) Dim current = DirectCast(compilation.GlobalNamespace.GetTypeMember("Custom").GetTypeMember("CustomEnumerator").GetMember("Current"), PropertySymbol) ' the type claimed to implement IDisposable and we believed it ... Dim dispose = DirectCast(compilation.GetSpecialType(System_Object).ContainingAssembly.GetSpecialTypeMember(SpecialMember.System_IDisposable__Dispose), MethodSymbol) For Each useInterface In {True, False} For Each useBlock In {True, False} Dim semanticInfoEx As ForEachStatementInfo If useInterface Then semanticInfoEx = DirectCast(GetBlockOrStatementInfoForTest(Of ForEachStatementSyntax, SemanticModel)(compilation, "a.vb", useParent:=useBlock), ForEachStatementInfo) Else semanticInfoEx = DirectCast(GetBlockOrStatementInfoForTest(Of ForEachStatementSyntax, VBSemanticModel)(compilation, "a.vb", useParent:=useBlock), ForEachStatementInfo) End If Assert.Equal(getEnumerator, semanticInfoEx.GetEnumeratorMethod) Assert.Equal(moveNext, semanticInfoEx.MoveNextMethod) Assert.Equal(current, semanticInfoEx.CurrentProperty) Assert.Equal(dispose, semanticInfoEx.DisposeMethod) Next Next End Sub <Fact()> Public Sub ForEachCustomCollectionWithMissingMoveNext() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports System Imports System.Collections Class Custom Public Function GetEnumerator() As CustomEnumerator Return Nothing End Function Public Class CustomEnumerator Implements IDisposable Public ReadOnly Property Current As Custom Get Return Nothing End Get End Property Public Sub Dispose() implements IDisposable.Dispose End Sub End Class End Class Class C1 Public Shared Sub Main() Dim myCustomCollection As Custom = nothing For Each element as Custom In myCustomCollection 'BIND:"For Each element as Custom In myCustomCollection" Console.WriteLine("goo") Next End Sub End Class ]]></file> </compilation>) Dim getEnumerator = DirectCast(compilation.GlobalNamespace.GetTypeMember("Custom").GetMember("GetEnumerator"), MethodSymbol) For Each useInterface In {True, False} For Each useBlock In {True, False} Dim semanticInfoEx As ForEachStatementInfo If useInterface Then semanticInfoEx = DirectCast(GetBlockOrStatementInfoForTest(Of ForEachStatementSyntax, SemanticModel)(compilation, "a.vb", useParent:=useBlock), ForEachStatementInfo) Else semanticInfoEx = DirectCast(GetBlockOrStatementInfoForTest(Of ForEachStatementSyntax, VBSemanticModel)(compilation, "a.vb", useParent:=useBlock), ForEachStatementInfo) End If Assert.Equal(getEnumerator, semanticInfoEx.GetEnumeratorMethod) ' methods are partly present up to the point where the pattern was violated. Assert.Null(semanticInfoEx.MoveNextMethod) Assert.Null(semanticInfoEx.CurrentProperty) Assert.Null(semanticInfoEx.DisposeMethod) Next Next End Sub <Fact()> Public Sub ForEachNotMatchingDesignPatternIEnumerable() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class C Public Shared Sub Main() For Each x In New Enumerable() 'BIND:"For Each x In New Enumerable()" System.Console.WriteLine(x) Next End Sub End Class Class Enumerable Implements System.Collections.IEnumerable ' Explicit implementation won't match pattern. Private Function System_Collections_IEnumerable_GetEnumerator() As System.Collections.IEnumerator Implements System.Collections.IEnumerable.GetEnumerator Dim list As New System.Collections.Generic.List(Of Integer)() list.Add(3) list.Add(2) list.Add(1) Return list.GetEnumerator() End Function End Class ]]></file> </compilation>) Dim getEnumerator = DirectCast(compilation.GetSpecialType(System_Object).ContainingAssembly.GetSpecialTypeMember(SpecialMember.System_Collections_IEnumerable__GetEnumerator), MethodSymbol) Dim moveNext = DirectCast(compilation.GetSpecialType(System_Object).ContainingAssembly.GetSpecialTypeMember(SpecialMember.System_Collections_IEnumerator__MoveNext), MethodSymbol) Dim current = DirectCast(compilation.GetSpecialType(System_Object).ContainingAssembly.GetSpecialTypeMember(SpecialMember.System_Collections_IEnumerator__Current), PropertySymbol) Dim dispose = DirectCast(compilation.GetSpecialType(System_Object).ContainingAssembly.GetSpecialTypeMember(SpecialMember.System_IDisposable__Dispose), MethodSymbol) For Each useInterface In {True, False} For Each useBlock In {True, False} Dim semanticInfoEx As ForEachStatementInfo If useInterface Then semanticInfoEx = DirectCast(GetBlockOrStatementInfoForTest(Of ForEachStatementSyntax, SemanticModel)(compilation, "a.vb", useParent:=useBlock), ForEachStatementInfo) Else semanticInfoEx = DirectCast(GetBlockOrStatementInfoForTest(Of ForEachStatementSyntax, VBSemanticModel)(compilation, "a.vb", useParent:=useBlock), ForEachStatementInfo) End If Assert.Equal(getEnumerator, semanticInfoEx.GetEnumeratorMethod) Assert.Equal(moveNext, semanticInfoEx.MoveNextMethod) Assert.Equal(current, semanticInfoEx.CurrentProperty) Assert.Equal(dispose, semanticInfoEx.DisposeMethod) Next Next End Sub <Fact()> Public Sub ForEachNotMatchingDesignPatternGenericIEnumerable() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class C Public Shared Sub Main() For Each x In New Enumerable(Of Integer)() 'BIND:"For Each x In New Enumerable(Of Integer)()" System.Console.WriteLine(x) Next End Sub End Class Class Enumerable(Of T) Implements System.Collections.Generic.IEnumerable(Of Integer) ' Explicit implementation won't match pattern. Public Function System_Collections_Generic_IEnumerable_GetEnumerator() As System.Collections.Generic.IEnumerator(Of Integer) Implements System.Collections.Generic.IEnumerable(Of Integer).GetEnumerator Return Nothing End Function Public Function GetEnumerator1() As System.Collections.IEnumerator Implements System.Collections.IEnumerable.GetEnumerator Return Nothing End Function End Class ]]></file> </compilation>) ' IEnumerable is preferred to IEnumerable(Of T) Dim ienumerable = compilation.GetSpecialType(System_Collections_Generic_IEnumerable_T).Construct(ImmutableArray.Create(Of TypeSymbol)(compilation.GetSpecialType(System_Int32))) Dim ienumerator = compilation.GetSpecialType(System_Collections_Generic_IEnumerator_T).Construct(ImmutableArray.Create(Of TypeSymbol)(compilation.GetSpecialType(System_Int32))) Dim getEnumerator = DirectCast(ienumerable.GetMember("GetEnumerator"), MethodSymbol) Dim moveNext = DirectCast(compilation.GetSpecialType(System_Object).ContainingAssembly.GetSpecialTypeMember(SpecialMember.System_Collections_IEnumerator__MoveNext), MethodSymbol) Dim current = DirectCast(ienumerator.GetMember("Current"), PropertySymbol) Dim dispose = DirectCast(compilation.GetSpecialType(System_Object).ContainingAssembly.GetSpecialTypeMember(SpecialMember.System_IDisposable__Dispose), MethodSymbol) For Each useInterface In {True, False} For Each useBlock In {True, False} Dim semanticInfoEx As ForEachStatementInfo If useInterface Then semanticInfoEx = DirectCast(GetBlockOrStatementInfoForTest(Of ForEachStatementSyntax, SemanticModel)(compilation, "a.vb", useParent:=useBlock), ForEachStatementInfo) Else semanticInfoEx = DirectCast(GetBlockOrStatementInfoForTest(Of ForEachStatementSyntax, VBSemanticModel)(compilation, "a.vb", useParent:=useBlock), ForEachStatementInfo) End If Assert.Equal(getEnumerator, semanticInfoEx.GetEnumeratorMethod) Assert.Equal(moveNext, semanticInfoEx.MoveNextMethod) Assert.Equal(current, semanticInfoEx.CurrentProperty) Assert.Equal(dispose, semanticInfoEx.DisposeMethod) Next Next End Sub <Fact()> Public Sub ForEachGenericIEnumerable() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System.Collections.Generic Class C Public Shared Sub Main() Dim collection as IEnumerable(Of Integer) For Each x In collection 'BIND:"For Each x In collection" System.Console.WriteLine(x) Next End Sub End Class ]]></file> </compilation>) ' the first matching symbol on IEnumerable(Of T) Dim moveNext = DirectCast(compilation.GetSpecialType(System_Object).ContainingAssembly.GetSpecialTypeMember(SpecialMember.System_Collections_IEnumerator__MoveNext), MethodSymbol) Dim dispose = DirectCast(compilation.GetSpecialType(System_Object).ContainingAssembly.GetSpecialTypeMember(SpecialMember.System_IDisposable__Dispose), MethodSymbol) For Each useInterface In {True, False} For Each useBlock In {True, False} Dim semanticInfoEx As ForEachStatementInfo If useInterface Then semanticInfoEx = DirectCast(GetBlockOrStatementInfoForTest(Of ForEachStatementSyntax, SemanticModel)(compilation, "a.vb", useParent:=useBlock), ForEachStatementInfo) Else semanticInfoEx = DirectCast(GetBlockOrStatementInfoForTest(Of ForEachStatementSyntax, VBSemanticModel)(compilation, "a.vb", useParent:=useBlock), ForEachStatementInfo) End If Assert.Equal("Function System.Collections.Generic.IEnumerable(Of System.Int32).GetEnumerator() As System.Collections.Generic.IEnumerator(Of System.Int32)", semanticInfoEx.GetEnumeratorMethod.ToDisplayString(SymbolDisplayFormat.TestFormat)) Assert.Equal(moveNext, semanticInfoEx.MoveNextMethod) ' the first matching symbol on IEnumerable(Of T) Assert.Equal("ReadOnly Property System.Collections.Generic.IEnumerator(Of System.Int32).Current As System.Int32", semanticInfoEx.CurrentProperty.ToDisplayString(SymbolDisplayFormat.TestFormat)) Assert.Equal(dispose, semanticInfoEx.DisposeMethod) Next Next End Sub <Fact()> Public Sub ForEachInvalidCollection() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports System Class C1 Public Shared Sub Main() For Each element as Integer In 1 'BIND:"For Each element as Integer In 1" Console.WriteLine(element) Next End Sub End Class ]]></file> </compilation>) For Each useInterface In {True, False} For Each useBlock In {True, False} Dim semanticInfoEx As ForEachStatementInfo If useInterface Then semanticInfoEx = DirectCast(GetBlockOrStatementInfoForTest(Of ForEachStatementSyntax, SemanticModel)(compilation, "a.vb", useParent:=useBlock), ForEachStatementInfo) Else semanticInfoEx = DirectCast(GetBlockOrStatementInfoForTest(Of ForEachStatementSyntax, VBSemanticModel)(compilation, "a.vb", useParent:=useBlock), ForEachStatementInfo) End If Assert.Null(semanticInfoEx.GetEnumeratorMethod) Assert.Null(semanticInfoEx.MoveNextMethod) Assert.Null(semanticInfoEx.CurrentProperty) Assert.Null(semanticInfoEx.DisposeMethod) Next Next End Sub <Fact()> Public Sub ForEachLateBinding() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Option Strict off Class C Public Shared Sub Main() Dim collection as Object = {1, 2, 3} For Each x In collection 'BIND:"For Each x In collection" System.Console.WriteLine(x) Next End Sub End Class ]]></file> </compilation>) ' the first matching symbol on IEnumerable Dim moveNext = DirectCast(compilation.GetSpecialType(System_Object).ContainingAssembly.GetSpecialTypeMember(SpecialMember.System_Collections_IEnumerator__MoveNext), MethodSymbol) Dim dispose = DirectCast(compilation.GetSpecialType(System_Object).ContainingAssembly.GetSpecialTypeMember(SpecialMember.System_IDisposable__Dispose), MethodSymbol) For Each useInterface In {True, False} For Each useBlock In {True, False} Dim semanticInfoEx As ForEachStatementInfo If useInterface Then semanticInfoEx = DirectCast(GetBlockOrStatementInfoForTest(Of ForEachStatementSyntax, SemanticModel)(compilation, "a.vb", useParent:=useBlock), ForEachStatementInfo) Else semanticInfoEx = DirectCast(GetBlockOrStatementInfoForTest(Of ForEachStatementSyntax, VBSemanticModel)(compilation, "a.vb", useParent:=useBlock), ForEachStatementInfo) End If Assert.Equal("Function System.Collections.IEnumerable.GetEnumerator() As System.Collections.IEnumerator", semanticInfoEx.GetEnumeratorMethod.ToDisplayString(SymbolDisplayFormat.TestFormat)) Assert.Equal(moveNext, semanticInfoEx.MoveNextMethod) Assert.Equal("ReadOnly Property System.Collections.IEnumerator.Current As System.Object", semanticInfoEx.CurrentProperty.ToDisplayString(SymbolDisplayFormat.TestFormat)) Assert.Equal(dispose, semanticInfoEx.DisposeMethod) Next Next End Sub <Fact()> Public Sub NewDelegate() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Delegate Sub Del(x As Integer) Module Program Sub Main(args As String()) Dim d As Del d = New Del(AddressOf goo)'BIND:"Del" End Sub Sub goo(x As Integer) End Sub End Module ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticInfo.Type) Assert.Null(semanticInfo.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Del", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub NewDelegate2() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Delegate Sub Del(x As Integer) Module Program Sub Main(args As String()) Dim d As Del d = New Del(AddressOf goo) 'BIND:"New Del(AddressOf goo)" End Sub Sub goo(x As Integer) End Sub End Module ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of ObjectCreationExpressionSyntax)(compilation, "a.vb") Assert.Equal("Del", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Delegate, semanticInfo.Type.TypeKind) Assert.Equal("Del", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Delegate, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub NewDelegateWrongMethodSignature() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Delegate Sub Del(x As Integer) Module Program Sub Main(args As String()) Dim d As Del d = New Del(AddressOf goo)'BIND:"Del" End Sub Sub goo(y As String, z As String) End Sub End Module ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticInfo.Type) Assert.Null(semanticInfo.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Del", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub NewDelegateWrongMethodSignature2() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Delegate Sub Del(x As Integer) Module Program Sub Main(args As String()) Dim d As Del d = New Del(AddressOf goo)'BIND:"New Del(AddressOf goo)" End Sub Sub goo(y As String, z As String) End Sub End Module ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of ObjectCreationExpressionSyntax)(compilation, "a.vb") Assert.Equal("Del", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Delegate, semanticInfo.Type.TypeKind) Assert.Equal("Del", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Delegate, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub NewDelegateOnLambda() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Delegate Sub Del(x As Integer) Module Program Sub Main(args As String()) Dim d As Del d = New Del(Sub(x) Console.WriteLine(x)) 'BIND:"Del"'BIND:"Del" End Sub Sub goo() End Sub End Module ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticInfo.Type) Assert.Null(semanticInfo.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Del", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub NewDelegateOnLambda2() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Delegate Sub Del(x As Integer) Module Program Sub Main(args As String()) Dim d As Del d = New Del(Sub(x) Console.WriteLine(x)) 'BIND:"New Del(Sub(x) Console.WriteLine(x))" End Sub Sub goo() End Sub End Module ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of ObjectCreationExpressionSyntax)(compilation, "a.vb") Assert.Equal("Del", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Delegate, semanticInfo.Type.TypeKind) Assert.Equal("Del", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Delegate, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub NewDelegateOnMismatchedLambda() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Delegate Sub Del(x As Integer) Module Program Sub Main(args As String()) Dim d As Del d = New Del(Sub(x, y) Console.WriteLine(x)) 'BIND:"Del"'BIND:"Del" End Sub Sub goo() End Sub End Module ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticInfo.Type) Assert.Null(semanticInfo.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Del", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub NewDelegateOnMismatchedLambda2() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Delegate Sub Del(x As Integer) Module Program Sub Main(args As String()) Dim d As Del d = New Del(Sub(x, y) Console.WriteLine(x)) 'BIND:"New Del(Sub(x, y) Console.WriteLine(x))" End Sub Sub goo() End Sub End Module ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of ObjectCreationExpressionSyntax)(compilation, "a.vb") Assert.Equal("Del", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Delegate, semanticInfo.Type.TypeKind) Assert.Equal("Del", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Delegate, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub NewOfInaccessibleClass() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Class X Private Class Y End Class End Class Module Program Sub Main(args As String()) Dim o As Object o = New X.Y(3)'BIND:"X.Y" End Sub Sub goo() End Sub End Module ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of QualifiedNameSyntax)(compilation, "a.vb") Assert.Null(semanticInfo.Type) Assert.Null(semanticInfo.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason) Assert.Equal(1, semanticInfo.CandidateSymbols.Length) Assert.Equal("X.Y", semanticInfo.CandidateSymbols(0).ToTestDisplayString()) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub NewOfInaccessibleClass2() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Class X Private Class Y End Class End Class Module Program Sub Main(args As String()) Dim o As Object o = New X.Y(3)'BIND:"New X.Y(3)" End Sub Sub goo() End Sub End Module ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of ObjectCreationExpressionSyntax)(compilation, "a.vb") Assert.Equal("X.Y", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.WideningReference, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason) Assert.Equal(1, semanticInfo.CandidateSymbols.Length) Assert.Equal("Sub X.Y..ctor()", semanticInfo.CandidateSymbols(0).ToTestDisplayString()) Assert.Equal(1, semanticInfo.MemberGroup.Length) Assert.Equal("Sub X.Y..ctor()", semanticInfo.MemberGroup(0).ToTestDisplayString()) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub OverloadResolutionFailureOnNew() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Class X Public Sub New(x As Integer) End Sub End Class Module Program Sub Main(args As String()) Dim o As Object o = New X(3, 4)'BIND:"X" End Sub Sub goo() End Sub End Module ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticInfo.Type) Assert.Null(semanticInfo.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("X", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub OverloadResolutionFailureOnNew2() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Class X Public Sub New(x As Integer) End Sub End Class Module Program Sub Main(args As String()) Dim o As Object o = New X(3, 4)'BIND:"New X(3, 4)" End Sub Sub goo() End Sub End Module ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of ObjectCreationExpressionSyntax)(compilation, "a.vb") Assert.Equal("X", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.WideningReference, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason) Assert.Equal(1, semanticInfo.CandidateSymbols.Length) Dim sortedCandidates = semanticInfo.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub X..ctor(x As System.Int32)", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(0).Kind) Assert.Equal(1, semanticInfo.MemberGroup.Length) Dim sortedMethodGroup = semanticInfo.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub X..ctor(x As System.Int32)", sortedMethodGroup(0).ToTestDisplayString()) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <WorkItem(542695, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542695")> <Fact()> Public Sub TestCandidateReasonForInaccessibleMethod() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class Class1 Private Class NestedClass Private Shared Sub Method1() End Sub End Class Sub Method1 NestedClass.Method1()'BIND:"NestedClass.Method1()" End Sub End Class ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of InvocationExpressionSyntax)(compilation, "a.vb") Assert.Equal("System.Void", semanticSummary.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticSummary.Type.TypeKind) Assert.Equal("System.Void", semanticSummary.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticSummary.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Null(semanticSummary.Symbol) Assert.Equal(CandidateReason.Inaccessible, semanticSummary.CandidateReason) Assert.Equal(1, semanticSummary.CandidateSymbols.Length) Dim sortedCandidates = semanticSummary.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub Class1.NestedClass.Method1()", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(0).Kind) Assert.Equal(0, semanticSummary.MemberGroup.Length) End Sub <WorkItem(542701, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542701")> <Fact()> Public Sub GenericTypeWithNoTypeArgsOnAttribute_AttributeSyntax() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class Gen(Of T) End Class <Gen()>'BIND:"Gen()" Class Test Sub Method1() End Sub End Class ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of AttributeSyntax)(compilation, "a.vb") Assert.Equal("Gen(Of T)", semanticSummary.Type.ToTestDisplayString()) Assert.Equal("Gen(Of T)", semanticSummary.ConvertedType.ToTestDisplayString()) Assert.Null(semanticSummary.Symbol) Assert.Equal(CandidateReason.WrongArity, semanticSummary.CandidateReason) Assert.Equal(1, semanticSummary.CandidateSymbols.Length) Dim sortedCandidates = semanticSummary.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub Gen(Of T)..ctor()", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(0).Kind) Assert.Null(semanticSummary.Alias) Assert.Equal(1, semanticSummary.MemberGroup.Length) Dim sortedMethodGroup = semanticSummary.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub Gen(Of T)..ctor()", sortedMethodGroup(0).ToTestDisplayString()) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact()> Public Sub GenericTypeWithNoTypeArgsOnAttribute_IdentifierSyntax() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class Gen(Of T) End Class <Gen()>'BIND:"Gen" Class Test Sub Method1() End Sub End Class ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("Gen(Of T)", semanticSummary.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.Type.TypeKind) Assert.Equal("Gen(Of T)", semanticSummary.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Null(semanticSummary.Symbol) Assert.Equal(CandidateReason.WrongArity, semanticSummary.CandidateReason) Assert.Equal(1, semanticSummary.CandidateSymbols.Length) Dim sortedCandidates = semanticSummary.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub Gen(Of T)..ctor()", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(0).Kind) Assert.Null(semanticSummary.Alias) Assert.Equal(1, semanticSummary.MemberGroup.Length) Dim sortedMethodGroup = semanticSummary.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub Gen(Of T)..ctor()", sortedMethodGroup(0).ToTestDisplayString()) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact()> Public Sub NextVariable() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class X Sub Goo() For i As Integer = 1 To 10 Next i'BIND:"i" End Sub End Class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("i As System.Int32", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <WorkItem(542009, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542009")> <Fact()> Public Sub Bug8966() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="a.vb"><![CDATA[ Option Strict Off Option Infer On Imports System.Runtime.CompilerServices Imports System Module M Sub Main() Dim s As String = "" Dim x As Action(Of String) = AddressOf s.ToLowerInvariant'BIND:"ToLowerInvariant" x(Nothing) End Sub <Extension()> Sub ToLowerInvariant(ByVal x As Object) Console.WriteLine(1) End Sub End Module ]]></file> </compilation>, {TestMetadata.Net40.SystemCore}, TestOptions.ReleaseExe) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") CompilationUtils.AssertNoErrors(compilation) Assert.Null(semanticInfo.Type) Assert.Null(semanticInfo.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Function System.String.ToLowerInvariant() As System.String", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(2, semanticInfo.MemberGroup.Length) Dim sortedMethodGroup = semanticInfo.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Function System.String.ToLowerInvariant() As System.String", sortedMethodGroup(0).ToTestDisplayString()) Assert.Equal("Sub System.Object.ToLowerInvariant()", sortedMethodGroup(1).ToTestDisplayString()) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub ImplicitLocal1() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Option Explicit Off Option Strict On Option Infer On Imports System Module Program Sub Main(args As String()) If True Then x$ = "hello" 'BIND2:"x$" End If y = x'BIND1:"x" Console.WriteLine(y) End Sub End Module ]]></file> </compilation>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim node1 = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1) Dim node2 = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 2) Dim semanticInfo1 = CompilationUtils.GetSemanticInfoSummary(semanticModel, node1) Assert.Equal("System.String", semanticInfo1.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo1.Type.TypeKind) Assert.Equal("System.Object", semanticInfo1.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo1.ConvertedType.TypeKind) Assert.Equal(ConversionKind.WideningReference, semanticInfo1.ImplicitConversion.Kind) Assert.Equal("x As System.String", semanticInfo1.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Local, semanticInfo1.Symbol.Kind) Dim semanticInfo2 = CompilationUtils.GetSemanticInfoSummary(semanticModel, node2) Assert.Equal("System.String", semanticInfo2.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo2.Type.TypeKind) Assert.Equal("System.String", semanticInfo2.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo2.ConvertedType.TypeKind) Assert.Equal("x As System.String", semanticInfo2.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Local, semanticInfo2.Symbol.Kind) Assert.Same(semanticInfo1.Symbol, semanticInfo2.Symbol) End Sub <Fact()> Public Sub ImplicitLocal2() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Option Explicit Off Option Strict On Option Infer On Imports System Module Program Sub Main(args As String()) Dim a1 As Action = Sub() x$ = "hello"'BIND2:"x$" End Sub Dim a2 As Action = Sub() y = x'BIND1:"x" Console.WriteLine(y) End Sub End Sub End Module ]]></file> </compilation>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim node1 = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1) Dim node2 = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 2) Dim semanticInfo1 = CompilationUtils.GetSemanticInfoSummary(semanticModel, node1) Assert.Equal("System.String", semanticInfo1.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo1.Type.TypeKind) Assert.Equal("System.Object", semanticInfo1.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo1.ConvertedType.TypeKind) Assert.Equal(ConversionKind.WideningReference, semanticInfo1.ImplicitConversion.Kind) Assert.Equal("x As System.String", semanticInfo1.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Local, semanticInfo1.Symbol.Kind) Dim semanticInfo2 = CompilationUtils.GetSemanticInfoSummary(semanticModel, node2) Assert.Equal("System.String", semanticInfo2.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo2.Type.TypeKind) Assert.Equal("System.String", semanticInfo2.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo2.ConvertedType.TypeKind) Assert.Equal("x As System.String", semanticInfo2.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Local, semanticInfo2.Symbol.Kind) Assert.Same(semanticInfo1.Symbol, semanticInfo2.Symbol) End Sub <Fact()> Public Sub ImplicitLocalInLambdaInInitializer() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Option Explicit Off Option Strict On Option Infer On Imports System Module Module1 Dim y As Integer = InvokeMultiple(Function() x% = x% + 1'BIND1:"x%" Return x% End Function, 2) + InvokeMultiple(Function() x% = x% + 1 Return x%'BIND2:"x%" End Function, 7) Function InvokeMultiple(f As Func(Of Integer), times As Integer) As Integer Dim result As Integer = 0 For i As Integer = 1 To times result = f() Next Return result End Function Sub Main() Console.WriteLine(y) End Sub End Module ]]></file> </compilation>) Dim semanticInfo1 = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb", 1) Assert.Equal("System.Int32", semanticInfo1.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo1.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo1.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo1.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo1.ImplicitConversion.Kind) Assert.Equal("x As System.Int32", semanticInfo1.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Local, semanticInfo1.Symbol.Kind) Assert.Equal(0, semanticInfo1.CandidateSymbols.Length) Assert.Equal(SymbolKind.Method, semanticInfo1.Symbol.ContainingSymbol.Kind) Dim containingMethod1 = DirectCast(semanticInfo1.Symbol.ContainingSymbol, MethodSymbol) Assert.True(containingMethod1.IsLambdaMethod, "variable should be contained by a lambda") Dim semanticInfo2 = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb", 2) Assert.Equal("System.Int32", semanticInfo2.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo2.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo2.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo2.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo2.ImplicitConversion.Kind) Assert.Equal("x As System.Int32", semanticInfo2.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Local, semanticInfo2.Symbol.Kind) Assert.Equal(0, semanticInfo2.CandidateSymbols.Length) Assert.Equal(SymbolKind.Method, semanticInfo2.Symbol.ContainingSymbol.Kind) Dim containingMethod2 = DirectCast(semanticInfo2.Symbol.ContainingSymbol, MethodSymbol) Assert.True(containingMethod2.IsLambdaMethod, "variable should be contained by a lambda") ' Should be different variables in different lambdas. Assert.NotSame(semanticInfo1.Symbol, semanticInfo2.Symbol) Assert.NotEqual(semanticInfo1.Symbol, semanticInfo2.Symbol) Assert.NotSame(containingMethod1, containingMethod2) Assert.NotEqual(containingMethod1, containingMethod2) End Sub <WorkItem(542301, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542301")> <Fact()> Public Sub Bug9489() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Collections Imports System.Linq Module Program Sub Main(args As String()) Dim col = New ObjectModel.Collection(Of MetadataReference)() From {ref1, ref2, ref3}'BIND:"Collection(Of MetadataReference)" End Sub End Module ]]></file> </compilation>, {TestMetadata.Net40.SystemCore}, TestOptions.ReleaseExe) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of GenericNameSyntax)(compilation, "a.vb") End Sub <WorkItem(542596, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542596")> <Fact()> Public Sub BindMethodInvocationWhenUnnamedArgFollowsNamed() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module Module1 Sub M1(x As Integer, y As Integer) End Sub Sub Main() M1(x:=2, 3) 'BIND:"M1(x:=2, 3)" End Sub End Module </file> </compilation>, parseOptions:=TestOptions.Regular.WithLanguageVersion(LanguageVersion.VisualBasic15)) compilation.AssertTheseDiagnostics(<errors> BC30241: Named argument expected. Please use language version 15.5 or greater to use non-trailing named arguments. M1(x:=2, 3) 'BIND:"M1(x:=2, 3)" ~ </errors>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of InvocationExpressionSyntax)(compilation, "a.vb") Assert.Equal("Sub Module1.M1(x As System.Int32, y As System.Int32)", semanticInfo.Symbol.ToTestDisplayString()) compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module Module1 Sub M1(x As Integer, y As Integer) End Sub Sub M1(x As Integer, y As Long) End Sub Sub Main() M1(x:=2, 3) 'BIND:"M1(x:=2, 3)" End Sub End Module </file> </compilation>, parseOptions:=TestOptions.Regular.WithLanguageVersion(LanguageVersion.VisualBasic15)) compilation.AssertTheseDiagnostics(<errors> BC30241: Named argument expected. Please use language version 15.5 or greater to use non-trailing named arguments. M1(x:=2, 3) 'BIND:"M1(x:=2, 3)" ~ </errors>) semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of InvocationExpressionSyntax)(compilation, "a.vb") Assert.Equal("Sub Module1.M1(x As System.Int32, y As System.Int32)", semanticInfo.Symbol.ToTestDisplayString()) End Sub <WorkItem(542332, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542332")> <Fact()> Public Sub BindArrayBoundOfField() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class class1 Public zipf As Integer = 7 Public b, quux(zipf) As Integer'BIND:"zipf" End Class ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("System.Int32", semanticSummary.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticSummary.Type.TypeKind) Assert.Equal("System.Int32", semanticSummary.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticSummary.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Equal("class1.zipf As System.Int32", semanticSummary.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Field, semanticSummary.Symbol.Kind) Assert.Equal(0, semanticSummary.CandidateSymbols.Length) Assert.Null(semanticSummary.Alias) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <WorkItem(542858, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542858")> <Fact()> Public Sub TypeNamesInsideCastExpression() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Module Module1 Sub Main(args As String()) Dim func1 As Func(Of Integer, Integer) = Function(x) x + 1 Dim type1 = CType(func1, Func(Of Integer, Integer)) 'BIND:"Func(Of Integer, Integer)" End Sub End Module ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of GenericNameSyntax)(compilation, "a.vb") Assert.Equal("System.Func(Of System.Int32, System.Int32)", semanticSummary.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Delegate, semanticSummary.Type.TypeKind) Assert.Equal("System.Func(Of System.Int32, System.Int32)", semanticSummary.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Delegate, semanticSummary.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Equal("System.Func(Of System.Int32, System.Int32)", semanticSummary.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, semanticSummary.Symbol.Kind) Assert.Equal(0, semanticSummary.CandidateSymbols.Length) Assert.Null(semanticSummary.Alias) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <WorkItem(542933, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542933")> <Fact()> Public Sub CTypeOnALambdaExpr() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Module Program Sub Main(args As String()) Dim f2 As Object = CType(Function(x) x + 5, Func(Of Integer, Integer))'BIND:"CType(Function(x) x + 5, Func(Of Integer, Integer))" End Sub End Module ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of CTypeExpressionSyntax)(compilation, "a.vb") Assert.Equal("System.Func(Of System.Int32, System.Int32)", semanticSummary.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Delegate, semanticSummary.Type.TypeKind) Assert.Equal("System.Object", semanticSummary.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.ConvertedType.TypeKind) Assert.Equal(ConversionKind.WideningReference Or ConversionKind.DelegateRelaxationLevelWideningToNonLambda, semanticSummary.ImplicitConversion.Kind) Assert.Null(semanticSummary.Symbol) Assert.Equal(CandidateReason.None, semanticSummary.CandidateReason) Assert.Equal(0, semanticSummary.CandidateSymbols.Length) Assert.Null(semanticSummary.Alias) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact()> Public Sub AliasInLocalDecl() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports System Imports A = System.String Module Program Sub Main(args As String()) Dim local As A = Nothing'BIND:"A" End Sub End Module ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("System.String", semanticSummary.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.Type.TypeKind) Assert.Equal("System.String", semanticSummary.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Equal("System.String", semanticSummary.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, semanticSummary.Symbol.Kind) Assert.Equal(0, semanticSummary.CandidateSymbols.Length) Assert.Equal("A=System.String", semanticSummary.Alias.ToTestDisplayString()) Assert.Equal(SymbolKind.Alias, semanticSummary.Alias.Kind) Assert.Equal(SymbolKind.NamedType, semanticSummary.Alias.Target.Kind) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact()> Public Sub AliasInTryCast() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports System Imports A = System.String Module Program Sub Main(args As String()) Dim local As A = Nothing Dim x = TryCast(local, A)'BIND:"A" End Sub End Module ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("System.String", semanticSummary.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.Type.TypeKind) Assert.Equal("System.String", semanticSummary.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Equal("System.String", semanticSummary.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, semanticSummary.Symbol.Kind) Assert.Equal(0, semanticSummary.CandidateSymbols.Length) Assert.Equal("A=System.String", semanticSummary.Alias.ToTestDisplayString()) Assert.Equal(SymbolKind.Alias, semanticSummary.Alias.Kind) Assert.Equal(SymbolKind.NamedType, semanticSummary.Alias.Target.Kind) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact()> Public Sub AliasInDirectCast() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports System Imports A = System.String Module Program Sub Main(args As String()) Dim local As A = Nothing Dim x = DirectCast(local, A)'BIND:"A" End Sub End Module ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("System.String", semanticSummary.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.Type.TypeKind) Assert.Equal("System.String", semanticSummary.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Equal("System.String", semanticSummary.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, semanticSummary.Symbol.Kind) Assert.Equal(0, semanticSummary.CandidateSymbols.Length) Assert.Equal("A=System.String", semanticSummary.Alias.ToTestDisplayString()) Assert.Equal(SymbolKind.Alias, semanticSummary.Alias.Kind) Assert.Equal(SymbolKind.NamedType, semanticSummary.Alias.Target.Kind) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact()> Public Sub AliasInCType() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports System Imports A = System.String Module Program Sub Main(args As String()) Dim local As A = Nothing Dim x = CType(local, A)'BIND:"A" End Sub End Module ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("System.String", semanticSummary.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.Type.TypeKind) Assert.Equal("System.String", semanticSummary.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Equal("System.String", semanticSummary.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, semanticSummary.Symbol.Kind) Assert.Equal(0, semanticSummary.CandidateSymbols.Length) Assert.Equal("A=System.String", semanticSummary.Alias.ToTestDisplayString()) Assert.Equal(SymbolKind.Alias, semanticSummary.Alias.Kind) Assert.Equal(SymbolKind.NamedType, semanticSummary.Alias.Target.Kind) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact()> Public Sub AliasInGenericTypeArgument() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports System Imports A = System.String Module Program Sub Main(args As String()) Dim local As A = Nothing Dim x = CType(local, IEnumerable(Of A))'BIND:"A" End Sub End Module ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("System.String", semanticSummary.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.Type.TypeKind) Assert.Equal("System.String", semanticSummary.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Equal("System.String", semanticSummary.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, semanticSummary.Symbol.Kind) Assert.Equal(0, semanticSummary.CandidateSymbols.Length) Assert.Equal("A=System.String", semanticSummary.Alias.ToTestDisplayString()) Assert.Equal(SymbolKind.Alias, semanticSummary.Alias.Kind) Assert.Equal(SymbolKind.NamedType, semanticSummary.Alias.Target.Kind) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <WorkItem(542885, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542885")> <Fact()> Public Sub AliasInGenericArgOfLocal() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System.Threading Imports Thr = System.Threading.Thread Module Program Sub Main(args As String()) Dim q = New List(Of Thr)'BIND:"Thr" End Sub End Module ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("System.Threading.Thread", semanticSummary.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.Type.TypeKind) Assert.Equal("System.Threading.Thread", semanticSummary.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Equal("System.Threading.Thread", semanticSummary.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, semanticSummary.Symbol.Kind) Assert.Equal(0, semanticSummary.CandidateSymbols.Length) Assert.Equal("Thr=System.Threading.Thread", semanticSummary.Alias.ToTestDisplayString()) Assert.Equal(SymbolKind.Alias, semanticSummary.Alias.Kind) Assert.Equal(SymbolKind.NamedType, semanticSummary.Alias.Target.Kind) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <WorkItem(542841, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542841")> <Fact()> Public Sub AliasInArrayCreation() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Imports IClon = System.ICloneable Module M Sub Goo() Dim y = New IClon() {}'BIND:"IClon" End Sub End Module ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("System.ICloneable", semanticSummary.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Interface, semanticSummary.Type.TypeKind) Assert.Equal("System.ICloneable", semanticSummary.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Interface, semanticSummary.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Equal("System.ICloneable", semanticSummary.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, semanticSummary.Symbol.Kind) Assert.Equal(0, semanticSummary.CandidateSymbols.Length) Assert.Equal("IClon=System.ICloneable", semanticSummary.Alias.ToTestDisplayString()) Assert.Equal(SymbolKind.Alias, semanticSummary.Alias.Kind) Assert.Equal(SymbolKind.NamedType, semanticSummary.Alias.Target.Kind) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <WorkItem(542808, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542808")> <Fact()> Public Sub InvocationWithMissingCloseParen() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="a.vb"><![CDATA[ Imports System.Diagnostics Class C Sub M() Dim watch = Stopwatch.StartNew('BIND:"Stopwatch.StartNew" watch.Start() End Sub End Class ]]></file> </compilation>, references:={SystemRef}) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of MemberAccessExpressionSyntax)(compilation, "a.vb") Assert.Null(semanticSummary.Symbol) Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticSummary.CandidateReason) Assert.Equal(1, semanticSummary.CandidateSymbols.Length) Dim sortedCandidates = semanticSummary.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Function System.Diagnostics.Stopwatch.StartNew() As System.Diagnostics.Stopwatch", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(0).Kind) Assert.Equal(1, semanticSummary.MemberGroup.Length) Dim sortedMethodGroup = semanticSummary.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Function System.Diagnostics.Stopwatch.StartNew() As System.Diagnostics.Stopwatch", sortedMethodGroup(0).ToTestDisplayString()) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:="https://github.com/dotnet/roslyn/issues/29531")> Public Sub FailedOverloadResolutionOnCallShouldHaveMemberGroup() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Dim v As A = New A() dim r = v.Goo("hello")'BIND:"Goo" End Sub End Module Class A Public Function Goo() As Integer Return 1 End Function 'Public Function Goo(x as integer, y as Integer) As Integer ' Return 1 'End Function End Class ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticSummary.Symbol) Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticSummary.CandidateReason) Assert.Equal(1, semanticSummary.CandidateSymbols.Length) Dim sortedCandidates = semanticSummary.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Function A.Goo() As System.Int32", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(0).Kind) Assert.Equal(1, semanticSummary.MemberGroup.Length) Dim sortedMethodGroup = semanticSummary.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Function A.Goo() As System.Int32", sortedMethodGroup(0).ToTestDisplayString()) End Sub <Fact()> Public Sub MyBaseNew() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Class B Sub New() Console.WriteLine("B constructor") End Sub End Class Class C Inherits B Sub New() 'Dim q = 42 MyBase.New()'BIND:"New" End Sub End Class ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticSummary.Type) Assert.Null(semanticSummary.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Equal("Sub B..ctor()", semanticSummary.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Method, semanticSummary.Symbol.Kind) Assert.Equal(0, semanticSummary.CandidateSymbols.Length) Assert.Null(semanticSummary.Alias) Assert.Equal(1, semanticSummary.MemberGroup.Length) Dim sortedMethodGroup = semanticSummary.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub B..ctor()", sortedMethodGroup(0).ToTestDisplayString()) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact()> Public Sub MyBaseNew2() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Class B Sub New() Console.WriteLine("B constructor") End Sub End Class Class C Inherits B Sub New() Dim q = 42 MyBase.New()'BIND:"New" End Sub End Class ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticSummary.Type) Assert.Null(semanticSummary.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Equal("Sub B..ctor()", semanticSummary.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Method, semanticSummary.Symbol.Kind) Assert.Equal(0, semanticSummary.CandidateSymbols.Length) Assert.Null(semanticSummary.Alias) Assert.Equal(1, semanticSummary.MemberGroup.Length) Dim sortedMethodGroup = semanticSummary.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub B..ctor()", sortedMethodGroup(0).ToTestDisplayString()) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact()> Public Sub MyBaseNew3() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Class B Sub New() Console.WriteLine("B constructor") End Sub End Class Class C Inherits B Sub New() 'Dim q = 42 MyBase.New()'BIND:"MyBase.New()" End Sub End Class ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of InvocationExpressionSyntax)(compilation, "a.vb") Assert.Equal("System.Void", semanticSummary.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticSummary.Type.TypeKind) Assert.Equal("System.Void", semanticSummary.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticSummary.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Equal("Sub B..ctor()", semanticSummary.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Method, semanticSummary.Symbol.Kind) Assert.Equal(0, semanticSummary.CandidateSymbols.Length) Assert.Null(semanticSummary.Alias) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact()> Public Sub MyBaseNew4() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Class B Sub New() Console.WriteLine("B constructor") End Sub End Class Class C Inherits B Sub New() Dim q = 42 MyBase.New()'BIND:"MyBase.New()" End Sub End Class ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of InvocationExpressionSyntax)(compilation, "a.vb") Assert.Equal("System.Void", semanticSummary.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticSummary.Type.TypeKind) Assert.Equal("System.Void", semanticSummary.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticSummary.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Equal("Sub B..ctor()", semanticSummary.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Method, semanticSummary.Symbol.Kind) Assert.Equal(0, semanticSummary.CandidateSymbols.Length) Assert.Null(semanticSummary.Alias) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <WorkItem(542941, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542941")> <Fact()> Public Sub QualifiedTypeInDim() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class Program Shared Sub Main() Dim c = HttpContext.Current'BIND:"HttpContext" End Sub End Class Class HttpContext Public Shared Property Current As Object End Class ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("HttpContext", semanticSummary.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.Type.TypeKind) Assert.Equal("HttpContext", semanticSummary.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Equal("HttpContext", semanticSummary.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, semanticSummary.Symbol.Kind) Assert.Equal(0, semanticSummary.CandidateSymbols.Length) Assert.Null(semanticSummary.Alias) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <WorkItem(543031, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543031")> <Fact()> Public Sub MissingIdentifierSyntaxNodeIncompleteMethodDecl() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Module Program Sub Main(args As End Sub End Module ]]></file> </compilation>) Dim tree = compilation.SyntaxTrees(0) Dim node As ExpressionSyntax = DirectCast(tree.FindNodeOrTokenByKind(SyntaxKind.IdentifierName).AsNode(), ExpressionSyntax) Dim info = compilation.GetSemanticModel(tree).GetTypeInfo(node) Assert.NotNull(info) Assert.Equal(TypeInfo.None, info) End Sub <WorkItem(543099, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543099")> <Fact()> Public Sub GetSymbolForOptionalParamMethodCall() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Module Program Sub Goo(x As Integer, Optional y As Double = #1/1/2001#) End Sub Sub Main(args As String()) Goo(1)'BIND:"Goo" End Sub End Module ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticSummary.Type) Assert.Null(semanticSummary.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Equal("Sub Program.Goo(x As System.Int32, [y As System.Double])", semanticSummary.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Method, semanticSummary.Symbol.Kind) Assert.Equal(0, semanticSummary.CandidateSymbols.Length) Assert.Null(semanticSummary.Alias) Assert.Equal(1, semanticSummary.MemberGroup.Length) Dim sortedMethodGroup = semanticSummary.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub Program.Goo(x As System.Int32, [y As System.Double])", sortedMethodGroup(0).ToTestDisplayString()) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <WorkItem(10607, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub GetSymbolForOptionalParamMethodCallWithOutParenthesis() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Goo(Optional i As Integer = 1) End Sub Sub Main(args As String()) Goo'BIND:"Goo" End Sub End Module ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of InvocationExpressionSyntax)(compilation, "a.vb") Assert.Equal("System.Void", semanticSummary.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticSummary.Type.TypeKind) Assert.Equal("System.Void", semanticSummary.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticSummary.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Equal("Sub Program.Goo([i As System.Int32 = 1])", semanticSummary.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Method, semanticSummary.Symbol.Kind) Assert.Equal(0, semanticSummary.CandidateSymbols.Length) Assert.Null(semanticSummary.Alias) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <WorkItem(542217, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542217")> <Fact()> Public Sub ConflictingAliases() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports S = System Imports S = System.IO Module Program Sub Main() End Sub End Module ]]></file> </compilation>) Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim aliases = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of SimpleImportsClauseSyntax).ToArray() Assert.Equal(2, aliases.Length) Dim alias1 = model.GetDeclaredSymbol(aliases(0)) Assert.NotNull(alias1) Assert.Equal("System", alias1.Target.ToTestDisplayString()) Dim alias2 = model.GetDeclaredSymbol(aliases(1)) Assert.NotNull(alias2) Assert.Equal("System.IO", alias2.Target.ToTestDisplayString()) Assert.NotEqual(alias1.Locations.Single(), alias2.Locations.Single()) ' This symbol we re-use. Dim alias1b = model.GetDeclaredSymbol(aliases(0)) Assert.Same(alias1, alias1b) ' This symbol we generate on-demand. Dim alias2b = model.GetDeclaredSymbol(aliases(1)) Assert.NotSame(alias2, alias2b) Assert.Equal(alias2, alias2b) End Sub <Fact()> Public Sub StaticLocals() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class C Public Function goo() As Integer Static i As Integer = 23 i = i + 1 Return i End Function Public Shared Sub Main() End Sub End Class ]]></file> </compilation>) Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim staticLocals = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of LocalDeclarationStatementSyntax).ToArray() Assert.Equal(1, staticLocals.Length) Dim SLDeclaration As LocalDeclarationStatementSyntax = staticLocals(0) 'Static Locals are Not Supported for this API Assert.Throws(Of NotSupportedException)(Sub() Dim i = model.GetDeclaredSymbolFromSyntaxNode(SLDeclaration) End Sub) Dim containingType = DirectCast(model, SemanticModel).GetEnclosingSymbol(SLDeclaration.SpanStart) Assert.Equal("Function C.goo() As System.Int32", DirectCast(containingType, Symbol).ToTestDisplayString()) 'GetSymbolInfo 'GetSpeculativeSymbolInfo() 'GetTypeInfo() Dim TI = DirectCast(model, SemanticModel).GetTypeInfo(SLDeclaration) Dim mG = DirectCast(model, SemanticModel).GetAliasInfo(SLDeclaration) Dim lus1 = DirectCast(model, SemanticModel).LookupSymbols(SLDeclaration.SpanStart, name:="i") 'GetAliasImports - only applicable for Imports statements 'ConstantValue End Sub <WorkItem(530631, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530631")> <Fact()> Public Sub Bug16603() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Module Program Sub Main() Dim x As Action = Sub() x = Sub(, y = x End Sub End Module ]]></file> </compilation>) Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim identifiers = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of IdentifierNameSyntax).ToArray() Assert.Equal(4, identifiers.Length) Dim id As IdentifierNameSyntax = identifiers(3) ' No crashes Dim ai = DirectCast(model, SemanticModel).GetAliasInfo(id) Dim si = DirectCast(model, SemanticModel).GetSymbolInfo(id) End Sub <WorkItem(543278, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543278")> <Fact()> Public Sub ModuleNameInObjectCreationExpr() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Module Program Sub Main(args As String()) Dim x1 = New Program() 'BIND:"Program" End Sub End Module ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticSummary.Type) Assert.Null(semanticSummary.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Null(semanticSummary.Symbol) Assert.Equal(CandidateReason.NotCreatable, semanticSummary.CandidateReason) Assert.Null(semanticSummary.Alias) Assert.Equal(1, semanticSummary.CandidateSymbols.Length) Dim sortedCandidates = semanticSummary.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Program", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, sortedCandidates(0).Kind) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact()> Public Sub ModuleNameInObjectCreationExpr2() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Module Program Sub Main(args As String()) Dim x1 = New Program() 'BIND:"New Program()" End Sub End Module ]]></file> </compilation>) compilation.AssertTheseDiagnostics(<expected> BC35000: Requested operation is not available because the runtime library function 'Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute..ctor' is not defined. Module Program ~~~~~~~ BC30371: Module 'Program' cannot be used as a type. Dim x1 = New Program() 'BIND:"New Program()" ~~~~~~~ </expected>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of ObjectCreationExpressionSyntax)(compilation, "a.vb") Assert.Equal("Program", semanticSummary.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Module, semanticSummary.Type.TypeKind) Assert.Equal("Program", semanticSummary.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Module, semanticSummary.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Null(semanticSummary.Symbol) Assert.Equal(CandidateReason.None, semanticSummary.CandidateReason) Assert.Null(semanticSummary.Alias) Assert.Equal(0, semanticSummary.CandidateSymbols.Length) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact()> Public Sub ClassWithInaccessibleConstructorsInObjectCreationExpr() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class C1 private sub new() end Sub end class Module Program Sub Main(args As String()) Dim x1 = New C1() 'BIND:"C1" End Sub public mustinherit class Goo public sub new() end sub end class End Module ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticSummary.Type) Assert.Null(semanticSummary.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Equal("C1", semanticSummary.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, semanticSummary.CandidateReason) Assert.Null(semanticSummary.Alias) Assert.Equal(0, semanticSummary.CandidateSymbols.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact()> Public Sub ClassWithInaccessibleConstructorsInObjectCreationExpr2() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class C1 private sub new() end Sub end class Module Program Sub Main(args As String()) Dim x1 = New C1() 'BIND:"New C1()" End Sub public mustinherit class Goo public sub new() end sub end class End Module ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of ObjectCreationExpressionSyntax)(compilation, "a.vb") Assert.Equal("C1", semanticSummary.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.Type.TypeKind) Assert.Null(semanticSummary.Symbol) Assert.Equal(CandidateReason.Inaccessible, semanticSummary.CandidateReason) Assert.Null(semanticSummary.Alias) Assert.Equal(1, semanticSummary.CandidateSymbols.Length) Assert.Equal("Sub C1..ctor()", semanticSummary.CandidateSymbols(0).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, semanticSummary.CandidateSymbols(0).Kind) Assert.False(semanticSummary.ConstantValue.HasValue) Assert.Equal(1, semanticSummary.MemberGroup.Length) Assert.Equal("Sub C1..ctor()", semanticSummary.MemberGroup(0).ToTestDisplayString()) End Sub <WorkItem(542844, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542844")> <Fact()> Public Sub Bug10246() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class C(Of T) Public Field As T End Class Class D Sub M() Call New C(Of Integer).Field.ToString() 'BIND1:"Field" End Sub End Class ]]></file> </compilation>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel1 = compilation.GetSemanticModel(tree) Dim node1 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1) Dim symbolInfo = semanticModel1.GetSymbolInfo(node1) Assert.Equal(CandidateReason.NotATypeOrNamespace, symbolInfo.CandidateReason) Assert.Equal(1, symbolInfo.CandidateSymbols.Length) Assert.Equal("C(Of System.Int32).Field As System.Int32", symbolInfo.CandidateSymbols(0).ToTestDisplayString()) Assert.Null(symbolInfo.Symbol) End Sub <WorkItem(530093, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530093")> <Fact()> Public Sub Bug530093() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class C Public Shared Field As C = Me 'BIND1:"Me" End Class ]]></file> </compilation>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel1 = compilation.GetSemanticModel(tree) Dim node1 As ExpressionSyntax = CompilationUtils.FindBindingText(Of ExpressionSyntax)(compilation, "a.vb", 1) Dim symbolInfo = semanticModel1.GetSymbolInfo(node1) Assert.Equal(CandidateReason.StaticInstanceMismatch, symbolInfo.CandidateReason) Assert.Equal(1, symbolInfo.CandidateSymbols.Length) Assert.Equal("Me As C", symbolInfo.CandidateSymbols(0).ToTestDisplayString()) Assert.Null(symbolInfo.Symbol) End Sub <WorkItem(530093, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530093")> <Fact()> Public Sub Bug530093b() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class C Public Shared Field As Object = MyBase 'BIND1:"MyBase" End Class ]]></file> </compilation>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel1 = compilation.GetSemanticModel(tree) Dim node1 As ExpressionSyntax = CompilationUtils.FindBindingText(Of ExpressionSyntax)(compilation, "a.vb", 1) Dim symbolInfo = semanticModel1.GetSymbolInfo(node1) Assert.Equal(CandidateReason.StaticInstanceMismatch, symbolInfo.CandidateReason) Assert.Equal(1, symbolInfo.CandidateSymbols.Length) Assert.Equal("Me As C", symbolInfo.CandidateSymbols(0).ToTestDisplayString()) Assert.Null(symbolInfo.Symbol) End Sub <Fact()> Public Sub NewOfModule() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Module Program Sub Main(args As String()) Dim a As Object = New X()'BIND:"X" End Sub End Module Module X End Module ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticSummary.Type) Assert.Null(semanticSummary.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Null(semanticSummary.Symbol) Assert.Equal(CandidateReason.NotCreatable, semanticSummary.CandidateReason) Assert.Equal(1, semanticSummary.CandidateSymbols.Length) Assert.Equal("X", semanticSummary.CandidateSymbols(0).ToTestDisplayString()) Assert.Null(semanticSummary.Alias) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact()> Public Sub NewOfModule2() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Module Program Sub Main(args As String()) Dim a As Object = New X()'BIND:"New X()" End Sub End Module Module X End Module ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of ObjectCreationExpressionSyntax)(compilation, "a.vb") Assert.Equal("X", semanticSummary.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Module, semanticSummary.Type.TypeKind) Assert.Equal("System.Object", semanticSummary.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.ConvertedType.TypeKind) Assert.Equal(ConversionKind.WideningReference, semanticSummary.ImplicitConversion.Kind) Assert.Null(semanticSummary.Symbol) Assert.Equal(CandidateReason.None, semanticSummary.CandidateReason) Assert.Equal(0, semanticSummary.CandidateSymbols.Length) Assert.Null(semanticSummary.Alias) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact()> Public Sub NewOfInterface() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Module Program Sub Main(args As String()) Dim a As Object = New X()'BIND:"X" End Sub End Module Interface X End Interface ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticSummary.Type) Assert.Null(semanticSummary.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Null(semanticSummary.Symbol) Assert.Equal(CandidateReason.NotCreatable, semanticSummary.CandidateReason) Assert.Equal(1, semanticSummary.CandidateSymbols.Length) Assert.Equal("X", semanticSummary.CandidateSymbols(0).ToTestDisplayString()) Assert.Null(semanticSummary.Alias) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact()> Public Sub NewOfInterface2() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Module Program Sub Main(args As String()) Dim a As Object = New X()'BIND:"New X()" End Sub End Module Interface X End Interface ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of ObjectCreationExpressionSyntax)(compilation, "a.vb") Assert.Equal("X", semanticSummary.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Interface, semanticSummary.Type.TypeKind) Assert.Equal("System.Object", semanticSummary.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.ConvertedType.TypeKind) Assert.Equal(ConversionKind.WideningReference, semanticSummary.ImplicitConversion.Kind) Assert.Null(semanticSummary.Symbol) Assert.Equal(CandidateReason.None, semanticSummary.CandidateReason) Assert.Equal(0, semanticSummary.CandidateSymbols.Length) Assert.Null(semanticSummary.Alias) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact()> Public Sub NewOfNotCreatable() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Class C Sub F() Dim a As Object = New X()'BIND:"X" End Sub End Class MustInherit Class X End Class ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticSummary.Type) Assert.Null(semanticSummary.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Null(semanticSummary.Symbol) Assert.Equal(CandidateReason.NotCreatable, semanticSummary.CandidateReason) Assert.Equal(1, semanticSummary.CandidateSymbols.Length) Assert.Equal("X", semanticSummary.CandidateSymbols(0).ToTestDisplayString()) Assert.Null(semanticSummary.Alias) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact()> Public Sub NewOfNotCreatable2() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Class C Sub F() Dim a As Object = New X()'BIND:"New X()" End Sub End Class MustInherit Class X End Class ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of ObjectCreationExpressionSyntax)(compilation, "a.vb") Assert.Equal("X", semanticSummary.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.Type.TypeKind) Assert.Equal("System.Object", semanticSummary.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.ConvertedType.TypeKind) Assert.Equal(ConversionKind.WideningReference, semanticSummary.ImplicitConversion.Kind) Assert.Null(semanticSummary.Symbol) Assert.Equal(CandidateReason.Inaccessible, semanticSummary.CandidateReason) Assert.Equal(1, semanticSummary.CandidateSymbols.Length) Assert.Equal("Sub X..ctor()", semanticSummary.CandidateSymbols(0).ToTestDisplayString()) Assert.Null(semanticSummary.Alias) Assert.Equal(1, semanticSummary.MemberGroup.Length) Dim sortedMethodGroup = semanticSummary.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub X..ctor()", sortedMethodGroup(0).ToTestDisplayString()) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact(), WorkItem(665920, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/665920")> Public Sub NewOfNotCreatable3() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System MustInherit Class X Protected Sub New(x as integer) End Sub Protected Sub New(x as string) End Sub Sub F() Dim a As Object = New X()'BIND1:"New X()" End Sub End Class ]]></file> </compilation>) Dim model = GetSemanticModel(compilation, "a.vb") Dim creation As ObjectCreationExpressionSyntax = CompilationUtils.FindBindingText(Of ObjectCreationExpressionSyntax)(compilation, "a.vb", 1) Dim symbolInfo As SymbolInfo = model.GetSymbolInfo(creation.Type) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.NotCreatable, symbolInfo.CandidateReason) Assert.Equal(1, symbolInfo.CandidateSymbols.Count) Assert.Equal("X", symbolInfo.CandidateSymbols(0).ToTestDisplayString()) Dim memberGroup = model.GetMemberGroup(creation.Type) Assert.Equal(0, memberGroup.Count) Dim typeInfo As TypeInfo = model.GetTypeInfo(creation.Type) Assert.Null(typeInfo.Type) Assert.Null(typeInfo.ConvertedType) Dim conv = model.GetConversion(creation.Type) Assert.True(conv.IsIdentity) memberGroup = model.GetMemberGroup(creation) Dim sortedMethodGroup As ISymbol() = memberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal(2, sortedMethodGroup.Length) Assert.Equal("Sub X..ctor(x As System.Int32)", sortedMethodGroup(0).ToTestDisplayString()) Assert.Equal("Sub X..ctor(x As System.String)", sortedMethodGroup(1).ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(creation) Assert.Null(symbolInfo.Symbol) sortedMethodGroup = symbolInfo.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal(2, sortedMethodGroup.Length) Assert.Equal("Sub X..ctor(x As System.Int32)", sortedMethodGroup(0).ToTestDisplayString()) Assert.Equal("Sub X..ctor(x As System.String)", sortedMethodGroup(1).ToTestDisplayString()) Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason) typeInfo = model.GetTypeInfo(creation) Assert.Equal("X", typeInfo.Type.ToTestDisplayString()) Assert.Equal("System.Object", typeInfo.ConvertedType.ToTestDisplayString()) conv = model.GetConversion(creation) Assert.Equal(ConversionKind.WideningReference, conv.Kind) End Sub <Fact(), WorkItem(665920, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/665920")> Public Sub NewOfNotCreatable4() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System MustInherit Class X Protected Sub New(x as integer) End Sub Protected Sub New(x as string) End Sub Sub F() Dim a As Object = New X(1)'BIND1:"New X(1)" End Sub End Class ]]></file> </compilation>) Dim model = GetSemanticModel(compilation, "a.vb") Dim creation As ObjectCreationExpressionSyntax = CompilationUtils.FindBindingText(Of ObjectCreationExpressionSyntax)(compilation, "a.vb", 1) Dim symbolInfo As SymbolInfo = model.GetSymbolInfo(creation.Type) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.NotCreatable, symbolInfo.CandidateReason) Assert.Equal(1, symbolInfo.CandidateSymbols.Count) Assert.Equal("X", symbolInfo.CandidateSymbols(0).ToTestDisplayString()) Dim memberGroup = model.GetMemberGroup(creation.Type) Assert.Equal(0, memberGroup.Count) Dim typeInfo As TypeInfo = model.GetTypeInfo(creation.Type) Assert.Null(typeInfo.Type) Assert.Null(typeInfo.ConvertedType) Dim conv = model.GetConversion(creation.Type) Assert.True(conv.IsIdentity) memberGroup = model.GetMemberGroup(creation) Dim sortedMethodGroup = memberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal(2, sortedMethodGroup.Length) Assert.Equal("Sub X..ctor(x As System.Int32)", sortedMethodGroup(0).ToTestDisplayString()) Assert.Equal("Sub X..ctor(x As System.String)", sortedMethodGroup(1).ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(creation) Assert.Equal("Sub X..ctor(x As System.Int32)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) typeInfo = model.GetTypeInfo(creation) Assert.Equal("X", typeInfo.Type.ToTestDisplayString()) Assert.Equal("System.Object", typeInfo.ConvertedType.ToTestDisplayString()) conv = model.GetConversion(creation) Assert.Equal(ConversionKind.WideningReference, conv.Kind) End Sub <Fact(), WorkItem(665920, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/665920")> Public Sub NewOfNotCreatable5() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Class C Sub F() Dim a As Object = New X(1)'BIND1:"New X(1)" End Sub End Class MustInherit Class X Protected Sub New(x as integer) End Sub Protected Sub New(x as string) End Sub End Class ]]></file> </compilation>) Dim model = GetSemanticModel(compilation, "a.vb") Dim creation As ObjectCreationExpressionSyntax = CompilationUtils.FindBindingText(Of ObjectCreationExpressionSyntax)(compilation, "a.vb", 1) Dim symbolInfo As SymbolInfo = model.GetSymbolInfo(creation.Type) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.NotCreatable, symbolInfo.CandidateReason) Assert.Equal(1, symbolInfo.CandidateSymbols.Count) Assert.Equal("X", symbolInfo.CandidateSymbols(0).ToTestDisplayString()) Dim memberGroup = model.GetMemberGroup(creation.Type) Assert.Equal(0, memberGroup.Count) Dim typeInfo As TypeInfo = model.GetTypeInfo(creation.Type) Assert.Null(typeInfo.Type) Assert.Null(typeInfo.ConvertedType) Dim conv = model.GetConversion(creation.Type) Assert.True(conv.IsIdentity) memberGroup = model.GetMemberGroup(creation) Dim sortedMethodGroup = memberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal(2, sortedMethodGroup.Length) Assert.Equal("Sub X..ctor(x As System.Int32)", sortedMethodGroup(0).ToTestDisplayString()) Assert.Equal("Sub X..ctor(x As System.String)", sortedMethodGroup(1).ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(creation) Assert.Null(symbolInfo.Symbol) Assert.Equal(1, symbolInfo.CandidateSymbols.Length) Assert.Equal("Sub X..ctor(x As System.Int32)", symbolInfo.CandidateSymbols(0).ToTestDisplayString()) Assert.Equal(CandidateReason.Inaccessible, symbolInfo.CandidateReason) typeInfo = model.GetTypeInfo(creation) Assert.Equal("X", typeInfo.Type.ToTestDisplayString()) Assert.Equal("System.Object", typeInfo.ConvertedType.ToTestDisplayString()) conv = model.GetConversion(creation) Assert.Equal(ConversionKind.WideningReference, conv.Kind) End Sub <Fact(), WorkItem(665920, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/665920")> Public Sub NewOfNotCreatable6() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Class C Sub F() Dim a As Object = New X()'BIND1:"New X()" End Sub End Class MustInherit Class X Protected Sub New(x as integer) End Sub Protected Sub New(x as string) End Sub End Class ]]></file> </compilation>) Dim model = GetSemanticModel(compilation, "a.vb") Dim creation As ObjectCreationExpressionSyntax = CompilationUtils.FindBindingText(Of ObjectCreationExpressionSyntax)(compilation, "a.vb", 1) Dim symbolInfo As SymbolInfo = model.GetSymbolInfo(creation.Type) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.NotCreatable, symbolInfo.CandidateReason) Assert.Equal(1, symbolInfo.CandidateSymbols.Count) Assert.Equal("X", symbolInfo.CandidateSymbols(0).ToTestDisplayString()) Dim memberGroup = model.GetMemberGroup(creation.Type) Assert.Equal(0, memberGroup.Count) Dim typeInfo As TypeInfo = model.GetTypeInfo(creation.Type) Assert.Null(typeInfo.Type) Assert.Null(typeInfo.ConvertedType) Dim conv = model.GetConversion(creation.Type) Assert.True(conv.IsIdentity) memberGroup = model.GetMemberGroup(creation) Dim sortedMethodGroup As ISymbol() = memberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal(2, sortedMethodGroup.Length) Assert.Equal("Sub X..ctor(x As System.Int32)", sortedMethodGroup(0).ToTestDisplayString()) Assert.Equal("Sub X..ctor(x As System.String)", sortedMethodGroup(1).ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(creation) Assert.Null(symbolInfo.Symbol) sortedMethodGroup = symbolInfo.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal(2, sortedMethodGroup.Length) Assert.Equal("Sub X..ctor(x As System.Int32)", sortedMethodGroup(0).ToTestDisplayString()) Assert.Equal("Sub X..ctor(x As System.String)", sortedMethodGroup(1).ToTestDisplayString()) Assert.Equal(CandidateReason.Inaccessible, symbolInfo.CandidateReason) typeInfo = model.GetTypeInfo(creation) Assert.Equal("X", typeInfo.Type.ToTestDisplayString()) Assert.Equal("System.Object", typeInfo.ConvertedType.ToTestDisplayString()) conv = model.GetConversion(creation) Assert.Equal(ConversionKind.WideningReference, conv.Kind) End Sub <Fact(), WorkItem(665920, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/665920")> Public Sub NewOfNotCreatable7() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System MustInherit Class X Protected Sub New(x as integer) End Sub Sub F() Dim a As Object = New X()'BIND1:"New X()" End Sub End Class ]]></file> </compilation>) Dim model = GetSemanticModel(compilation, "a.vb") Dim creation As ObjectCreationExpressionSyntax = CompilationUtils.FindBindingText(Of ObjectCreationExpressionSyntax)(compilation, "a.vb", 1) Dim symbolInfo As SymbolInfo = model.GetSymbolInfo(creation.Type) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.NotCreatable, symbolInfo.CandidateReason) Assert.Equal(1, symbolInfo.CandidateSymbols.Count) Assert.Equal("X", symbolInfo.CandidateSymbols(0).ToTestDisplayString()) Dim memberGroup = model.GetMemberGroup(creation.Type) Assert.Equal(0, memberGroup.Count) Dim typeInfo As TypeInfo = model.GetTypeInfo(creation.Type) Assert.Null(typeInfo.Type) Assert.Null(typeInfo.ConvertedType) Dim conv = model.GetConversion(creation.Type) Assert.True(conv.IsIdentity) memberGroup = model.GetMemberGroup(creation) Dim sortedMethodGroup = memberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal(1, sortedMethodGroup.Length) Assert.Equal("Sub X..ctor(x As System.Int32)", sortedMethodGroup(0).ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(creation) Assert.Null(symbolInfo.Symbol) Assert.Equal(1, symbolInfo.CandidateSymbols.Length) Assert.Equal("Sub X..ctor(x As System.Int32)", symbolInfo.CandidateSymbols(0).ToTestDisplayString()) Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason) typeInfo = model.GetTypeInfo(creation) Assert.Equal("X", typeInfo.Type.ToTestDisplayString()) Assert.Equal("System.Object", typeInfo.ConvertedType.ToTestDisplayString()) conv = model.GetConversion(creation) Assert.Equal(ConversionKind.WideningReference, conv.Kind) End Sub <Fact()> Public Sub NewOfUnconstrainedTypeParameter() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Class C(Of T) Sub F() Dim a As Object = New T()'BIND:"T" End Sub End Class ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticSummary.Type) Assert.Null(semanticSummary.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Null(semanticSummary.Symbol) Assert.Equal(CandidateReason.NotCreatable, semanticSummary.CandidateReason) Assert.Equal(1, semanticSummary.CandidateSymbols.Length) Assert.Equal("T", semanticSummary.CandidateSymbols(0).ToTestDisplayString()) Assert.Null(semanticSummary.Alias) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact()> Public Sub NewOfUnconstrainedTypeParameter2() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Class C(Of T) Sub F() Dim a As Object = New T()'BIND:"New T()" End Sub End Class ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of ObjectCreationExpressionSyntax)(compilation, "a.vb") Assert.Equal("T", semanticSummary.Type.ToTestDisplayString()) Assert.Equal(TypeKind.TypeParameter, semanticSummary.Type.TypeKind) Assert.Null(semanticSummary.Symbol) Assert.Equal(CandidateReason.None, semanticSummary.CandidateReason) Assert.Equal(0, semanticSummary.CandidateSymbols.Length) Assert.Null(semanticSummary.Alias) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <WorkItem(543534, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543534")> <Fact()> Public Sub InterfaceCreationExpression() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Interface I Property X() As Integer End Interface Class Program Private Shared Sub Main() Dim x = New I()'BIND:"I" End Sub End Class ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticSummary.Type) Assert.Null(semanticSummary.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Null(semanticSummary.Symbol) Assert.Equal(CandidateReason.NotCreatable, semanticSummary.CandidateReason) Assert.Equal(1, semanticSummary.CandidateSymbols.Length) Dim sortedCandidates = semanticSummary.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("I", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, sortedCandidates(0).Kind) Assert.Null(semanticSummary.Alias) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact()> Public Sub InterfaceCreationExpression2() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Interface I Property X() As Integer End Interface Class Program Private Shared Sub Main() Dim x = New I()'BIND:"New I()" End Sub End Class ]]></file> </compilation>) compilation.AssertTheseDiagnostics(<expected> BC30375: 'New' cannot be used on an interface. Dim x = New I()'BIND:"New I()" ~~~~~~~ </expected>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of ObjectCreationExpressionSyntax)(compilation, "a.vb") Assert.Equal("I", semanticSummary.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Interface, semanticSummary.Type.TypeKind) Assert.Equal("I", semanticSummary.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Interface, semanticSummary.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Null(semanticSummary.Symbol) Assert.Equal(CandidateReason.None, semanticSummary.CandidateReason) Assert.Equal(0, semanticSummary.CandidateSymbols.Length) Assert.Null(semanticSummary.Alias) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <WorkItem(543515, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543515")> <ConditionalFact(GetType(WindowsOnly), Reason:="https://github.com/dotnet/roslyn/issues/29531")> Public Sub AliasAttributeName() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ imports A = A1 Class A1 Inherits System.Attribute End Class <A> 'BIND:"A" Class C End Class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("A1", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.[Class], semanticInfo.Type.TypeKind) Assert.Equal("A1", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.[Class], semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Sub A1..ctor()", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(1, semanticInfo.MemberGroup.Length) Dim sortedMethodGroup = semanticInfo.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub A1..ctor()", sortedMethodGroup(0).ToTestDisplayString()) Assert.False(semanticInfo.ConstantValue.HasValue) Dim aliasInfo = GetAliasInfoForTest(compilation, "a.vb") Assert.NotNull(aliasInfo) Assert.Equal("A=A1", aliasInfo.ToTestDisplayString()) Assert.Equal(SymbolKind.[Alias], aliasInfo.Kind) End Sub <WorkItem(543515, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543515")> <ConditionalFact(GetType(WindowsOnly), Reason:="https://github.com/dotnet/roslyn/issues/29531")> Public Sub AliasAttributeName_02_AttributeSyntax() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ imports GooAttribute = System.ObsoleteAttribute <Goo> 'BIND:"Goo" Class C End Class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of AttributeSyntax)(compilation, "a.vb") Assert.Equal("System.ObsoleteAttribute", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.[Class], semanticInfo.Type.TypeKind) Assert.Equal("System.ObsoleteAttribute", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.[Class], semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Sub System.ObsoleteAttribute..ctor()", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(3, semanticInfo.MemberGroup.Length) Dim sortedMethodGroup = semanticInfo.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub System.ObsoleteAttribute..ctor()", sortedMethodGroup(0).ToTestDisplayString()) Assert.Equal("Sub System.ObsoleteAttribute..ctor(message As System.String)", sortedMethodGroup(1).ToTestDisplayString()) Assert.Equal("Sub System.ObsoleteAttribute..ctor(message As System.String, [error] As System.Boolean)", sortedMethodGroup(2).ToTestDisplayString()) Assert.[False](semanticInfo.ConstantValue.HasValue) Dim aliasInfo = GetAliasInfoForTest(compilation, "a.vb") Assert.NotNull(aliasInfo) Assert.Equal("GooAttribute=System.ObsoleteAttribute", aliasInfo.ToTestDisplayString()) Assert.Equal(SymbolKind.[Alias], aliasInfo.Kind) End Sub <WorkItem(543515, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543515")> <ConditionalFact(GetType(WindowsOnly), Reason:="https://github.com/dotnet/roslyn/issues/29531")> Public Sub AliasAttributeName_02_IdentifierNameSyntax() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ imports GooAttribute = System.ObsoleteAttribute <Goo> 'BIND:"Goo" Class C End Class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("System.ObsoleteAttribute", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.[Class], semanticInfo.Type.TypeKind) Assert.Equal("System.ObsoleteAttribute", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.[Class], semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Sub System.ObsoleteAttribute..ctor()", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(3, semanticInfo.MemberGroup.Length) Dim sortedMethodGroup = semanticInfo.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub System.ObsoleteAttribute..ctor()", sortedMethodGroup(0).ToTestDisplayString()) Assert.Equal("Sub System.ObsoleteAttribute..ctor(message As System.String)", sortedMethodGroup(1).ToTestDisplayString()) Assert.Equal("Sub System.ObsoleteAttribute..ctor(message As System.String, [error] As System.Boolean)", sortedMethodGroup(2).ToTestDisplayString()) Assert.[False](semanticInfo.ConstantValue.HasValue) Dim aliasInfo = GetAliasInfoForTest(compilation, "a.vb") Assert.NotNull(aliasInfo) Assert.Equal("GooAttribute=System.ObsoleteAttribute", aliasInfo.ToTestDisplayString()) Assert.Equal(SymbolKind.[Alias], aliasInfo.Kind) End Sub <WorkItem(543515, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543515")> <ConditionalFact(GetType(WindowsOnly), Reason:="https://github.com/dotnet/roslyn/issues/29531")> Public Sub AliasAttributeName_03_AttributeSyntax() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ imports GooAttribute = System.ObsoleteAttribute <GooAttribute> 'BIND:"GooAttribute" Class C End Class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of AttributeSyntax)(compilation, "a.vb") Assert.Equal("System.ObsoleteAttribute", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.[Class], semanticInfo.Type.TypeKind) Assert.Equal("System.ObsoleteAttribute", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.[Class], semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Sub System.ObsoleteAttribute..ctor()", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(3, semanticInfo.MemberGroup.Length) Dim sortedMethodGroup = semanticInfo.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub System.ObsoleteAttribute..ctor()", sortedMethodGroup(0).ToTestDisplayString()) Assert.Equal("Sub System.ObsoleteAttribute..ctor(message As System.String)", sortedMethodGroup(1).ToTestDisplayString()) Assert.Equal("Sub System.ObsoleteAttribute..ctor(message As System.String, [error] As System.Boolean)", sortedMethodGroup(2).ToTestDisplayString()) Assert.[False](semanticInfo.ConstantValue.HasValue) Dim aliasInfo = GetAliasInfoForTest(compilation, "a.vb") Assert.NotNull(aliasInfo) Assert.Equal("GooAttribute=System.ObsoleteAttribute", aliasInfo.ToTestDisplayString()) Assert.Equal(SymbolKind.[Alias], aliasInfo.Kind) End Sub <WorkItem(543515, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543515")> <ConditionalFact(GetType(WindowsOnly), Reason:="https://github.com/dotnet/roslyn/issues/29531")> Public Sub AliasAttributeName_03_IdentifierNameSyntax() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ imports GooAttribute = System.ObsoleteAttribute <GooAttribute> 'BIND:"GooAttribute" Class C End Class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("System.ObsoleteAttribute", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.[Class], semanticInfo.Type.TypeKind) Assert.Equal("System.ObsoleteAttribute", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.[Class], semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Sub System.ObsoleteAttribute..ctor()", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(3, semanticInfo.MemberGroup.Length) Dim sortedMethodGroup = semanticInfo.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub System.ObsoleteAttribute..ctor()", sortedMethodGroup(0).ToTestDisplayString()) Assert.Equal("Sub System.ObsoleteAttribute..ctor(message As System.String)", sortedMethodGroup(1).ToTestDisplayString()) Assert.Equal("Sub System.ObsoleteAttribute..ctor(message As System.String, [error] As System.Boolean)", sortedMethodGroup(2).ToTestDisplayString()) Assert.[False](semanticInfo.ConstantValue.HasValue) Dim aliasInfo = GetAliasInfoForTest(compilation, "a.vb") Assert.NotNull(aliasInfo) Assert.Equal("GooAttribute=System.ObsoleteAttribute", aliasInfo.ToTestDisplayString()) Assert.Equal(SymbolKind.[Alias], aliasInfo.Kind) End Sub <WorkItem(543515, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543515")> <Fact()> Public Sub AliasQualifiedAttributeName_01() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ namespace N <global.AttributeClass.SomeClass()> 'BIND:"AttributeClass" class C end class class AttributeClass inherits System.Attribute end class end namespace class AttributeClass inherits System.Attribute class SomeClass end class end class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("AttributeClass", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.[Class], semanticInfo.Type.TypeKind) Assert.Equal("AttributeClass", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.[Class], semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("AttributeClass", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.[False](semanticInfo.ConstantValue.HasValue) Assert.[False](SyntaxFacts.IsAttributeName((DirectCast(semanticInfo.Symbol, SourceNamedTypeSymbol)).SyntaxReferences.First().GetSyntax()), "IsAttributeName can be true only for alias name being qualified") End Sub <Fact()> Public Sub AliasQualifiedAttributeName_02() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ namespace N <global.AttributeClass.SomeClass()> 'BIND:"global.AttributeClass" class C end class class AttributeClass inherits System.Attribute end class end namespace class AttributeClass inherits System.Attribute class SomeClass end class end class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of QualifiedNameSyntax)(compilation, "a.vb") Assert.Equal("AttributeClass", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.[Class], semanticInfo.Type.TypeKind) Assert.Equal("AttributeClass", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.[Class], semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("AttributeClass", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.[False](semanticInfo.ConstantValue.HasValue) Assert.[False](SyntaxFacts.IsAttributeName((DirectCast(semanticInfo.Symbol, SourceNamedTypeSymbol)).SyntaxReferences.First().GetSyntax()), "IsAttributeName can be true only for alias name being qualified") End Sub <Fact()> Public Sub AliasQualifiedAttributeName_03() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ namespace N <global.AttributeClass.SomeClass()> 'BIND:"SomeClass" class C end class class AttributeClass inherits System.Attribute end class end namespace class AttributeClass inherits System.Attribute class SomeClass end class end class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("AttributeClass.SomeClass", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.[Class], semanticInfo.Type.TypeKind) Assert.Equal("AttributeClass.SomeClass", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.[Class], semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.NotAnAttributeType, semanticInfo.CandidateReason) Assert.Equal(1, semanticInfo.CandidateSymbols.Length) Dim sortedCandidates = semanticInfo.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub AttributeClass.SomeClass..ctor()", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(0).Kind) Assert.Equal(1, semanticInfo.MemberGroup.Length) Dim sortedMethodGroup = semanticInfo.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub AttributeClass.SomeClass..ctor()", sortedMethodGroup(0).ToTestDisplayString()) Assert.[False](semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub AliasQualifiedAttributeName_04() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ namespace N <global.AttributeClass.SomeClass()> 'BIND:"global.AttributeClass.SomeClass" class C end class class AttributeClass inherits System.Attribute end class end namespace class AttributeClass inherits System.Attribute class SomeClass end class end class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of QualifiedNameSyntax)(compilation, "a.vb") Assert.Equal("AttributeClass.SomeClass", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.[Class], semanticInfo.Type.TypeKind) Assert.Equal("AttributeClass.SomeClass", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.[Class], semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.NotAnAttributeType, semanticInfo.CandidateReason) Assert.Equal(1, semanticInfo.CandidateSymbols.Length) Dim sortedCandidates = semanticInfo.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub AttributeClass.SomeClass..ctor()", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(0).Kind) Assert.Equal(1, semanticInfo.MemberGroup.Length) Dim sortedMethodGroup = semanticInfo.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub AttributeClass.SomeClass..ctor()", sortedMethodGroup(0).ToTestDisplayString()) Assert.[False](semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub AliasAttributeName_NonAttributeAlias() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ imports GooAttribute = C <GooAttribute> 'BIND:"GooAttribute" Class C end class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("C", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.[Class], semanticInfo.Type.TypeKind) Assert.Equal("C", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.[Class], semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.NotAnAttributeType, semanticInfo.CandidateReason) Assert.Equal(1, semanticInfo.CandidateSymbols.Length) Dim sortedCandidates = semanticInfo.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub C..ctor()", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(0).Kind) Assert.Equal(1, semanticInfo.MemberGroup.Length) Dim sortedMethodGroup = semanticInfo.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub C..ctor()", sortedMethodGroup(0).ToTestDisplayString()) Assert.[False](semanticInfo.ConstantValue.HasValue) Dim aliasInfo = GetAliasInfoForTest(compilation, "a.vb") Assert.Null(aliasInfo) End Sub <Fact()> Public Sub AliasAttributeName_NonAttributeAlias_GenericType() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ imports GooAttribute = Gen(of Integer) <GooAttribute> 'BIND:"GooAttribute" Class Gen(of T) end class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("Gen(Of System.Int32)", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.[Class], semanticInfo.Type.TypeKind) Assert.Equal("Gen(Of System.Int32)", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.[Class], semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.NotAnAttributeType, semanticInfo.CandidateReason) Assert.Equal(1, semanticInfo.CandidateSymbols.Length) Dim sortedCandidates = semanticInfo.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub Gen(Of System.Int32)..ctor()", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(0).Kind) Assert.Equal(1, semanticInfo.MemberGroup.Length) Dim sortedMethodGroup = semanticInfo.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub Gen(Of System.Int32)..ctor()", sortedMethodGroup(0).ToTestDisplayString()) Assert.[False](semanticInfo.ConstantValue.HasValue) Dim aliasInfo = GetAliasInfoForTest(compilation, "a.vb") Assert.Null(aliasInfo) End Sub <Fact(), WorkItem(545085, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545085")> Public Sub ColorColorBug13346() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Public Class Compilation Public Shared Function M(a As Integer) As Boolean Return False End Function End Class Friend Class Program2 Public ReadOnly Property Compilation As Compilation Get Return Nothing End Get End Property Public Sub Main() Dim x = Compilation.M(a:=123)'BIND:"Compilation" End Sub End Class ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("Compilation", semanticSummary.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.Type.TypeKind) Assert.Equal("Compilation", semanticSummary.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Equal("Compilation", semanticSummary.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, semanticSummary.Symbol.Kind) Assert.Equal(0, semanticSummary.CandidateSymbols.Length) Assert.Null(semanticSummary.Alias) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <WorkItem(529702, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529702")> <Fact()> Public Sub ColorColorBug14084() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class C Shared Sub Goo() End Sub End Class Class A(Of T As C) Class B Dim t As T Sub Goo() T.Goo()'BIND:"T" End Sub End Class End Class ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("T", semanticSummary.Type.ToTestDisplayString()) Assert.Equal(TypeKind.TypeParameter, semanticSummary.Type.TypeKind) Assert.Equal("T", semanticSummary.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.TypeParameter, semanticSummary.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Equal("A(Of T).B.t As T", semanticSummary.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Field, semanticSummary.Symbol.Kind) Assert.Equal(0, semanticSummary.CandidateSymbols.Length) Assert.Null(semanticSummary.Alias) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <WorkItem(546097, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546097")> <Fact()> Public Sub LambdaParametersAsOptional() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Module Test Sub Main() Dim s1 = Function(Optional x = 3) x > 5 'BIND:"3" End Sub End Module ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of LiteralExpressionSyntax)(compilation, "a.vb") Assert.Null(semanticSummary.Symbol) compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Module M Private Function F1() As Object Return Nothing End Function Private F2 = Function(Optional o = F1()) Nothing 'BIND:"F1" End Module ]]></file> </compilation>) semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of VisualBasicSyntaxNode)(compilation, "a.vb") CheckSymbol(semanticSummary.Symbol, "Function M.F1() As Object") End Sub <Fact()> Public Sub OptionalParameterOutsideType() ' Method. Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Sub M(Optional o As Object = 3) 'BIND:"3" End Sub ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of LiteralExpressionSyntax)(compilation, "a.vb") Assert.Null(semanticSummary.Symbol) ' Method with type arguments. compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Sub M(Of T)(Optional o As Object = 3) 'BIND:"3" End Sub ]]></file> </compilation>) semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of LiteralExpressionSyntax)(compilation, "a.vb") Assert.Null(semanticSummary.Symbol) ' Property. compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ ReadOnly Property P(Optional o As Object = 3) As Object 'BIND:"3" Get Return Nothing End Get End Property ]]></file> </compilation>) semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of LiteralExpressionSyntax)(compilation, "a.vb") Assert.Null(semanticSummary.Symbol) ' Event. compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Event E(Optional o As Object = 3) 'BIND:"3" ]]></file> </compilation>) semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of LiteralExpressionSyntax)(compilation, "a.vb") Assert.Null(semanticSummary.Symbol) End Sub <Fact> Public Sub ConstantUnevaluatedReceiver() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="a.vb"><![CDATA[ Class A Const F As Object = Nothing Function M() As Object Return Me.F End Function End Class ]]></file> </compilation>, references:=XmlReferences) compilation.AssertNoErrors() Dim tree = compilation.SyntaxTrees(0) Dim semanticModel = compilation.GetSemanticModel(tree) Dim expr = FindNodeOfTypeFromText(Of ExpressionSyntax)(tree, "Me") Dim info = semanticModel.GetSemanticInfoSummary(expr) CheckSymbol(info.Type, "A") End Sub <Fact> Public Sub CallUnevaluatedReceiver() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="a.vb"><![CDATA[ Class A Shared Function F() As Object Return Nothing End Function Function M() As Object Return Me.F() End Function End Class ]]></file> </compilation>, references:=XmlReferences) compilation.AssertNoErrors() Dim tree = compilation.SyntaxTrees(0) Dim semanticModel = compilation.GetSemanticModel(tree) Dim expr = FindNodeOfTypeFromText(Of ExpressionSyntax)(tree, "Me") Dim info = semanticModel.GetSemanticInfoSummary(expr) CheckSymbol(info.Type, "A") End Sub <Fact> Public Sub AddressOfUnevaluatedReceiver() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="a.vb"><![CDATA[ Class A Shared Sub M() End Sub Function F() As System.Action Return AddressOf (Me).M End Function End Class ]]></file> </compilation>, references:=XmlReferences) compilation.AssertNoErrors() Dim tree = compilation.SyntaxTrees(0) Dim semanticModel = compilation.GetSemanticModel(tree) Dim expr = FindNodeOfTypeFromText(Of ExpressionSyntax)(tree, "Me") Dim info = semanticModel.GetSemanticInfoSummary(expr) CheckSymbol(info.Type, "A") End Sub <Fact> Public Sub TypeExpressionUnevaluatedReceiver() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="a.vb"><![CDATA[ Class A Class B Friend Const F As Object = Nothing End Class Function M() As Object Return (Me.B).F End Function End Class ]]></file> </compilation>, references:=XmlReferences) compilation.AssertNoErrors() Dim tree = compilation.SyntaxTrees(0) Dim semanticModel = compilation.GetSemanticModel(tree) Dim expr = FindNodeOfTypeFromText(Of ExpressionSyntax)(tree, "Me") Dim info = semanticModel.GetSemanticInfoSummary(expr) CheckSymbol(info.Type, "A") End Sub ''' <summary> ''' SymbolInfo and TypeInfo should implement IEquatable&lt;T&gt;. ''' </summary> <WorkItem(792647, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/792647")> <Fact> Public Sub ImplementsIEquatable() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class C Function F() Return Me End Function End Class ]]></file> </compilation>) compilation.AssertNoErrors() Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim expr = FindNodeOfTypeFromText(Of ExpressionSyntax)(tree, "Me") Dim symbolInfo1 = model.GetSymbolInfo(expr) Dim symbolInfo2 = model.GetSymbolInfo(expr) Dim symbolComparer = DirectCast(symbolInfo1, IEquatable(Of SymbolInfo)) Assert.True(symbolComparer.Equals(symbolInfo2)) Dim typeInfo1 = model.GetTypeInfo(expr) Dim typeInfo2 = model.GetTypeInfo(expr) Dim typeComparer = DirectCast(typeInfo1, IEquatable(Of TypeInfo)) Assert.True(typeComparer.Equals(typeInfo2)) End Sub <Fact, WorkItem(2805, "https://github.com/dotnet/roslyn/issues/2805")> Public Sub AliasWithAnError() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Imports ShortName = LongNamespace Namespace NS Class Test Public Function Method1() As Object Return (New ShortName.Class1()).Prop End Function End Class End Namespace ]]></file> </compilation>, options:=TestOptions.DebugDll) compilation.AssertTheseDiagnostics(<expected> BC40056: Namespace or type specified in the Imports 'LongNamespace' 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 ShortName = LongNamespace ~~~~~~~~~~~~~ BC30002: Type 'ShortName.Class1' is not defined. Return (New ShortName.Class1()).Prop ~~~~~~~~~~~~~~~~ </expected>) Dim tree = compilation.SyntaxTrees.Single() Dim node = tree.GetRoot().DescendantNodes().OfType(Of IdentifierNameSyntax)().Where(Function(id) id.Identifier.ValueText = "ShortName").Single() Assert.Equal("ShortName.Class1", node.Parent.ToString()) Dim model = compilation.GetSemanticModel(tree) Dim [alias] = model.GetAliasInfo(node) Assert.Equal("ShortName=LongNamespace", [alias].ToTestDisplayString()) Assert.Equal(SymbolKind.ErrorType, [alias].Target.Kind) Assert.Equal("LongNamespace", [alias].Target.ToTestDisplayString()) Dim symbolInfo = model.GetSymbolInfo(node) Assert.Null(symbolInfo.Symbol) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) End Sub End Class End Namespace
' 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.IO Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.SpecialType Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.OverloadResolution Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Partial Public Class GetExtendedSemanticInfoTests : Inherits SemanticModelTestBase <Fact> Public Sub LambdaInInitializer() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C Private Shared AmbiguousInNSError As Func(Of C, D) = Function(syms As C) As D If C IsNot Nothing Return New D()'BIND:"D" Else Return New D() End If End Function End Class </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") 'simply not crashing is the goal for now. End Sub <Fact> Public Sub BindLambdasInArgsOfBadParent() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> 'note that T is not defined which causes the object creation expression 'to be bad. This test ensures that the arguments are still bound and analyzable. Module M Private Shared Function Meth() As T Return New T(Function() String.Empty)'BIND:"String" End Function End Module </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of PredefinedTypeSyntax)(compilation, "a.vb") 'not crashing End Sub <Fact> Public Sub RunningAfoulOfExtensions() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System.Runtime.CompilerServices Imports System.Linq.Expressions Module M Private Shared Function GetExpressionType(x As Symbol) As TypeSymbol Select Case x.Kind Case Else Dim type = TryCast(x, TypeSymbol)'BIND:"x" If type IsNot Nothing Then Return type End If End Select Return Nothing End Function &lt;Extension()&gt; Sub Type(ByVal x As Integer) End Sub &lt;Extension()&gt; Sub Type(x As String) End Sub End Module </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") 'not crashing End Sub <Fact> Public Sub BindPredefinedTypeOutsideMethodBody() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String())'BIND:"String" End Sub End Module </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of PredefinedTypeSyntax)(compilation, "a.vb") Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("System.String", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact> Public Sub BindPredefinedTypeInsideMethodBody() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Dim x = String.Empty 'BIND:"String" End Sub End Module </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of PredefinedTypeSyntax)(compilation, "a.vb") Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("System.String", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact> Public Sub ConvertedLocal() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Dim x As Integer Dim y As Long y = x'BIND:"x" End Sub End Module </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int64", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.WideningNumeric, semanticInfo.ImplicitConversion.Kind) Assert.Equal("x As System.Int32", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact> Public Sub InaccessibleType1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System Module Program Dim a As A.B'BIND:"B" Sub Main(args As String()) End Sub End Module Class A Private Class B Public Sub f() End Sub End Class End Class </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("A.B", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("A.B", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason) Assert.Equal(1, semanticInfo.CandidateSymbols.Length) Dim sortedCandidates = semanticInfo.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("A.B", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, sortedCandidates(0).Kind) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact> Public Sub InaccessibleType2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System Module Program Sub Main(args As String()) A.B.f()'BIND:"B" End Sub End Module Class A Private Class B Public Sub f() End Sub End Class End Class </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("A.B", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("A.B", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason) Assert.Equal(1, semanticInfo.CandidateSymbols.Length) Dim sortedCandidates = semanticInfo.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("A.B", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, sortedCandidates(0).Kind) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact> Public Sub InaccessibleType3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System Module Program Sub Main(args As String()) Dim z As A.B'BIND:"B" End Sub End Module Class A Private Class B Public Sub f() End Sub End Class End Class </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("A.B", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("A.B", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason) Assert.Equal(1, semanticInfo.CandidateSymbols.Length) Dim sortedCandidates = semanticInfo.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("A.B", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, sortedCandidates(0).Kind) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact> Public Sub AmbiguousType1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System Imports N1, N2 Module Program Dim x As A'BIND:"A" Sub Main(args As String()) End Sub End Module Namespace N1 Class A End Class End Namespace Namespace N2 Class A End Class End Namespace </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("A", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind) Assert.Equal("A", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.Ambiguous, semanticInfo.CandidateReason) Assert.Equal(2, semanticInfo.CandidateSymbols.Length) Dim sortedCandidates = semanticInfo.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("N1.A", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, sortedCandidates(0).Kind) Assert.Equal("N2.A", sortedCandidates(1).ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, sortedCandidates(1).Kind) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact> Public Sub AmbiguousType2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System Imports N1, N2 Module Program Sub Main(args As String()) Dim x As A'BIND:"A" End Sub End Module Namespace N1 Class A End Class End Namespace Namespace N2 Class A End Class End Namespace </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("A", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind) Assert.Equal("A", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.Ambiguous, semanticInfo.CandidateReason) Assert.Equal(2, semanticInfo.CandidateSymbols.Length) Dim sortedCandidates = semanticInfo.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("N1.A", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, sortedCandidates(0).Kind) Assert.Equal("N2.A", sortedCandidates(1).ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, sortedCandidates(1).Kind) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact> Public Sub AmbiguousType3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System Imports N1, N2 Module Program Sub Main(args As String()) A.goo()'BIND:"A" End Sub End Module Namespace N1 Class A End Class End Namespace Namespace N2 Class A End Class End Namespace </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("A", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind) Assert.Equal("A", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.Ambiguous, semanticInfo.CandidateReason) Assert.Equal(2, semanticInfo.CandidateSymbols.Length) Dim sortedCandidates = semanticInfo.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("N1.A", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, sortedCandidates(0).Kind) Assert.Equal("N2.A", sortedCandidates(1).ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, sortedCandidates(1).Kind) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact> Public Sub InaccessibleSharedField() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System Module Program Sub Main(args As String()) Dim z As Integer = A.fi'BIND:"fi" End Sub End Module Class A Private Shared fi As Integer End Class </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason) Assert.Equal(1, semanticInfo.CandidateSymbols.Length) Dim sortedCandidates = semanticInfo.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("A.fi As System.Int32", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.Field, sortedCandidates(0).Kind) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact> Public Sub MethodGroup1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System Module Program Sub Main(args As String()) f(3)'BIND:"f" End Sub Sub f() End Sub Sub f(x As Integer) End Sub Function f(ByVal a As Integer, b As Long) As String Return "hi" End Function End Module </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticInfo.Type) Assert.Null(semanticInfo.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Sub Program.f(x As System.Int32)", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(3, semanticInfo.MemberGroup.Length) Dim sortedMethodGroup = semanticInfo.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Function Program.f(a As System.Int32, b As System.Int64) As System.String", sortedMethodGroup(0).ToTestDisplayString()) Assert.Equal("Sub Program.f()", sortedMethodGroup(1).ToTestDisplayString()) Assert.Equal("Sub Program.f(x As System.Int32)", sortedMethodGroup(2).ToTestDisplayString()) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact> Public Sub MethodGroup2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System Module Program Sub Main(args As String()) Dim x As New Class1() x.f(3, 7)'BIND:"x.f" End Sub End Module Class Class1 Public Sub f() End Sub Public Sub f(x As Integer) End Sub Public Function f(ByVal a As Integer, b As Long) As String Return "hi" End Function End Class </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of MemberAccessExpressionSyntax)(compilation, "a.vb") Assert.Null(semanticInfo.Type) Assert.Null(semanticInfo.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Function Class1.f(a As System.Int32, b As System.Int64) As System.String", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(3, semanticInfo.MemberGroup.Length) Dim sortedMethodGroup = semanticInfo.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Function Class1.f(a As System.Int32, b As System.Int64) As System.String", sortedMethodGroup(0).ToTestDisplayString()) Assert.Equal("Sub Class1.f()", sortedMethodGroup(1).ToTestDisplayString()) Assert.Equal("Sub Class1.f(x As System.Int32)", sortedMethodGroup(2).ToTestDisplayString()) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact> Public Sub InaccessibleMethodGroup() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System Module Program Sub Main(args As String()) Dim x As New Class1() x.f(3, 7)'BIND:"x.f" End Sub End Module Class Class1 Protected Sub f() End Sub Protected Sub f(x As Integer) End Sub Private Function f(ByVal a As Integer, b As Long) As String Return "hi" End Function End Class </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of MemberAccessExpressionSyntax)(compilation, "a.vb") ' This test should return all three inaccessible methods. I am ' leaving it in so it doesn't regress further, but it should be ' better. Assert.Null(semanticInfo.Type) Assert.Null(semanticInfo.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason) Assert.Equal(1, semanticInfo.CandidateSymbols.Length) Dim sortedCandidates = semanticInfo.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Function Class1.f(a As System.Int32, b As System.Int64) As System.String", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(0).Kind) Assert.Equal(3, semanticInfo.MemberGroup.Length) Dim sortedMethodGroup = semanticInfo.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Function Class1.f(a As System.Int32, b As System.Int64) As System.String", sortedMethodGroup(0).ToTestDisplayString()) Assert.Equal("Sub Class1.f()", sortedMethodGroup(1).ToTestDisplayString()) Assert.Equal("Sub Class1.f(x As System.Int32)", sortedMethodGroup(2).ToTestDisplayString()) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact> Public Sub InaccessibleMethodGroup_Constructors_ObjectCreationExpressionSyntax() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Module Program Sub Main(args As String()) Dim x As New Class1(3, 7)'BIND:"New Class1(3, 7)" End Sub End Module Class Class1 Protected Sub New() End Sub Protected Sub New(x As Integer) End Sub Private Sub New(ByVal a As Integer, b As Long) End Sub End Class ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of ObjectCreationExpressionSyntax)(compilation, "a.vb") Assert.Equal("Class1", semanticSummary.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.Type.TypeKind) Assert.Equal("Class1", semanticSummary.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Null(semanticSummary.Symbol) Assert.Equal(CandidateReason.Inaccessible, semanticSummary.CandidateReason) Assert.Equal(1, semanticSummary.CandidateSymbols.Length) Assert.Equal("Sub Class1..ctor(a As System.Int32, b As System.Int64)", semanticSummary.CandidateSymbols(0).ToTestDisplayString()) Assert.Null(semanticSummary.Alias) Assert.Equal(3, semanticSummary.MemberGroup.Length) Dim sortedMethodGroup = semanticSummary.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub Class1..ctor()", sortedMethodGroup(0).ToTestDisplayString()) Assert.Equal("Sub Class1..ctor(a As System.Int32, b As System.Int64)", sortedMethodGroup(1).ToTestDisplayString()) Assert.Equal("Sub Class1..ctor(x As System.Int32)", sortedMethodGroup(2).ToTestDisplayString()) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact> Public Sub InaccessibleMethodGroup_Constructors_IdentifierNameSyntax() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Module Program Sub Main(args As String()) Dim x As New Class1(3, 7)'BIND:"Class1" End Sub End Module Class Class1 Protected Sub New() End Sub Protected Sub New(x As Integer) End Sub Private Sub New(ByVal a As Integer, b As Long) End Sub End Class ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticSummary.Type) Assert.Null(semanticSummary.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Equal("Class1", semanticSummary.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, semanticSummary.CandidateReason) Assert.Equal(0, semanticSummary.CandidateSymbols.Length) Assert.Null(semanticSummary.Alias) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact> Public Sub InaccessibleMethodGroup_AttributeSyntax() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Module Program <Class1(3, 7)>'BIND:"Class1(3, 7)" Sub Main(args As String()) End Sub End Module Class Class1 Inherits Attribute Protected Sub New() End Sub Protected Sub New(x As Integer) End Sub Private Sub New(ByVal a As Integer, b As Long) End Sub End Class ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of AttributeSyntax)(compilation, "a.vb") Assert.Equal("Class1", semanticSummary.Type.ToTestDisplayString()) Assert.Equal(TypeKind.[Class], semanticSummary.Type.TypeKind) Assert.Equal("Class1", semanticSummary.ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Null(semanticSummary.Symbol) Assert.Equal(CandidateReason.Inaccessible, semanticSummary.CandidateReason) Assert.Equal(3, semanticSummary.CandidateSymbols.Length) Dim sortedCandidates = semanticSummary.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub Class1..ctor()", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(0).Kind) Assert.Equal("Sub Class1..ctor(a As System.Int32, b As System.Int64)", sortedCandidates(1).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(1).Kind) Assert.Equal("Sub Class1..ctor(x As System.Int32)", sortedCandidates(2).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(2).Kind) Assert.Null(semanticSummary.Alias) Assert.Equal(3, semanticSummary.MemberGroup.Length) Dim sortedMethodGroup = semanticSummary.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub Class1..ctor()", sortedMethodGroup(0).ToTestDisplayString()) Assert.Equal("Sub Class1..ctor(a As System.Int32, b As System.Int64)", sortedMethodGroup(1).ToTestDisplayString()) Assert.Equal("Sub Class1..ctor(x As System.Int32)", sortedMethodGroup(2).ToTestDisplayString()) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact> Public Sub InaccessibleMethodGroup_Attribute_IdentifierNameSyntax() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Module Program <Class1(3, 7)>'BIND:"Class1" Sub Main(args As String()) End Sub End Module Class Class1 Inherits Attribute Protected Sub New() End Sub Protected Sub New(x As Integer) End Sub Private Sub New(ByVal a As Integer, b As Long) End Sub End Class ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("Class1", semanticSummary.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.Type.TypeKind) Assert.Equal("Class1", semanticSummary.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Null(semanticSummary.Symbol) Assert.Equal(CandidateReason.Inaccessible, semanticSummary.CandidateReason) Assert.Equal(3, semanticSummary.CandidateSymbols.Length) Dim sortedCandidates = semanticSummary.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub Class1..ctor()", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(0).Kind) Assert.Equal("Sub Class1..ctor(a As System.Int32, b As System.Int64)", sortedCandidates(1).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(1).Kind) Assert.Equal("Sub Class1..ctor(x As System.Int32)", sortedCandidates(2).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(2).Kind) Assert.Null(semanticSummary.Alias) Assert.Equal(3, semanticSummary.MemberGroup.Length) Dim sortedMethodGroup = semanticSummary.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub Class1..ctor()", sortedMethodGroup(0).ToTestDisplayString()) Assert.Equal("Sub Class1..ctor(a As System.Int32, b As System.Int64)", sortedMethodGroup(1).ToTestDisplayString()) Assert.Equal("Sub Class1..ctor(x As System.Int32)", sortedMethodGroup(2).ToTestDisplayString()) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact> Public Sub InaccessibleConstructorsFiltered_ObjectCreationExpressionSyntax() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Module Program Sub Main(args As String()) Dim x As New Class1(3, 7)'BIND:"New Class1(3, 7)" End Sub End Module Class Class1 Protected Sub New() End Sub Public Sub New(x As Integer) End Sub Public Sub New(ByVal a As Integer, b As Long) End Sub End Class ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of ObjectCreationExpressionSyntax)(compilation, "a.vb") Assert.Equal("Class1", semanticSummary.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.Type.TypeKind) Assert.Equal("Class1", semanticSummary.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Equal("Sub Class1..ctor(a As System.Int32, b As System.Int64)", semanticSummary.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Method, semanticSummary.Symbol.Kind) Assert.Equal(0, semanticSummary.CandidateSymbols.Length) Assert.Null(semanticSummary.Alias) Assert.Equal(2, semanticSummary.MemberGroup.Length) Dim sortedMethodGroup = semanticSummary.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub Class1..ctor(a As System.Int32, b As System.Int64)", sortedMethodGroup(0).ToTestDisplayString()) Assert.Equal("Sub Class1..ctor(x As System.Int32)", sortedMethodGroup(1).ToTestDisplayString()) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact> Public Sub InaccessibleConstructorsFiltered_IdentifierNameSyntax() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Module Program Sub Main(args As String()) Dim x As New Class1(3, 7)'BIND:"Class1" End Sub End Module Class Class1 Protected Sub New() End Sub Public Sub New(x As Integer) End Sub Public Sub New(ByVal a As Integer, b As Long) End Sub End Class ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticSummary.Type) Assert.Null(semanticSummary.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Equal("Class1", semanticSummary.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, semanticSummary.Symbol.Kind) Assert.Equal(0, semanticSummary.CandidateSymbols.Length) Assert.Null(semanticSummary.Alias) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact> Public Sub InaccessibleConstructorsFiltered_IdentifierNameSyntax2() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Module Program Sub Main(args As String()) Dim x As New Class1(3, 7)'BIND:"New Class1(3, 7)" End Sub End Module Class Class1 Protected Sub New() End Sub Public Sub New(x As Integer) End Sub Public Sub New(ByVal a As Integer, b As Long) End Sub End Class ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of ObjectCreationExpressionSyntax)(compilation, "a.vb") Assert.Equal("Class1", semanticSummary.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.Type.TypeKind) Assert.Equal("Class1", semanticSummary.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Equal("Sub Class1..ctor(a As System.Int32, b As System.Int64)", semanticSummary.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Method, semanticSummary.Symbol.Kind) Assert.Equal(0, semanticSummary.CandidateSymbols.Length) Assert.Null(semanticSummary.Alias) Assert.Equal(2, semanticSummary.MemberGroup.Length) Dim sortedMethodGroup = semanticSummary.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub Class1..ctor(a As System.Int32, b As System.Int64)", sortedMethodGroup(0).ToTestDisplayString()) Assert.Equal("Sub Class1..ctor(x As System.Int32)", sortedMethodGroup(1).ToTestDisplayString()) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact> Public Sub InaccessibleConstructorsFiltered_AttributeSyntax() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Module Program <Class1(3, 7)>'BIND:"Class1(3, 7)" Sub Main(args As String()) End Sub End Module Class Class1 Inherits Attribute Protected Sub New() End Sub Public Sub New(x As Integer) End Sub Public Sub New(ByVal a As Integer, b As Long) End Sub End Class ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of AttributeSyntax)(compilation, "a.vb") Assert.Equal("Class1", semanticSummary.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.Type.TypeKind) Assert.Equal("Class1", semanticSummary.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Equal("Sub Class1..ctor(a As System.Int32, b As System.Int64)", semanticSummary.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Method, semanticSummary.Symbol.Kind) Assert.Equal(0, semanticSummary.CandidateSymbols.Length) Assert.Null(semanticSummary.Alias) Assert.Equal(2, semanticSummary.MemberGroup.Length) Dim sortedMethodGroup = semanticSummary.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub Class1..ctor(a As System.Int32, b As System.Int64)", sortedMethodGroup(0).ToTestDisplayString()) Assert.Equal("Sub Class1..ctor(x As System.Int32)", sortedMethodGroup(1).ToTestDisplayString()) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact> Public Sub InaccessibleConstructorsFiltered_Attribute_IdentifierNameSyntax() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Module Program <Class1(3, 7)>'BIND:"Class1" Sub Main(args As String()) End Sub End Module Class Class1 Inherits Attribute Protected Sub New() End Sub Public Sub New(x As Integer) End Sub Public Sub New(ByVal a As Integer, b As Long) End Sub End Class ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("Class1", semanticSummary.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.Type.TypeKind) Assert.Equal("Class1", semanticSummary.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Equal("Sub Class1..ctor(a As System.Int32, b As System.Int64)", semanticSummary.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Method, semanticSummary.Symbol.Kind) Assert.Equal(0, semanticSummary.CandidateSymbols.Length) Assert.Null(semanticSummary.Alias) Assert.Equal(2, semanticSummary.MemberGroup.Length) Dim sortedMethodGroup = semanticSummary.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub Class1..ctor(a As System.Int32, b As System.Int64)", sortedMethodGroup(0).ToTestDisplayString()) Assert.Equal("Sub Class1..ctor(x As System.Int32)", sortedMethodGroup(1).ToTestDisplayString()) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact> Public Sub Invocation1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System Module Program Sub Main(args As String()) f(3, 7)'BIND:"f(3, 7)" End Sub Sub f() End Sub Sub f(x As Integer) End Sub Function f(ByVal a As Integer, b As Long) As String Return "hi" End Function End Module </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of InvocationExpressionSyntax)(compilation, "a.vb") Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Function Program.f(a As System.Int32, b As System.Int64) As System.String", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact> Public Sub Invocation2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System Module Program Sub Main(args As String()) Dim x As New Class1() x.f(3, 7)'BIND:"x.f(3, 7)" End Sub End Module Class Class1 Public Sub f() End Sub Public Sub f(x As Integer) End Sub Public Function f(ByVal a As Integer, b As Long) As String Return "hi" End Function End Class </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of InvocationExpressionSyntax)(compilation, "a.vb") Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Function Class1.f(a As System.Int32, b As System.Int64) As System.String", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact> Public Sub InaccessibleInvocation() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System Module Program Sub Main(args As String()) Dim x As New Class1() x.f(3, 7)'BIND:"x.f(3, 7)" End Sub End Module Class Class1 Protected Sub f() End Sub Protected Sub f(x As Integer) End Sub Private Function f(ByVal a As Integer, b As Long) As String Return "hi" End Function End Class </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of InvocationExpressionSyntax)(compilation, "a.vb") Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason) Assert.Equal(1, semanticInfo.CandidateSymbols.Length) Dim sortedCandidates = semanticInfo.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Function Class1.f(a As System.Int32, b As System.Int64) As System.String", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(0).Kind) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact> Public Sub Property1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Dim a As New X a.Prop = 4'BIND:"Prop" End Sub End Module Class X Public Property Prop As String Get Return "" End Get Set End Set End Property End Class </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Property X.Prop As System.String", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Property, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact> Public Sub Property2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Dim a As New X Dim u As String = a.Prop'BIND:"a.Prop" End Sub End Module Class X Public Property Prop As String Get Return "" End Get Set End Set End Property End Class </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of MemberAccessExpressionSyntax)(compilation, "a.vb") Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Property X.Prop As System.String", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Property, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact> Public Sub SimpleConstantExpression() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Dim i As Integer = 10 * 10'BIND:"10 * 10" End Sub End Module Class X End Class </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of BinaryExpressionSyntax)(compilation, "a.vb") Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Function System.Int32.op_Multiply(left As System.Int32, right As System.Int32) As System.Int32", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.True(semanticInfo.ConstantValue.HasValue) Assert.Equal(100, semanticInfo.ConstantValue.Value) End Sub <Fact> Public Sub InaccessibleParameter() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub goo(a As Outer.Inner) Dim q As Integer q = a.x'BIND:"a" End Sub End Module Class Outer Private Class Inner Public x As Integer End Class End Class </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("Outer.Inner", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("Outer.Inner", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("a As Outer.Inner", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Parameter, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim paramSym As ParameterSymbol = DirectCast(semanticInfo.Symbol, ParameterSymbol) Assert.Equal(TypeKind.Error, paramSym.Type.TypeKind) End Sub <WorkItem(538447, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538447")> <Fact> Public Sub CastInterfaceToArray() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim i As ICloneable = New Integer() {} Dim arr() As Integer arr = CType(i, Integer())'BIND:"CType(i, Integer())" arr = DirectCast(i, Integer()) arr = TryCast(i, Integer()) End Sub End Module </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of CastExpressionSyntax)(compilation, "a.vb") Assert.Equal("System.Int32()", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Array, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32()", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Array, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact> Public Sub ImplementsClause1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Interface IA(Of T) Overloads Sub Goo(ByVal x As T) Overloads Sub Goo(ByVal x As String) End Interface Interface IC(Of T) Inherits IA(Of T) End Interface Interface IB Overloads Sub Bar(x As String) ReadOnly Property P As Long Property R(x As String) As Long End Interface Class K Implements IC(Of Integer) Implements IB Public Overloads Sub F(x As String) Implements IB.Bar, IC(Of Integer).Goo 'BIND1:"IB.Bar" 'BIND2:"Goo" End Sub Public Overloads Sub F(x As Integer) Implements IA(Of Integer).Goo 'BIND3:"IA(Of Integer).Goo" End Sub Public Property Q(x As String) As Long Implements IB.R 'BIND4:"IB.R" Get Return 0 End Get Set End Set End Property Public Property Q As Long Implements IB.P 'BIND5:"IB" Get Return 0 End Get Set End Set End Property End Class </file> </compilation>) 'IB.Bar Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of QualifiedNameSyntax)(compilation, "a.vb", 1) Assert.Null(semanticInfo.Type) Assert.Null(semanticInfo.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Sub IB.Bar(x As System.String)", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) 'Goo semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb", 2) Assert.Null(semanticInfo.Type) Assert.Null(semanticInfo.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Sub IA(Of System.Int32).Goo(x As System.String)", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) ' IA(Of Integer).Goo semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of QualifiedNameSyntax)(compilation, "a.vb", 3) Assert.Null(semanticInfo.Type) Assert.Null(semanticInfo.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Sub IA(Of System.Int32).Goo(x As System.Int32)", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) ' IB.R semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of QualifiedNameSyntax)(compilation, "a.vb", 4) Assert.Null(semanticInfo.Type) Assert.Null(semanticInfo.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Property IB.R(x As System.String) As System.Int64", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Property, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) ' IB semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb", 5) Assert.Equal("IB", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Interface, semanticInfo.Type.TypeKind) Assert.Equal("IB", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Interface, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("IB", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact> Public Sub ImplementsClause2() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports System Interface I1 Sub goo(x As Integer) End Interface Class C1 Implements I1 Public Function goo(x As Integer) As String Implements I1.goo'BIND:"I1.goo" Throw New NotImplementedException() End Function End Class ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of QualifiedNameSyntax)(compilation, "a.vb") Assert.Null(semanticSummary.Type) Assert.Null(semanticSummary.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Null(semanticSummary.Symbol) Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticSummary.CandidateReason) Assert.Equal(1, semanticSummary.CandidateSymbols.Length) Dim sortedCandidates = semanticSummary.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub I1.goo(x As System.Int32)", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(0).Kind) Assert.Null(semanticSummary.Alias) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:="https://github.com/dotnet/roslyn/issues/29531")> Public Sub ImplementsClause3() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports System Interface I1 Sub goo(x As Integer) Sub goo(x As Integer, y As Integer) End Interface Class C1 Implements I1 Public Sub goo(x As Long) Implements I1.goo'BIND:"I1.goo" Throw New NotImplementedException() End Sub End Class ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of QualifiedNameSyntax)(compilation, "a.vb") Assert.Null(semanticSummary.Type) Assert.Null(semanticSummary.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Null(semanticSummary.Symbol) Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticSummary.CandidateReason) Assert.Equal(2, semanticSummary.CandidateSymbols.Length) Dim sortedCandidates = semanticSummary.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString(), StringComparer.Ordinal).ToArray() Assert.Equal("Sub I1.goo(x As System.Int32)", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(0).Kind) Assert.Equal("Sub I1.goo(x As System.Int32, y As System.Int32)", sortedCandidates(1).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(1).Kind) Assert.Null(semanticSummary.Alias) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact> Public Sub ImplementsClause4() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports System Interface I1 Sub goo(x As Integer) Sub goo(x As Integer, y As Integer) End Interface Class C1 Public Sub goo(x As Integer) Implements I1.goo 'BIND:"I1.goo"'BIND:"I1.goo" Throw New NotImplementedException() End Sub End Class ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of QualifiedNameSyntax)(compilation, "a.vb") Assert.Null(semanticSummary.Type) Assert.Null(semanticSummary.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Null(semanticSummary.Symbol) Assert.Equal(CandidateReason.NotReferencable, semanticSummary.CandidateReason) Assert.Equal(1, semanticSummary.CandidateSymbols.Length) Dim sortedCandidates = semanticSummary.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub I1.goo(x As System.Int32)", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(0).Kind) Assert.Null(semanticSummary.Alias) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact> Public Sub ImplementsClause5() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports System Interface I1 Private Sub goo(x As Integer) End Interface Class C1 Implements I1 Public Sub goo(x As Integer) Implements I1.goo 'BIND:"I1.goo"'BIND:"I1.goo" Throw New NotImplementedException() End Sub End Class ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of QualifiedNameSyntax)(compilation, "a.vb") Assert.Null(semanticSummary.Type) Assert.Null(semanticSummary.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Null(semanticSummary.Symbol) Assert.Equal(CandidateReason.Inaccessible, semanticSummary.CandidateReason) Assert.Equal(1, semanticSummary.CandidateSymbols.Length) Dim sortedCandidates = semanticSummary.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub I1.goo(x As System.Int32)", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(0).Kind) Assert.Null(semanticSummary.Alias) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact> Public Sub ImplementsClause6() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports System Interface I1 Inherits I2, I3 End Interface Interface I2 Sub goo(x As Integer, z As String) End Interface Interface I3 Sub goo(x As Integer, y As Integer) End Interface Class C1 Public Sub goo(x As Integer) Implements I1.goo 'BIND:"I1.goo"'BIND:"I1.goo" Throw New NotImplementedException() End Sub End Class ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of QualifiedNameSyntax)(compilation, "a.vb") Assert.Null(semanticSummary.Type) Assert.Null(semanticSummary.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Null(semanticSummary.Symbol) Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticSummary.CandidateReason) Assert.Equal(2, semanticSummary.CandidateSymbols.Length) Dim sortedCandidates = semanticSummary.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub I2.goo(x As System.Int32, z As System.String)", sortedCandidates(0).ToTestDisplayString()) Assert.Equal("Sub I3.goo(x As System.Int32, y As System.Int32)", sortedCandidates(1).ToTestDisplayString()) Assert.Null(semanticSummary.Alias) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact> Public Sub ImplementsClause7() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports System Module m1 Public Sub main() End Sub End Module Interface I1 Inherits I2, I3 End Interface Interface I2 Event E1() End Interface Interface I3 Event E2 As I1.E1EventHandler End Interface Class C1 Implements I1 Public Event E3() Implements I2.E1, I3.E2'BIND:"I3.E2" End Class ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of QualifiedNameSyntax)(compilation, "a.vb") Assert.Null(semanticSummary.Type) Assert.Null(semanticSummary.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Equal("Event I3.E2 As I2.E1EventHandler", semanticSummary.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Event, semanticSummary.Symbol.Kind) Assert.Equal(0, semanticSummary.CandidateSymbols.Length) Assert.Null(semanticSummary.Alias) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact()> Public Sub InterfaceImplementationCantFindMatching() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Interface IA Overloads Sub Goo(ByVal x As Long) Overloads Sub Goo(ByVal x As String) End Interface Class K Implements IA Public Overloads Sub F(x As Integer) Implements IA.Goo'BIND:"IA.Goo" End Sub End Class </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of QualifiedNameSyntax)(compilation, "a.vb") Assert.Null(semanticInfo.Type) Assert.Null(semanticInfo.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.True(semanticInfo.CandidateSymbols.Length > 0, "Should have candidate symbols") Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason) Assert.False(semanticInfo.MemberGroup.Length > 0, "Shouldn't have member group") Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <WorkItem(539111, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539111")> <Fact> Public Sub MethodReferenceWithImplicitTypeArguments() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System Module Module1 Sub Main() Goo(Of Integer)'BIND:"Goo(Of Integer)" End Sub Sub Goo(a As String) End Sub Sub Goo(ByRef a As String, b As String) End Sub Sub Goo(Of T)(a As String, b As String) End Sub End Module </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of GenericNameSyntax)(compilation, "a.vb") Assert.Null(semanticInfo.Type) Assert.Null(semanticInfo.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason) Assert.Equal(1, semanticInfo.CandidateSymbols.Length) Dim sortedCandidates = semanticInfo.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub Module1.Goo(Of System.Int32)(a As System.String, b As System.String)", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(0).Kind) Assert.Equal(1, semanticInfo.MemberGroup.Length) Dim sortedMethodGroup = semanticInfo.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub Module1.Goo(Of System.Int32)(a As System.String, b As System.String)", sortedMethodGroup(0).ToTestDisplayString()) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <WorkItem(538452, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538452")> <Fact> Public Sub InvalidMethodInvocationExpr() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Sub Main() T()'BIND:"T()" End Sub Sub T() End Sub </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of InvocationExpressionSyntax)(compilation, "a.vb") Assert.Equal(SpecialType.System_Void, semanticInfo.Type.SpecialType) Assert.Equal(SpecialType.System_Void, semanticInfo.ConvertedType.SpecialType) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("T", semanticInfo.Symbol.Name) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact> Public Sub UnaryPlusExprWithoutMsCorlibRef() Dim compilation = CreateEmptyCompilationWithReferences( <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim count As Integer count = +10 'BIND:"+10"'BIND:"+10" End Sub End Module </file> </compilation>, {}) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of UnaryExpressionSyntax)(compilation, "a.vb") Assert.Equal("System.Int32[missing]", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32[missing]", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Function System.Int32[missing].op_UnaryPlus(value As System.Int32[missing]) As System.Int32[missing]", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <WorkItem(4280, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub BindingIsNothingFunc() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports Microsoft.VisualBasic Module Module1 Sub Main() Dim var1 As Object If IsNothing(var1) Then'BIND:"IsNothing(var1)" End If End Sub End Module </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of InvocationExpressionSyntax)(compilation, "a.vb") Assert.Equal("System.Boolean", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) End Sub <Fact> Public Sub MaxIntPlusOneHexLiteralConst() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim lngPass As Integer lngPass = &amp;H80000000'BIND:"&amp;H80000000" End Sub End Module </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of LiteralExpressionSyntax)(compilation, "a.vb") Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.True(semanticInfo.ConstantValue.HasValue) Assert.Equal(CInt(-2147483648), semanticInfo.ConstantValue.Value) End Sub <WorkItem(539017, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539017")> <Fact> Public Sub ParenExprInMultiDimArrayDeclWithError() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Module Mod1 Sub Main() Dim scen3(, 5,6,) As Integer Dim x((,)) As Integer 'BIND:"(,)" End Sub End Module ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of TupleExpressionSyntax)(compilation, "a.vb") Assert.Equal("(?, ?)", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(Nothing, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact> Public Sub InvocExprWithImplicitlyTypedArgument() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Module Module1 Sub VerifyByteArray(ByRef arry() As Byte, ByRef lbnd As Integer) End Sub Sub Main() Dim vsarry() As Byte Dim Max = 140000 VerifyByteArray(vsarry, Max)'BIND:"VerifyByteArray(vsarry, Max)" End Sub End Module </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of InvocationExpressionSyntax)(compilation, "a.vb") Assert.Equal("System.Void", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Void", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Sub Module1.VerifyByteArray(ByRef arry As System.Byte(), ByRef lbnd As System.Int32)", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <WorkItem(4512, "DevDiv_Projects/Roslyn")> <Fact> Public Sub MultiDimArrayCreationExpr() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim y = New Object() {1, 2} Dim x As Object = New Object()() {y, y}'BIND:"New Object()() {y, y}" End Sub End Module </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of ArrayCreationExpressionSyntax)(compilation, "a.vb") Assert.Equal("System.Object()()", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Array, semanticInfo.Type.TypeKind) Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.WideningReference, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <WorkItem(527716, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527716")> <Fact> Public Sub EmptyParenExprInArrayDeclWithError() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Module Mod1 Sub Main() Dim x1 = New Single(0, (* ) - 1) {{2}, {4}}'BIND:"(* )" End Sub End Module </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of ParenthesizedExpressionSyntax)(compilation, "a.vb") Assert.Equal("?", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind) Assert.Equal("?", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <WorkItem(538918, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538918")> <Fact> Public Sub MeSymbol() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C Sub Test() Me.Test()'BIND:"Me" End Sub End Class </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of MeExpressionSyntax)(compilation, "a.vb") Assert.Equal("C", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("C", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Me As C", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Parameter, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.True(DirectCast(semanticInfo.Symbol, ParameterSymbol).IsMe, "should be Me symbol") Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <WorkItem(527818, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527818")> <Fact> Public Sub BindingFuncNoBracket() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System Imports Microsoft.VisualBasic Namespace VBNS Class Test Function MyFunc() As Byte Return Nothing End Function Sub MySub() Dim ret As Byte = MyFunc'BIND:"MyFunc" End Sub End Class End Namespace </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("System.Byte", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Byte", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Function VBNS.Test.MyFunc() As System.Byte", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact> Public Sub NamespaceAlias() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports S = System Namespace NS Class Test Dim x As S.Exception'BIND:"S" End Class End Namespace </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticInfo.Type) Assert.Null(semanticInfo.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.NotNull(semanticInfo.Symbol) Assert.NotNull(semanticInfo.Alias) Assert.Equal("S=System", semanticInfo.Alias.ToTestDisplayString()) Assert.Equal(SymbolKind.Alias, semanticInfo.Alias.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Dim ns = DirectCast(semanticInfo.Alias.Target, NamespaceSymbol) Assert.Equal(ns.Name, "System") Assert.Equal(compilation.SourceModule, semanticInfo.Alias.ContainingModule) Assert.Equal(compilation.Assembly, semanticInfo.Alias.ContainingAssembly) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact> Public Sub NamespaceAlias2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System Imports N = NS1.NS2 Namespace NS1.NS2 Public Class A Public Shared Sub M Dim o As N.A'BIND:"N" End Sub End Class End Namespace </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticInfo.Type) Assert.Null(semanticInfo.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.NotNull(semanticInfo.Symbol) Assert.NotNull(semanticInfo.Alias) Assert.Equal("N=NS1.NS2", semanticInfo.Alias.ToTestDisplayString()) Assert.Equal(SymbolKind.Alias, semanticInfo.Alias.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Dim ns = DirectCast(semanticInfo.Alias.Target, NamespaceSymbol) Assert.Equal("NS1.NS2", ns.ToTestDisplayString()) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact> Public Sub TypeAlias() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports S = System.String Namespace NS Class Test Sub Goo Dim x As String x = S.Empty'BIND:"S" End Sub End Class End Namespace </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.NotNull(semanticInfo.Symbol) Assert.NotNull(semanticInfo.Alias) Assert.Equal("S=System.String", semanticInfo.Alias.ToTestDisplayString()) Assert.Equal(SymbolKind.Alias, semanticInfo.Alias.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal("String", semanticInfo.Alias.Target.Name) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact> Public Sub TypeAlias2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Imports System.Linq Imports T = System.Guid Module Program Sub Main(args As String()) Dim a As Type a = GetType(T)'BIND:"T" End Sub End Module </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("System.Guid", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Guid", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.NotNull(semanticInfo.Symbol) Assert.NotNull(semanticInfo.Alias) Assert.Equal("T=System.Guid", semanticInfo.Alias.ToTestDisplayString()) Assert.Equal(SymbolKind.Alias, semanticInfo.Alias.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact> Public Sub TypeAlias3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Imports System.Linq Imports T = System.Guid Module Program Dim a As T'BIND:"T" Sub Main(args As String()) End Sub End Module </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("System.Guid", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Guid", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.NotNull(semanticInfo.Symbol) Assert.NotNull(semanticInfo.Alias) Assert.Equal("T=System.Guid", semanticInfo.Alias.ToTestDisplayString()) Assert.Equal(SymbolKind.Alias, semanticInfo.Alias.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <WorkItem(540279, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540279")> <Fact> Public Sub NoMembersForVoidReturnType() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C Sub Test() System.Console.WriteLine()'BIND:"System.Console.WriteLine()" End Sub End Class </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of InvocationExpressionSyntax)(compilation, "a.vb") Assert.Equal("System.Void", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Void", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Sub System.Console.WriteLine()", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim semanticModel = compilation.GetSemanticModel(CompilationUtils.GetTree(compilation, "a.vb")) Dim methodSymbol As MethodSymbol = DirectCast(semanticInfo.Symbol, MethodSymbol) Dim returnType = methodSymbol.ReturnType Dim symbols = semanticModel.LookupSymbols(0, returnType) Assert.Equal(0, symbols.Length) End Sub <Fact> Public Sub EnumMember1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Enum filePermissions create = 1 read = create'BIND:"create" write = 4 delete = 8 End Enum Class c1 Public Shared Sub Main(args As String()) Dim file1Perm As filePermissions file1Perm = filePermissions.create Or filePermissions.read End Sub End Class </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("filePermissions", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Enum, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.WideningNumeric Or ConversionKind.InvolvesEnumTypeConversions, semanticInfo.ImplicitConversion.Kind) Assert.Equal("filePermissions.create", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Field, semanticInfo.Symbol.Kind) Assert.True(TypeOf semanticInfo.Symbol Is SourceEnumConstantSymbol, "Should have bound to synthesized enum constant") Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.True(semanticInfo.ConstantValue.HasValue) Assert.Equal(1, semanticInfo.ConstantValue.Value) End Sub <Fact> Public Sub CatchVariable() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class c1 Public Shared Sub Main() Try Catch ex as Exception 'BIND:"ex" End Try End Sub End Class </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("Exception", semanticInfo.Type.ToTestDisplayString()) End Sub <Fact> Public Sub CatchVariable1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class c1 Public Shared Sub Main() dim a as Action = Sub() Try Catch ex as Exception 'BIND:"ex" End Try End Sub End Sub End Class </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("Exception", semanticInfo.Type.ToTestDisplayString()) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <WorkItem(540050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540050")> <Fact> Public Sub StaticLocalSymbol() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C Public Function goo() As Integer Static i As Integer = 23 i = i + 1'BIND:"i" Return i End Function Public Shared Sub Main() End Sub End Class </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("i As System.Int32", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim iSymbol = DirectCast(semanticInfo.Symbol, LocalSymbol) Assert.True(iSymbol.IsStatic) Assert.False(iSymbol.IsShared) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:="https://github.com/dotnet/roslyn/issues/29531")> Public Sub IncompleteWriteLine() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Console.WriteLine( 'BIND:"WriteLine" End Sub End Module </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticInfo.Type) Assert.Null(semanticInfo.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason) Assert.Equal(12, semanticInfo.CandidateSymbols.Length) Dim sortedCandidates = semanticInfo.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString(), StringComparer.InvariantCulture).ToArray() Assert.Equal("Sub System.Console.WriteLine(buffer As System.Char())", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(0).Kind) Assert.Equal("Sub System.Console.WriteLine(value As System.Boolean)", sortedCandidates(1).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(1).Kind) Assert.Equal("Sub System.Console.WriteLine(value As System.Char)", sortedCandidates(2).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(2).Kind) Assert.Equal("Sub System.Console.WriteLine(value As System.Decimal)", sortedCandidates(3).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(3).Kind) Assert.Equal("Sub System.Console.WriteLine(value As System.Double)", sortedCandidates(4).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(4).Kind) Assert.Equal("Sub System.Console.WriteLine(value As System.Int32)", sortedCandidates(5).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(5).Kind) Assert.Equal("Sub System.Console.WriteLine(value As System.Int64)", sortedCandidates(6).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(6).Kind) Assert.Equal("Sub System.Console.WriteLine(value As System.Object)", sortedCandidates(7).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(7).Kind) Assert.Equal("Sub System.Console.WriteLine(value As System.Single)", sortedCandidates(8).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(8).Kind) Assert.Equal("Sub System.Console.WriteLine(value As System.String)", sortedCandidates(9).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(9).Kind) Assert.Equal("Sub System.Console.WriteLine(value As System.UInt32)", sortedCandidates(10).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(10).Kind) Assert.Equal("Sub System.Console.WriteLine(value As System.UInt64)", sortedCandidates(11).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(11).Kind) Assert.Equal(19, semanticInfo.MemberGroup.Length) Dim sortedMethodGroup = semanticInfo.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString(), StringComparer.Ordinal).ToArray() Assert.Equal("Sub System.Console.WriteLine()", sortedMethodGroup(0).ToTestDisplayString()) Assert.Equal("Sub System.Console.WriteLine(buffer As System.Char())", sortedMethodGroup(1).ToTestDisplayString()) Assert.Equal("Sub System.Console.WriteLine(buffer As System.Char(), index As System.Int32, count As System.Int32)", sortedMethodGroup(2).ToTestDisplayString()) Assert.Equal("Sub System.Console.WriteLine(format As System.String, ParamArray arg As System.Object())", sortedMethodGroup(3).ToTestDisplayString()) Assert.Equal("Sub System.Console.WriteLine(format As System.String, arg0 As System.Object)", sortedMethodGroup(4).ToTestDisplayString()) Assert.Equal("Sub System.Console.WriteLine(format As System.String, arg0 As System.Object, arg1 As System.Object)", sortedMethodGroup(5).ToTestDisplayString()) Assert.Equal("Sub System.Console.WriteLine(format As System.String, arg0 As System.Object, arg1 As System.Object, arg2 As System.Object)", sortedMethodGroup(6).ToTestDisplayString()) Assert.Equal("Sub System.Console.WriteLine(format As System.String, arg0 As System.Object, arg1 As System.Object, arg2 As System.Object, arg3 As System.Object)", sortedMethodGroup(7).ToTestDisplayString()) Assert.Equal("Sub System.Console.WriteLine(value As System.Boolean)", sortedMethodGroup(8).ToTestDisplayString()) Assert.Equal("Sub System.Console.WriteLine(value As System.Char)", sortedMethodGroup(9).ToTestDisplayString()) Assert.Equal("Sub System.Console.WriteLine(value As System.Decimal)", sortedMethodGroup(10).ToTestDisplayString()) Assert.Equal("Sub System.Console.WriteLine(value As System.Double)", sortedMethodGroup(11).ToTestDisplayString()) Assert.Equal("Sub System.Console.WriteLine(value As System.Int32)", sortedMethodGroup(12).ToTestDisplayString()) Assert.Equal("Sub System.Console.WriteLine(value As System.Int64)", sortedMethodGroup(13).ToTestDisplayString()) Assert.Equal("Sub System.Console.WriteLine(value As System.Object)", sortedMethodGroup(14).ToTestDisplayString()) Assert.Equal("Sub System.Console.WriteLine(value As System.Single)", sortedMethodGroup(15).ToTestDisplayString()) Assert.Equal("Sub System.Console.WriteLine(value As System.String)", sortedMethodGroup(16).ToTestDisplayString()) Assert.Equal("Sub System.Console.WriteLine(value As System.UInt32)", sortedMethodGroup(17).ToTestDisplayString()) Assert.Equal("Sub System.Console.WriteLine(value As System.UInt64)", sortedMethodGroup(18).ToTestDisplayString()) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact> Public Sub ReturnedNothingLiteral() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System Module Program Function Main(args As String()) As String Return Nothing'BIND:"Nothing" End Function End Module </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of LiteralExpressionSyntax)(compilation, "a.vb") Assert.Null(semanticInfo.Type) Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.WideningNothingLiteral, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.True(semanticInfo.ConstantValue.HasValue) Assert.Null(semanticInfo.ConstantValue.Value) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:="https://github.com/dotnet/roslyn/issues/29531")> Public Sub FailedConstructorCall() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System Class C End Class Class V Sub goo Dim c As C c = New C(13)'BIND:"C" End Sub End Class </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticInfo.Type) Assert.Null(semanticInfo.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("C", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:="https://github.com/dotnet/roslyn/issues/29531")> Public Sub FailedConstructorCall2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Imports System Class C End Class Class V Sub goo Dim c As C c = New C(13)'BIND:"New C(13)" End Sub End Class </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of ObjectCreationExpressionSyntax)(compilation, "a.vb") Assert.Equal("C", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("C", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason) Assert.Equal(1, semanticInfo.CandidateSymbols.Length) Dim sortedCandidates = semanticInfo.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub C..ctor()", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(0).Kind) Assert.Equal(1, semanticInfo.MemberGroup.Length) Dim sortedMethodGroup = semanticInfo.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub C..ctor()", sortedMethodGroup(0).ToTestDisplayString()) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact> Public Sub ExplicitCallToDefaultProperty1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class X Public ReadOnly Property Goo As Y Get Return Nothing End Get End Property End Class Class Y Public Default ReadOnly Property Item(ByVal a As Integer) As String Get Return "hi" End Get End Property End Class Module M1 Sub Main() Dim a As String Dim b As X b = New X() a = b.Goo.Item(4)'BIND:"Item" End Sub End Module </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticInfo.Type) Assert.Null(semanticInfo.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("ReadOnly Property Y.Item(a As System.Int32) As System.String", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Property, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(1, semanticInfo.MemberGroup.Length) Dim sortedMethodGroup = semanticInfo.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("ReadOnly Property Y.Item(a As System.Int32) As System.String", sortedMethodGroup(0).ToTestDisplayString()) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub ExplicitCallToDefaultProperty2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class X Public ReadOnly Property Goo As Y Get Return Nothing End Get End Property End Class Class Y Public Default ReadOnly Property Item(ByVal a As Integer) As String Get Return "hi" End Get End Property End Class Module M1 Sub Main() Dim a As String Dim b As X b = New X() a = b.Goo.Item(4)'BIND:"b.Goo.Item(4)" End Sub End Module </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of InvocationExpressionSyntax)(compilation, "a.vb") Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("ReadOnly Property Y.Item(a As System.Int32) As System.String", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Property, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <WorkItem(541240, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541240")> <Fact()> Public Sub ConstFieldInitializer() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C Public Const ClassId As String = Nothing 'BIND:"Nothing" End Class </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of ExpressionSyntax)(compilation, "a.vb") Assert.Null(semanticInfo.Type) Assert.True(semanticInfo.ConstantValue.HasValue) Assert.Null(semanticInfo.ConstantValue.Value) End Sub <Fact()> Public Sub ConstFieldInitializer2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C Public Const ClassId As Integer = 23 'BIND:"23" End Class </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of ExpressionSyntax)(compilation, "a.vb") Assert.NotNull(semanticInfo.Type) Assert.Equal(System_Int32, semanticInfo.Type.SpecialType) Assert.Equal(semanticInfo.ConstantValue.Value, 23) Assert.True(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub ConstFieldInitializer3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C Public Const ClassDate As DateTime = #11/04/2008# 'BIND:"#11/04/2008#" End Class </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of ExpressionSyntax)(compilation, "a.vb") Assert.NotNull(semanticInfo.Type) Assert.Equal(System_DateTime, semanticInfo.Type.SpecialType) Assert.True(semanticInfo.ConstantValue.HasValue) Assert.Equal(#11/4/2008#, semanticInfo.ConstantValue.Value) End Sub <Fact()> Public Sub ConstFieldInitializer4() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C Public Const ClassId As Integer = 2 + 2 'BIND:"2 + 2" End Class </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of ExpressionSyntax)(compilation, "a.vb") Assert.NotNull(semanticInfo.Type) Assert.Equal(System_Int32, semanticInfo.Type.SpecialType) Assert.Equal(semanticInfo.ConstantValue.Value, 4) Assert.True(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub ConstFieldInitializer5() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C Public Const A As Integer = 4 Public Const B As Integer = 7 + 2 * A 'BIND:"2 * A" End Class </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of ExpressionSyntax)(compilation, "a.vb") Assert.NotNull(semanticInfo.Type) Assert.Equal(System_Int32, semanticInfo.Type.SpecialType) Assert.Equal(semanticInfo.ConstantValue.Value, 8) Assert.True(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub ConstFieldInitializersMultipleSymbols() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C Const X, Y As Integer = 6 Const Z As Integer = Y End Class </file> </compilation>) Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim node = FindNodeFromText(tree, "X") Dim symbol = DirectCast(model.GetDeclaredSymbol(node), FieldSymbol) Assert.Equal(symbol.Name, "X") Assert.Equal(System_Int32, symbol.Type.SpecialType) Assert.Equal(symbol.ConstantValue, 6) End Sub <Fact()> Public Sub FieldInitializer1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C Public ClassId As Integer = 23 'BIND:"23" End Class </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of ExpressionSyntax)(compilation, "a.vb") Assert.NotNull(semanticInfo.Type) Assert.Equal(System_Int32, semanticInfo.Type.SpecialType) Assert.Equal(semanticInfo.ConstantValue.Value, 23) Assert.True(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub FieldInitializer2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C Public ClassId As Integer = C.goo() 'BIND:"goo" shared Function goo() as Integer return 23 End Function End Class </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of ExpressionSyntax)(compilation, "a.vb") Assert.Null(semanticInfo.Type) Assert.Equal(1, semanticInfo.MemberGroup.Length) Assert.Equal("Function C.goo() As System.Int32", semanticInfo.MemberGroup(0).ToDisplayString(SymbolDisplayFormat.TestFormat)) End Sub <WorkItem(541243, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541243")> <Fact()> Public Sub CollectionInitializerNoMscorlibRef() Dim compilation = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim numbers() As Integer = New Integer() {0, 1, 2, 3, 4} 'BIND:"{0, 1, 2, 3, 4}" End Sub End Module </file> </compilation>, {}) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of ExpressionSyntax)(compilation, "a.vb") Assert.Equal("System.Int32[missing]()", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Array, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32[missing]()", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Array, semanticInfo.ConvertedType.TypeKind) End Sub <Fact()> Public Sub CollectionInitializerWithoutConversion() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Option Strict On Class C Shared Sub M(s as string) Dim s = New String() {s} 'BIND:"{s}" End Sub End Class </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of ExpressionSyntax)(compilation, "a.vb") Assert.Equal("System.String()", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Array, semanticInfo.Type.TypeKind) Assert.Equal("System.String()", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Array, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) End Sub <WorkItem(541422, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541422")> <Fact()> Public Sub CollectionInitializerWithConversion() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Option Strict On Class C Shared Sub M(o As Object) Dim s = New String() {o} 'BIND:"{o}" End Sub End Class </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of ExpressionSyntax)(compilation, "a.vb") Assert.Equal("System.String()", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Array, semanticInfo.Type.TypeKind) Assert.Equal("System.String()", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Array, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) End Sub <Fact()> Public Sub ArrayInitializerMemberWithConversion() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Dim s As String Dim x As Object() = New Object() {s}'BIND:"s" End Sub End Module ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.WideningReference, semanticInfo.ImplicitConversion.Kind) Assert.Equal("s As System.String", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub TwoDArrayInitializerMember() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Module Program Sub Main() Dim s1 As String = "hi" Dim s2 As String = "hello" Dim o1 As Object = Nothing Dim o2 As Object = Nothing Dim arr As Object(,) = New Object(,) {{o1, o2}, {s1, s2}}'BIND:"s2" End Sub End Module ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.WideningReference, semanticInfo.ImplicitConversion.Kind) Assert.Equal("s2 As System.String", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub PartialArrayInitializer() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Module Program Sub Main() Dim s1 As String = "hi" Dim s2 As String = "hello" Dim o1 As Object = Nothing Dim o2 As Object = Nothing Dim arr As Object(,) = New Object(,) {{o1, o2}, {s1, s2}}'BIND:"{s1, s2}" End Sub End Module ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of CollectionInitializerSyntax)(compilation, "a.vb") Assert.Null(semanticInfo.Type) Assert.Null(semanticInfo.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <WorkItem(541270, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541270")> <Fact()> Public Sub GetSemanticInfoOfNothing() Dim compilation = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation> <file name="a.vb"> Module Module1 Sub Main() End Sub End Module </file> </compilation>, {}) Dim semanticModel = compilation.GetSemanticModel(compilation.SyntaxTrees(0)) Assert.Throws(Of ArgumentNullException)(Function() Return semanticModel.GetAliasInfo(Nothing) End Function ) Assert.Throws(Of ArgumentNullException)(Function() Return semanticModel.GetSymbolInfo(DirectCast(Nothing, AttributeSyntax)) End Function ) Assert.Throws(Of ArgumentNullException)(Function() Return semanticModel.GetSymbolInfo(DirectCast(Nothing, ExpressionRangeVariableSyntax)) End Function ) Assert.Throws(Of ArgumentNullException)(Function() Return semanticModel.GetSymbolInfo(DirectCast(Nothing, ExpressionSyntax)) End Function ) Assert.Throws(Of ArgumentNullException)(Function() Return semanticModel.GetSymbolInfo(DirectCast(Nothing, FunctionAggregationSyntax)) End Function ) Assert.Throws(Of ArgumentNullException)(Function() Return semanticModel.GetSymbolInfo(DirectCast(Nothing, OrderingSyntax)) End Function ) Assert.Throws(Of ArgumentNullException)(Function() Return semanticModel.GetSymbolInfo(DirectCast(Nothing, QueryClauseSyntax)) End Function ) Assert.Throws(Of ArgumentNullException)(Function() Return semanticModel.GetTypeInfo(DirectCast(Nothing, AttributeSyntax)) End Function ) Assert.Throws(Of ArgumentNullException)(Function() Return semanticModel.GetTypeInfo(DirectCast(Nothing, ExpressionSyntax)) End Function ) Assert.Throws(Of ArgumentNullException)(Function() Return semanticModel.GetConstantValue(DirectCast(Nothing, ExpressionSyntax)) End Function ) Assert.Throws(Of ArgumentNullException)(Function() Return semanticModel.GetMemberGroup(DirectCast(Nothing, ExpressionSyntax)) End Function ) End Sub <WorkItem(541390, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541390")> <Fact()> Public Sub ErrorLambdaParamInsideFieldInitializer() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module Module1 Dim f1 As Func(Of Integer, Integer) = Function(lambdaParam As Integer) Return lambdaParam + 1 'BIND:"lambdaParam" End Function End Module </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of ExpressionSyntax)(compilation, "a.vb") Assert.NotNull(semanticInfo) Assert.NotNull(semanticInfo.Type) Assert.Equal(System_Int32, semanticInfo.Type.SpecialType) End Sub <Fact()> Public Sub ErrorLambdaParamInsideLocalInitializer() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim f1 As Func(Of Integer, Integer) = Function(lambdaParam As Integer) Return lambdaParam + 1 'BIND:"lambdaParam" End Function End Sub End Module </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of ExpressionSyntax)(compilation, "a.vb") Assert.NotNull(semanticInfo) Assert.NotNull(semanticInfo.Type) Assert.Equal(System_Int32, semanticInfo.Type.SpecialType) End Sub <WorkItem(541390, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541390")> <Fact()> Public Sub LambdaParamInsideFieldInitializer() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Module Module1 Dim f1 As Func(Of Integer, Integer) = Function(lambdaParam) Return lambdaParam + 1 'BIND:"lambdaParam" End Function End Module </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of ExpressionSyntax)(compilation, "a.vb") Assert.NotNull(semanticInfo) Assert.NotNull(semanticInfo.Type) Assert.Equal(System_Int32, semanticInfo.Type.SpecialType) End Sub <Fact()> Public Sub LambdaParamInsideLocalInitializer() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Module Module1 Sub Main() Dim f1 As Func(Of Integer, Integer) = Function(lambdaParam) Return lambdaParam + 1 'BIND:"lambdaParam" End Function End Sub End Module </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of ExpressionSyntax)(compilation, "a.vb") Assert.NotNull(semanticInfo) Assert.NotNull(semanticInfo.Type) Assert.Equal(System_Int32, semanticInfo.Type.SpecialType) End Sub <WorkItem(541418, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541418")> <Fact()> Public Sub BindAttributeInstanceWithoutAttributeSuffix() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ <Assembly: My> 'BIND:"My" Class MyAttribute : Inherits System.Attribute End Class]]> </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of ExpressionSyntax)(compilation, "a.vb") Assert.NotNull(semanticInfo) Assert.NotNull(semanticInfo.Symbol) Assert.Equal("Sub MyAttribute..ctor()", semanticInfo.Symbol.ToDisplayString(SymbolDisplayFormat.TestFormat)) Assert.Equal("MyAttribute", semanticInfo.Type.ToDisplayString(SymbolDisplayFormat.TestFormat)) End Sub <WorkItem(541401, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541401")> <Fact()> Public Sub BindingAttributeParameter() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class MineAttribute Inherits Attribute Public Sub New(p As Short) End Sub End Class <Mine(123)> 'BIND:"123" Class C End Class ]]> </file> </compilation>) ' NOTE: VB doesn't allow same line comments after attribute Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of LiteralExpressionSyntax)(compilation, "a.vb") Assert.NotNull(semanticInfo.Type) Assert.Equal(System_Int32, semanticInfo.Type.SpecialType) Assert.Equal(System_Int16, semanticInfo.ConvertedType.SpecialType) Assert.Equal(semanticInfo.ConstantValue.Value, 123) Assert.True(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub BindAttributeNamespace() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> <![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Namespace n1 Module Program <n1.Program.Test1(1)>'BIND:"n1" Class A End Class <AttributeUsageAttribute(AttributeTargets.All, AllowMultiple:=True)> Class Test1 Inherits Attribute Public Sub New(i As Integer) End Sub End Class End Module End Namespace ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticInfo.Type) Assert.Null(semanticInfo.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("n1", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Namespace, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <WorkItem(541418, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541418")> <Fact()> Public Sub BindingAttributeClassName() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System <System.AttributeUsage(AttributeTargets.All, AllowMultiple:=true)> _ 'BIND:"AttributeUsage" Class ZAttribute Inherits Attribute End Class <ZAttribute()> Class scen1 Shared Sub Main() Dim x = 1 Console.WriteLine(x) End Sub End Class ]]> </file> </compilation>) ' NOTE: VB doesn't allow same line comments after attribute Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.NotNull(semanticInfo.Type) Assert.Equal("System.AttributeUsageAttribute", semanticInfo.Type.ToString()) Assert.False(DirectCast(semanticInfo.Type, TypeSymbol).IsErrorType) End Sub <Fact()> Public Sub TestAttributeFieldName() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Namespace n1 Module Program <Test1(fi:=10)>'BIND:"fi" Class A End Class <AttributeUsageAttribute(AttributeTargets.All, AllowMultiple:=True)> Class Test1 Inherits Attribute Public Sub New(i As Integer) End Sub Public fi As Integer End Class End Module End Namespace]]> </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("n1.Program.Test1.fi As System.Int32", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Field, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub TestAttributePropertyName() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Namespace n1 Module Program Class A <Test1(1, Pi:=2)>'BIND:"Pi" Sub s End Sub End Class <AttributeUsageAttribute(AttributeTargets.All, AllowMultiple:=True)> Class Test1 Inherits Attribute Public Sub New() End Sub Public Sub New(i As Integer) End Sub Public fi As Integer Public Property Pi As Integer End Class End Module End Namespace ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Property n1.Program.Test1.Pi As System.Int32", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Property, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub TestAttributePositionalArgOnParameter() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Namespace n1 Module Program Class A Function f( <Test1("parameter")> x As Integer) As Integer'BIND:""parameter"" Return 0 End Function End Class <AttributeUsageAttribute(AttributeTargets.All, AllowMultiple:=True)> Class Test1 Inherits Attribute Public Sub New(i As String) End Sub End Class End Module End Namespace ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of LiteralExpressionSyntax)(compilation, "a.vb") Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.True(semanticInfo.ConstantValue.HasValue) Assert.Equal("parameter", semanticInfo.ConstantValue.Value) End Sub <Fact()> Public Sub TestAttributeClassNameOnReturnValue() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Namespace n1 Module Program Class A Function f(x As Integer) As <Test1(4)> Integer'BIND:"Test1" Return 0 End Function End Class <AttributeUsageAttribute(AttributeTargets.All, AllowMultiple:=True)> Class Test1 Inherits Attribute Public Sub New(i As Integer) End Sub End Class End Module End Namespace ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("n1.Program.Test1", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("n1.Program.Test1", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Sub n1.Program.Test1..ctor(i As System.Int32)", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(1, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub TestAttributeCannotBindToUnqualifiedClassMember() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Namespace n1 Module Program <Test1(C1)>'BIND:"C1" Class A Public Const C1 As Integer = 99 End Class <AttributeUsageAttribute(AttributeTargets.All, AllowMultiple:=True)> Class Test1 Inherits Attribute Public Sub New(i As Integer) End Sub End Class End Module End Namespace ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("?", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind) Assert.Equal("?", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:="https://github.com/dotnet/roslyn/issues/29531")> Public Sub AttributeSemanticInfo_OverloadResolutionFailure_01() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System <Module: ObsoleteAttribute(GetType())>'BIND:"ObsoleteAttribute" ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("System.ObsoleteAttribute", semanticSummary.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.Type.TypeKind) Assert.Equal("System.ObsoleteAttribute", semanticSummary.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Null(semanticSummary.Symbol) Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticSummary.CandidateReason) Assert.Equal(3, semanticSummary.CandidateSymbols.Length) Dim sortedCandidates = semanticSummary.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString(), StringComparer.Ordinal).ToArray() Assert.Equal("Sub System.ObsoleteAttribute..ctor()", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(0).Kind) Assert.Equal("Sub System.ObsoleteAttribute..ctor(message As System.String)", sortedCandidates(1).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(1).Kind) Assert.Equal("Sub System.ObsoleteAttribute..ctor(message As System.String, [error] As System.Boolean)", sortedCandidates(2).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(2).Kind) Assert.Null(semanticSummary.Alias) Assert.Equal(3, semanticSummary.MemberGroup.Length) Dim sortedMethodGroup = semanticSummary.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString(), StringComparer.Ordinal).ToArray() Assert.Equal("Sub System.ObsoleteAttribute..ctor()", sortedMethodGroup(0).ToTestDisplayString()) Assert.Equal("Sub System.ObsoleteAttribute..ctor(message As System.String)", sortedMethodGroup(1).ToTestDisplayString()) Assert.Equal("Sub System.ObsoleteAttribute..ctor(message As System.String, [error] As System.Boolean)", sortedMethodGroup(2).ToTestDisplayString()) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:="https://github.com/dotnet/roslyn/issues/29531")> Public Sub AttributeSemanticInfo_OverloadResolutionFailure_02() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System <Module: Obsolete(GetType())>'BIND:"Module: Obsolete(GetType())" ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of AttributeSyntax)(compilation, "a.vb") Assert.Equal("System.ObsoleteAttribute", semanticSummary.Type.ToTestDisplayString()) Assert.Equal("System.ObsoleteAttribute", semanticSummary.ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Null(semanticSummary.Symbol) Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticSummary.CandidateReason) Assert.Equal(3, semanticSummary.CandidateSymbols.Length) Dim sortedCandidates = semanticSummary.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString(), StringComparer.Ordinal).ToArray() Assert.Equal("Sub System.ObsoleteAttribute..ctor()", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(0).Kind) Assert.Equal("Sub System.ObsoleteAttribute..ctor(message As System.String)", sortedCandidates(1).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(1).Kind) Assert.Equal("Sub System.ObsoleteAttribute..ctor(message As System.String, [error] As System.Boolean)", sortedCandidates(2).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(2).Kind) Assert.Null(semanticSummary.Alias) Assert.Equal(3, semanticSummary.MemberGroup.Length) Dim sortedMethodGroup = semanticSummary.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString(), StringComparer.Ordinal).ToArray() Assert.Equal("Sub System.ObsoleteAttribute..ctor()", sortedMethodGroup(0).ToTestDisplayString()) Assert.Equal("Sub System.ObsoleteAttribute..ctor(message As System.String)", sortedMethodGroup(1).ToTestDisplayString()) Assert.Equal("Sub System.ObsoleteAttribute..ctor(message As System.String, [error] As System.Boolean)", sortedMethodGroup(2).ToTestDisplayString()) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <WorkItem(541481, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541481")> <Fact()> Public Sub BindingPredefinedCastExpression() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports Microsoft.VisualBasic Module Test Sub Main() Dim exp As Integer = 123 Dim act As String = CStr(exp) 'BIND:"CStr(exp)" End Sub End Module ]]> </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of PredefinedCastExpressionSyntax)(compilation, "a.vb") Assert.NotNull(semanticInfo.Type) Assert.Equal("String", semanticInfo.Type.ToString()) End Sub <WorkItem(541498, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541498")> <Fact()> Public Sub DictionaryAccessExpressionErrorType() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Module Module1 Sub Main() Dim c As Collection Dim b = c!A 'BIND:"c!A" End Sub End Module ]]> </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of MemberAccessExpressionSyntax)(compilation, "a.vb") Assert.NotNull(semanticInfo) Assert.Null(semanticInfo.Symbol) Assert.Equal(semanticInfo.Type.TypeKind, TypeKind.Error) End Sub <Fact()> Public Sub DictionaryAccessExpressionErrorExpr() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Class A Private Shared F As System.Collections.Generic.Dictionary(Of String, Integer) End Class Class B Shared Sub M() Dim o = A.F!x 'BIND:"A.F!x" End Sub End Class ]]> </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of MemberAccessExpressionSyntax)(compilation, "a.vb") Assert.NotNull(semanticInfo) CompilationUtils.CheckSymbol(semanticInfo.Symbol, "Property Dictionary(Of String, Integer).Item(key As String) As Integer") Assert.Equal(semanticInfo.Type.SpecialType, System_Int32) End Sub <Fact()> Public Sub DictionaryAccessExpressionNoType() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Class C Shared Sub M() Dim o = (AddressOf M)!x 'BIND:"(AddressOf M)!x" End Sub End Class ]]> </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of MemberAccessExpressionSyntax)(compilation, "a.vb") Assert.NotNull(semanticInfo) Assert.Null(semanticInfo.Symbol) Assert.Equal(semanticInfo.Type.TypeKind, TypeKind.Error) End Sub <Fact()> Public Sub DictionaryAccessExpression() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Class A Friend Shared F As System.Collections.Generic.Dictionary(Of String, Integer) End Class Class B Shared Sub M() Dim o = A.F!x 'BIND:"A.F!x" End Sub End Class ]]> </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of MemberAccessExpressionSyntax)(compilation, "a.vb") Assert.NotNull(semanticInfo) CompilationUtils.CheckSymbol(semanticInfo.Symbol, "Property Dictionary(Of String, Integer).Item(key As String) As Integer") Assert.Equal(semanticInfo.Type.SpecialType, System_Int32) End Sub <WorkItem(541384, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541384")> <Fact()> Public Sub DictionaryAccessKey() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Class C Shared Function M(d As System.Collections.Generic.Dictionary(Of String, Integer)) As Integer Return d!key 'BIND:"key" End Function End Class ]]> </file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.NotNull(semanticInfo) Assert.NotNull(semanticInfo.Type) Assert.Equal(semanticInfo.Type.SpecialType, System_String) Assert.Equal(semanticInfo.ConstantValue.Value, "key") Assert.Null(semanticInfo.Symbol) End Sub <WorkItem(541518, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541518")> <Fact()> Public Sub AssignAddressOfPropertyToDelegate() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Module Module1 Delegate Function del2() As Integer Property p() As Integer Get Return 10 End Get Set(ByVal Value As Integer) End Set End Property Sub Main() Dim var2 = New del2(AddressOf p)'BIND:"p" End Sub End Module ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticInfo.Type) Assert.Null(semanticInfo.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason) Assert.Equal(1, semanticInfo.CandidateSymbols.Length) Dim sortedCandidates = semanticInfo.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Property Module1.p As System.Int32", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.Property, sortedCandidates(0).Kind) Assert.Equal(1, semanticInfo.MemberGroup.Length) Dim sortedMethodGroup = semanticInfo.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Property Module1.p As System.Int32", sortedMethodGroup(0).ToTestDisplayString()) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub FieldAccess() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Class B Public f1 As Integer End Class Class M Public Sub Main() Dim bInstance As B bInstance = New B() Console.WriteLine(bInstance.f1)'BIND:"f1" End Sub End Class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("B.f1 As System.Int32", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Field, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub LocalVariable() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Class B Public f1 As Integer End Class Class M Public Sub Main() Dim bInstance As B bInstance = New B() Console.WriteLine(bInstance.f1)'BIND:"bInstance" End Sub End Class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("B", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("B", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("bInstance As B", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub NotFunctionReturnLocal() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Class M Public Function Goo() As Integer Goo()'BIND:"Goo" End Function End Class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticInfo.Type) Assert.Null(semanticInfo.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Function M.Goo() As System.Int32", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(1, semanticInfo.MemberGroup.Length) Dim sortedMethodGroup = semanticInfo.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Function M.Goo() As System.Int32", sortedMethodGroup(0).ToTestDisplayString()) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub FunctionReturnLocal() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Class M Public Function Goo() As Integer Goo = 4'BIND:"Goo" End Function End Class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Goo As System.Int32", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub MeSemanticInfo() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Class M Public x As Integer Public Function Goo() As Integer Me.x = 5'BIND:"Me" End Function End Class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of MeExpressionSyntax)(compilation, "a.vb") Assert.Equal("M", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("M", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Me As M", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Parameter, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.True(DirectCast(semanticInfo.Symbol, ParameterSymbol).IsMe) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub LocalVariableInConstructor() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Class B Public f1 As Integer End Class Class M Public Sub New() Dim bInstance As B bInstance = New B() Console.WriteLine(bInstance.f1)'BIND:"bInstance" End Sub End Class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("B", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("B", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("bInstance As B", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub LocalVariableInSharedConstructor() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Class B Public f1 As Integer End Class Class M Shared Sub New() Dim bInstance As B bInstance = New B() Console.WriteLine(bInstance.f1)'BIND:"bInstance" End Sub End Class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("B", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("B", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("bInstance As B", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub LocalVariableInModuleConstructor() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Class B Public f1 As Integer End Class Module M Sub New() Dim bInstance As B bInstance = New B() Console.WriteLine(bInstance.f1)'BIND:"bInstance" End Sub End Module ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("B", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("B", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("bInstance As B", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub ConstructorConstructorCall_Structure_Me_New_WithParameters() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Structure Program Public Sub New(i As Integer) End Sub Public Sub New(s As String) Me.New(1)'BIND:"Me.New(1)" End Sub End Structure ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of InvocationExpressionSyntax)(compilation, "a.vb") Assert.Equal("System.Void", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Void", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Sub Program..ctor(i As System.Int32)", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim method = DirectCast(semanticInfo.Symbol, MethodSymbol) Assert.Equal(MethodKind.Constructor, method.MethodKind) Assert.False(method.IsShared) Assert.False(method.IsImplicitlyDeclared) End Sub <Fact()> Public Sub ConstructorConstructorCall_Class_Me_New_WithParameters() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Class Program Public Sub New(i As Integer) End Sub Public Sub New(s As String) Me.New(1)'BIND:"Me.New(1)" End Sub End Class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of InvocationExpressionSyntax)(compilation, "a.vb") Assert.Equal("System.Void", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Void", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Sub Program..ctor(i As System.Int32)", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim method = DirectCast(semanticInfo.Symbol, MethodSymbol) Assert.Equal(MethodKind.Constructor, method.MethodKind) Assert.False(method.IsShared) Assert.False(method.IsImplicitlyDeclared) End Sub <Fact()> Public Sub ConstructorConstructorCall_Structure_Me_New_NoParameters() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Structure Program Public Sub New(s As String) Me.New()'BIND:"Me.New()" End Sub End Structure ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of InvocationExpressionSyntax)(compilation, "a.vb") Assert.Equal("System.Void", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Void", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Sub Program..ctor()", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim method = DirectCast(semanticInfo.Symbol, MethodSymbol) Assert.Equal(MethodKind.Constructor, method.MethodKind) Assert.False(method.IsShared) Assert.True(method.IsImplicitlyDeclared) End Sub <Fact()> Public Sub ConstructorConstructorCall_Class_Me_New_NoParameters() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Class Program Public Sub New() End Sub Public Sub New(s As String) Me.New()'BIND:"Me.New()" End Sub End Class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of InvocationExpressionSyntax)(compilation, "a.vb") Assert.Equal("System.Void", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Void", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Sub Program..ctor()", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim method = DirectCast(semanticInfo.Symbol, MethodSymbol) Assert.Equal(MethodKind.Constructor, method.MethodKind) Assert.False(method.IsShared) Assert.False(method.IsImplicitlyDeclared) End Sub <Fact()> Public Sub Invocation() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class C Private Sub M() Dim x As String = F()'BIND:"F()" End Sub Private Function F() As String Return "Hello" End Function End Class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of InvocationExpressionSyntax)(compilation, "a.vb") Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Function C.F() As System.String", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub MethodGroup() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class C Private Sub M() Dim x As String = F()'BIND:"F" End Sub Private Function F() As String Return "Hello" End Function Private Function F(arg As String) As String Return "Goodbye" End Function End Class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticInfo.Type) Assert.Null(semanticInfo.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Function C.F() As System.String", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(2, semanticInfo.MemberGroup.Length) Dim sortedMethodGroup = semanticInfo.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Function C.F() As System.String", sortedMethodGroup(0).ToTestDisplayString()) Assert.Equal("Function C.F(arg As System.String) As System.String", sortedMethodGroup(1).ToTestDisplayString()) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub InvocationNoMatchingOverloads() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class C Private Sub M() Dim x As String = F()'BIND:"F()" End Sub Private Function F(arg As Integer) As String Return "Hello" End Function Private Function F(arg As String) As String Return "Goodbye" End Function End Class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of InvocationExpressionSyntax)(compilation, "a.vb") Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason) Assert.Equal(2, semanticInfo.CandidateSymbols.Length) Dim sortedCandidates = semanticInfo.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Function C.F(arg As System.Int32) As System.String", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(0).Kind) Assert.Equal("Function C.F(arg As System.String) As System.String", sortedCandidates(1).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(1).Kind) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <WorkItem(540580, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540580")> <WorkItem(541567, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541567")> <ConditionalFact(GetType(WindowsOnly), Reason:="https://github.com/dotnet/roslyn/issues/29531")> Public Sub NoMatchingOverloads2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class C Private Sub M() Dim x As String = F(6, 3)'BIND:"F(6, 3)" End Sub Private Function F() As String Return "Hello" End Function End Class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of InvocationExpressionSyntax)(compilation, "a.vb") Assert.Equal("System.Char", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason) Assert.Equal(1, semanticInfo.CandidateSymbols.Length) Dim sortedCandidates = semanticInfo.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("ReadOnly Property System.String.Chars(index As System.Int32) As System.Char", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.Property, sortedCandidates(0).Kind) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub NoMatchingOverloads3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class C Private Sub M() Dim x As String = F.Chars(6, 3)'BIND:"F.Chars(6, 3)" End Sub Private Function F() As String Return "Hello" End Function End Class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of InvocationExpressionSyntax)(compilation, "a.vb") Assert.Equal("System.Char", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason) Assert.Equal(1, semanticInfo.CandidateSymbols.Length) Dim sortedCandidates = semanticInfo.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("ReadOnly Property System.String.Chars(index As System.Int32) As System.Char", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.Property, sortedCandidates(0).Kind) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <WorkItem(541567, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541567")> <ConditionalFact(GetType(WindowsOnly), Reason:="https://github.com/dotnet/roslyn/issues/29531")> Public Sub NoMatchingOverloads4() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Module Program Sub Main(args As String()) Dim a As New C1() Dim b As Integer b = a(5, 6, 7)'BIND:"a(5, 6, 7)" b = a.P1(5, 6, 7) End Sub End Module Class C1 Public Default Property P1(x As Integer) As String Get Return "hello" End Get Set(ByVal value As String) End Set End Property Public Default Property P1(x As Integer, y As Integer) As String Get Return "hi" End Get Set(ByVal value As String) End Set End Property End Class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of InvocationExpressionSyntax)(compilation, "a.vb") Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.NarrowingString, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason) Assert.Equal(2, semanticInfo.CandidateSymbols.Length) Dim sortedCandidates = semanticInfo.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString(), StringComparer.Ordinal).ToArray() Assert.Equal("Property C1.P1(x As System.Int32) As System.String", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.Property, sortedCandidates(0).Kind) Assert.Equal("Property C1.P1(x As System.Int32, y As System.Int32) As System.String", sortedCandidates(1).ToTestDisplayString()) Assert.Equal(SymbolKind.Property, sortedCandidates(1).Kind) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <WorkItem(540580, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540580")> <Fact()> Public Sub PropertyPassedByRef() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Class C Private Sub M() S(P)'BIND:"P" End Sub Public Property P As String Private Sub S(ByRef a As String) End Sub End Class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Property C.P As System.String", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Property, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub InvocationWithNoMatchingOverloadsAndNonMatchingReturnTypes() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class C Private Sub M() Dim x As String = F()'BIND:"F()" End Sub Private Function F(arg As Integer) As String Return "Hello" End Function Private Function F(arg As String) As Integer Return "Goodbye" End Function End Class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of InvocationExpressionSyntax)(compilation, "a.vb") Assert.Equal("?", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind) Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.DelegateRelaxationLevelNone, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason) Assert.Equal(2, semanticInfo.CandidateSymbols.Length) Dim sortedCandidates = semanticInfo.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Function C.F(arg As System.Int32) As System.String", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(0).Kind) Assert.Equal("Function C.F(arg As System.String) As System.Int32", sortedCandidates(1).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(1).Kind) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub IncompleteInvocation() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class C Private Sub M() Dim x As String = F(:'BIND:"F(" End Sub Private Function F(arg As Integer) As String Return "Hello" End Function Private Function F(arg As String) As String Return "Goodbye" End Function End Class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of InvocationExpressionSyntax)(compilation, "a.vb") Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason) Assert.Equal(2, semanticInfo.CandidateSymbols.Length) Dim sortedCandidates = semanticInfo.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Function C.F(arg As System.Int32) As System.String", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(0).Kind) Assert.Equal("Function C.F(arg As System.String) As System.String", sortedCandidates(1).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(1).Kind) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub TypeNameInsideMethod() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class C Public Sub Main() Dim cInstance As C'BIND:"C" End Sub End Class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("C", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("C", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("C", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub TypeNameInsideMethodWithConflictingLocal() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class C Public Sub Main() Dim cInstance As C'BIND:"C" Dim C As String End Sub End Class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("C", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("C", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("C", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub TypeNameOutsideMethod() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class C Public Sub Main(ByVal arg As D)'BIND:"D" End Sub End Class Class D End Class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("D", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("D", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("D", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub NamespaceName() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class C Private Sub M() Dim x As System.String = F()'BIND:"System" End Sub Private Function F() As String Return "Hello" End Function End Class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticInfo.Type) Assert.Null(semanticInfo.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("System", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Namespace, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub NamespaceNameInDeclaration() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class C Private Sub M(arg As System.String)'BIND:"System" End Sub End Class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticInfo.Type) Assert.Null(semanticInfo.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("System", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Namespace, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub NamespaceNameWithConflictingField() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class C Private Sub M() Dim x As System.String = F()'BIND:"System" End Sub Private Function F() As String Return "Hello" End Function Public System As Integer End Class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticInfo.Type) Assert.Null(semanticInfo.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("System", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Namespace, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub MissingNamespaceName() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class C Private Sub M() Dim x As Baz.Goo.String'BIND:"Goo" End Sub Private Function F() As String Return "Hello" End Function End Class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("Baz.Goo", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind) Assert.Equal("Baz.Goo", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub RightSideOfQualifiedName() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Public Class C Sub M() Dim x As N.D = Nothing'BIND:"D" End Sub End Class Public Class D End Class Namespace N Public Class D End Class End Namespace ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("N.D", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("N.D", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("N.D", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub RHSInDeclaration() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class C Private Sub M(arg As System.String)'BIND:"String" End Sub End Class Class [String] End Class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("System.String", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub ImportsRHS() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports NS1.NS2'BIND:"NS2" ]]></file> <file name="b.vb"><![CDATA[ Namespace NS1 Namespace NS2 Class X End Class End Namespace End Namespace ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticInfo.Type) Assert.Null(semanticInfo.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("NS1.NS2", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Namespace, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub ImportsLHS() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports NS1.NS2'BIND:"NS1" ]]></file> <file name="b.vb"><![CDATA[ Namespace NS1 Namespace NS2 Class X End Class End Namespace End Namespace ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticInfo.Type) Assert.Null(semanticInfo.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("NS1", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Namespace, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub AmbiguousType() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Public Class C Sub M() Dim x As AAA'BIND:"AAA" End Sub End Class ]]></file> <file name="b.vb"><![CDATA[ Module Q Class AAA End Class End Module Module R Class AAA End Class End Module ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("AAA", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind) Assert.Equal("AAA", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.Ambiguous, semanticInfo.CandidateReason) Assert.Equal(2, semanticInfo.CandidateSymbols.Length) Dim sortedCandidates = semanticInfo.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Q.AAA", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, sortedCandidates(0).Kind) Assert.Equal("R.AAA", sortedCandidates(1).ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, sortedCandidates(1).Kind) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub AmbiguousField() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Public Class C Sub M() Dim x As String x = elvis'BIND:"elvis" End Sub End Class ]]></file> <file name="b.vb"><![CDATA[ Module Q Public elvis As Integer End Module Module R Public elvis As String End Module ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("?", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind) Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(Nothing, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.Ambiguous, semanticInfo.CandidateReason) Assert.Equal(2, semanticInfo.CandidateSymbols.Length) Dim sortedCandidates = semanticInfo.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Q.elvis As System.Int32", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.Field, sortedCandidates(0).Kind) Assert.Equal("R.elvis As System.String", sortedCandidates(1).ToTestDisplayString()) Assert.Equal(SymbolKind.Field, sortedCandidates(1).Kind) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub InNamespaceDeclaration() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Namespace AAA.BBB'BIND:"AAA" Class AAA End Class End Namespace ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticInfo.Type) Assert.Null(semanticInfo.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("AAA", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Namespace, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub LocalInitializerWithConversion() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Public Class C Sub M() Dim x As Long = 5, y As Double = 17'BIND:"5" End Sub End Class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of LiteralExpressionSyntax)(compilation, "a.vb") Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int64", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.WideningNumeric, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.True(semanticInfo.ConstantValue.HasValue) Assert.Equal(5, semanticInfo.ConstantValue.Value) End Sub <Fact()> Public Sub LocalInitializerWithConversion2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Public Class C Sub M() Dim x As Long = 5, y As Double = 17'BIND:"17" End Sub End Class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of LiteralExpressionSyntax)(compilation, "a.vb") Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Double", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.WideningNumeric, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.True(semanticInfo.ConstantValue.HasValue) Assert.Equal(17, semanticInfo.ConstantValue.Value) End Sub <Fact()> Public Sub ArgumentWithParentConversion() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Public Class C Sub M() Dim x As Integer = 5 Dim y As Long = func(x)'BIND:"x" End Sub Function func(x As Long) As Long Return x End Function End Class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int64", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.WideningNumeric, semanticInfo.ImplicitConversion.Kind) Assert.Equal("x As System.Int32", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub LocalWithConversionInParent() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Public Class C Sub M() Dim x As Integer = 5 Dim y As Long = x'BIND:"x" End Sub End Class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int64", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.WideningNumeric, semanticInfo.ImplicitConversion.Kind) Assert.Equal("x As System.Int32", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <WorkItem(539179, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539179")> <Fact()> Public Sub LocalWithConversionInParent2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Public Class C Sub M() Dim x As UShort = 99 + 1 Dim y As ULong y = x'BIND:"x" End Sub End Class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("System.UInt16", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.UInt64", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.WideningNumeric, semanticInfo.ImplicitConversion.Kind) Assert.Equal("x As System.UInt16", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub FieldInitializer() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class C Private F = 1 + G()'BIND:"1 + G()" Shared Function G() As Integer Return 1 End Function End Class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of BinaryExpressionSyntax)(compilation, "a.vb") Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.WideningValue, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Function System.Int32.op_Addition(left As System.Int32, right As System.Int32) As System.Int32", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub AutoPropertyInitializers() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class C Private Const F As Integer = 1 Property P = 1 + F'BIND:"1 + F" End Class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of BinaryExpressionSyntax)(compilation, "a.vb") Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.WideningValue, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Function System.Int32.op_Addition(left As System.Int32, right As System.Int32) As System.Int32", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.True(semanticInfo.ConstantValue.HasValue) Assert.Equal(2, semanticInfo.ConstantValue.Value) End Sub <WorkItem(541562, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541562")> <Fact()> Public Sub ObjectCreationInAsNew() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Class C1 Dim Scen2 As New C2() 'BIND:"New C2()" Class C2 Class C3 End Class End Class End Class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of ObjectCreationExpressionSyntax)(compilation, "a.vb") Assert.NotNull(semanticInfo.Type) Assert.Equal("C1.C2", semanticInfo.Type.ToString()) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.False(semanticInfo.ConstantValue.HasValue) CompilationUtils.AssertNoErrors(compilation) End Sub <WorkItem(541563, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541563")> <Fact()> Public Sub NewDelegateCreation() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Module Test Delegate Sub DSub() Sub DMethod() End Sub Sub Main() Dim dd As DSub = New DSub(AddressOf DMethod) 'BIND:"New DSub(AddressOf DMethod)" End Sub End Module ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of ObjectCreationExpressionSyntax)(compilation, "a.vb") Assert.NotNull(semanticInfo.Type) Assert.Equal("Test.DSub", semanticInfo.Type.ToString()) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.False(semanticInfo.ConstantValue.HasValue) CompilationUtils.AssertNoErrors(compilation) End Sub <WorkItem(541581, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541581")> <Fact()> Public Sub ImplicitConversionTestFieldInit() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Module Module1 Dim x1 As Long = 44 'BIND:"44" Sub Main(ByVal args As String()) End Sub End Module ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of LiteralExpressionSyntax)(compilation, "a.vb") Assert.Equal(System_Int32, semanticInfo.Type.SpecialType) Assert.True(semanticInfo.ConstantValue.HasValue) Assert.Equal(44, semanticInfo.ConstantValue.Value) Assert.True(semanticInfo.ImplicitConversion.IsWidening) Assert.Equal(ConversionKind.WideningNumeric, semanticInfo.ImplicitConversion.Kind) Assert.Equal(System_Int64, semanticInfo.ConvertedType.SpecialType) End Sub <Fact()> Public Sub IdentityCIntConversion() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Module Program Sub Main(args As String()) Dim x As Integer = 7 Dim y As Integer y = CInt(x)'BIND:"CInt(x)" End Sub End Module ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of PredefinedCastExpressionSyntax)(compilation, "a.vb") Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <WorkItem(528541, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528541")> <Fact()> Public Sub ImplicitConversionTestLongNumericToInteger() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Module Program Sub Main(args As String()) Dim x1 As Integer = 45L 'BIND:"45L" End Sub End Module ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of LiteralExpressionSyntax)(compilation, "a.vb") Assert.Equal(System_Int64, semanticInfo.Type.SpecialType) Assert.True(semanticInfo.ConstantValue.HasValue) Assert.Equal(45L, semanticInfo.ConstantValue.Value) Assert.Equal(System_Int32, semanticInfo.ConvertedType.SpecialType) ' Perhaps surprisingly, this is a widening conversion. ' Section 8.8: Widening conversions: ' From a constant expression of type ULong, Long, UInteger, Integer, UShort, Short, Byte, or SByte ' to a narrower type, provided the value of the constant expression is within the range of the destination type. Assert.True(semanticInfo.ImplicitConversion.IsNumeric) Assert.False(semanticInfo.ImplicitConversion.IsNarrowing) Assert.True(semanticInfo.ImplicitConversion.IsWidening) Assert.True((semanticInfo.ImplicitConversion.Kind And ConversionKind.InvolvesNarrowingFromNumericConstant) <> 0, "includes bit InvolvesNarrowingFromNumericConstant") End Sub <WorkItem(541596, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541596")> <Fact()> Public Sub ImplicitConversionExprReturnedByLambda() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Module Program Dim x1 As Func(Of Long) = Function() 45 'BIND:"45" End Module ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of LiteralExpressionSyntax)(compilation, "a.vb") Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int64", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.WideningNumeric, semanticInfo.ImplicitConversion.Kind) Assert.False(semanticInfo.ImplicitConversion.IsIdentity) Assert.False(semanticInfo.ImplicitConversion.IsNarrowing) Assert.True(semanticInfo.ImplicitConversion.IsNumeric) Assert.True(semanticInfo.ImplicitConversion.IsWidening) Assert.True(semanticInfo.ConstantValue.HasValue) Assert.Equal(45, semanticInfo.ConstantValue.Value) End Sub <WorkItem(541608, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541608")> <Fact()> Public Sub IncompleteAttributeOnMethod() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class B <A( Sub Main() 'BIND:"Main" End Sub End Class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.NotNull(semanticInfo) Assert.Equal(SymbolKind.ErrorType, semanticInfo.Type.Kind) End Sub <WorkItem(541625, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541625")> <Fact()> Public Sub ImplicitConvExtensionMethodReceiver() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndReferences( <compilation> <file name="a.vb"><![CDATA[ Imports System.Runtime.CompilerServices Module StringExtensions <Extension()> Public Sub Print(ByVal aString As Object) End Sub End Module Module Program Sub Main(args As String()) Dim example As String = "Hello" example.Print()'BIND:"example" End Sub End Module ]]></file> </compilation>, {TestMetadata.Net40.SystemCore}) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.WideningReference, semanticInfo.ImplicitConversion.Kind) Assert.True(semanticInfo.ImplicitConversion.IsReference) Assert.True(semanticInfo.ImplicitConversion.IsWidening) Assert.Equal("example As System.String", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind) End Sub <Fact()> Public Sub NamedArgument1() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Public Class Class1 Public Sub f(a As Integer) End Sub Public Sub f(b As Integer, a As String) End Sub End Class Public Module M1 Sub goo() Dim x As New Class1 x.f(4, a:="hello")'BIND:"a" End Sub End Module ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticInfo.Type) Assert.Null(semanticInfo.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("a As System.String", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Parameter, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub NamedArgument2() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Public Class Class1 Public Sub f(a As Integer) End Sub Public Sub f(b As Integer, a As String) End Sub Public Sub f(q As Integer, b As String, c As Integer) End Sub Public Sub f(q As Integer, b As String, c As Guid) End Sub End Class Public Module M1 Sub goo() Dim x As New Class1 x.f(4, "hithere", b:="hello")'BIND:"b" End Sub End Module ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticInfo.Type) Assert.Null(semanticInfo.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason) Assert.Equal(2, semanticInfo.CandidateSymbols.Length) Dim sortedCandidates = semanticInfo.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString() & s.ContainingSymbol.ToTestDisplayString()).ToArray() Assert.Equal("b As System.String", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.Parameter, sortedCandidates(0).Kind) Assert.Equal("Sub Class1.f(q As System.Int32, b As System.String, c As System.Guid)", sortedCandidates(0).ContainingSymbol.ToTestDisplayString()) Assert.Equal("b As System.String", sortedCandidates(1).ToTestDisplayString()) Assert.Equal(SymbolKind.Parameter, sortedCandidates(1).Kind) Assert.Equal("Sub Class1.f(q As System.Int32, b As System.String, c As System.Int32)", sortedCandidates(1).ContainingSymbol.ToTestDisplayString()) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub NamedArgument3() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Public Class Class1 Public Sub f(a As Integer) End Sub Public Sub f(b As Integer, a As String) End Sub Public Sub f(q As Integer, b As String, c As Integer) End Sub Public Sub f(q As Integer, b As String, c As Guid) End Sub End Class Public Module M1 Sub goo() Dim x As New Class1 x.f(4, "hithere", zappa:="hello")'BIND:"zappa" End Sub End Module ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticInfo.Type) Assert.Null(semanticInfo.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub NamedArgumentInOnProperty() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Public Class Class1 Public ReadOnly Property f(a As Integer) As Integer Get Return 1 End Get End Property Public ReadOnly Property f(b As Integer, a As String) Get Return 1 End Get End Property Public ReadOnly Property f(q As Integer, b As String, c As Integer) Get Return 1 End Get End Property Public ReadOnly Property f(q As Integer, b As String, c As Guid) Get Return 1 End Get End Property End Class Public Module M1 Sub goo() Dim x As New Class1 Dim y As Integer = x.f(4, c:=12, b:="hi") 'BIND:"c"'BIND:"c" End Sub End Module ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticInfo.Type) Assert.Null(semanticInfo.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("c As System.Int32", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Parameter, semanticInfo.Symbol.Kind) Assert.Equal("ReadOnly Property Class1.f(q As System.Int32, b As System.String, c As System.Int32) As System.Object", semanticInfo.Symbol.ContainingSymbol.ToTestDisplayString()) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <WorkItem(541412, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541412")> <Fact()> Public Sub TestGetSemanticInfoFromAttributeSyntax_Error_MissingSystemImport() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class AAttribute Inherits Attribute Public Sub New() End Sub End Class Class B <A()> 'BIND:"A()" Sub S() End Sub End Class ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of AttributeSyntax)(compilation, "a.vb") Assert.Equal("AAttribute", semanticSummary.Type.ToTestDisplayString()) Assert.Equal("AAttribute", semanticSummary.ConvertedType.ToTestDisplayString()) Assert.Null(semanticSummary.Symbol) Assert.Equal(CandidateReason.NotAnAttributeType, semanticSummary.CandidateReason) Assert.Equal(1, semanticSummary.CandidateSymbols.Length) Dim sortedCandidates = semanticSummary.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString() & s.ContainingSymbol.ToTestDisplayString()).ToArray() Assert.Equal("Sub AAttribute..ctor()", sortedCandidates(0).ToTestDisplayString()) Assert.Null(semanticSummary.Alias) Assert.Equal(1, semanticSummary.MemberGroup.Length) Dim sortedMethodGroup = semanticSummary.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub AAttribute..ctor()", sortedMethodGroup(0).ToTestDisplayString()) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact()> Public Sub TestGetSemanticInfoFromAttributeSyntax_Error_MustInheritAttributeClass() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System MustInherit Class AAttribute Inherits Attribute Public Sub New() End Sub ' Inaccessible constructors shouldn't appear in semantic info method group. Private Sub New(x as Integer) End Sub End Class Class B <A()>'BIND:"A()" Sub S() End Sub End Class ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of AttributeSyntax)(compilation, "a.vb") Assert.Equal("AAttribute", semanticSummary.Type.ToTestDisplayString()) Assert.Equal("AAttribute", semanticSummary.ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Null(semanticSummary.Symbol) Assert.Equal(CandidateReason.NotAnAttributeType, semanticSummary.CandidateReason) Assert.Equal(1, semanticSummary.CandidateSymbols.Length) Dim sortedCandidates = semanticSummary.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub AAttribute..ctor()", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(0).Kind) Assert.Null(semanticSummary.Alias) Assert.Equal(1, semanticSummary.MemberGroup.Length) Dim sortedMethodGroup = semanticSummary.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub AAttribute..ctor()", sortedMethodGroup(0).ToTestDisplayString()) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact()> Public Sub TestGetSemanticInfoFromIdentifierSyntax_Error_MustInheritAttributeClass() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System MustInherit Class AAttribute Inherits Attribute Public Sub New() End Sub End Class Class B <A()>'BIND:"A" Sub S() End Sub End Class ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("AAttribute", semanticSummary.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.Type.TypeKind) Assert.Equal("AAttribute", semanticSummary.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Null(semanticSummary.Symbol) Assert.Equal(CandidateReason.NotAnAttributeType, semanticSummary.CandidateReason) Assert.Equal(1, semanticSummary.CandidateSymbols.Length) Dim sortedCandidates = semanticSummary.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub AAttribute..ctor()", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(0).Kind) Assert.Null(semanticSummary.Alias) Assert.Equal(1, semanticSummary.MemberGroup.Length) Dim sortedMethodGroup = semanticSummary.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub AAttribute..ctor()", sortedMethodGroup(0).ToTestDisplayString()) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact()> Public Sub TestGetSemanticInfoFromAttributeSyntax_Error_GenericAttributeClass() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Class AAttribute(Of T) Public Sub New() End Sub End Class Class B <AAttribute()>'BIND:"AAttribute()" Sub S() End Sub End Class ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of AttributeSyntax)(compilation, "a.vb") Assert.Equal("AAttribute(Of T)", semanticSummary.Type.ToTestDisplayString()) Assert.Equal("AAttribute(Of T)", semanticSummary.ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Null(semanticSummary.Symbol) Assert.Equal(CandidateReason.WrongArity, semanticSummary.CandidateReason) Assert.Equal(1, semanticSummary.CandidateSymbols.Length) Dim sortedCandidates = semanticSummary.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub AAttribute(Of T)..ctor()", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(0).Kind) Assert.Null(semanticSummary.Alias) Assert.Equal(1, semanticSummary.MemberGroup.Length) Dim sortedMethodGroup = semanticSummary.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub AAttribute(Of T)..ctor()", sortedMethodGroup(0).ToTestDisplayString()) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <WorkItem(539822, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539822")> <Fact()> Public Sub UseTypeAsVariable() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Module Program Sub Main(args As String()) [String] = "hello"'BIND:"[String]" End Sub End Module ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.NotAValue, semanticInfo.CandidateReason) Assert.Equal(1, semanticInfo.CandidateSymbols.Length) Dim sortedCandidates = semanticInfo.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("System.String", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, sortedCandidates(0).Kind) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub ForEachWithOneDimensionalArray() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports System Class C1 Public Shared Sub Main() Dim arr As Integer() = New Integer(1) {} arr(0) = 23 arr(1) = 42 For Each element as Integer In arr 'BIND:"For Each element as Integer In arr" Console.WriteLine(element) Next End Sub End Class ]]></file> </compilation>) Dim getEnumerator = DirectCast(DirectCast(compilation.GetSpecialType(System_Array), TypeSymbol).GetMember("GetEnumerator"), MethodSymbol) Dim moveNext = DirectCast(compilation.GetSpecialType(System_Object).ContainingAssembly.GetSpecialTypeMember(SpecialMember.System_Collections_IEnumerator__MoveNext), MethodSymbol) Dim current = DirectCast(compilation.GetSpecialType(System_Object).ContainingAssembly.GetSpecialTypeMember(SpecialMember.System_Collections_IEnumerator__Current), PropertySymbol) Dim dispose = DirectCast(compilation.GetSpecialType(System_Object).ContainingAssembly.GetSpecialTypeMember(SpecialMember.System_IDisposable__Dispose), MethodSymbol) For Each useInterface In {True, False} For Each useBlock In {True, False} Dim semanticInfoEx As ForEachStatementInfo If useInterface Then semanticInfoEx = DirectCast(GetBlockOrStatementInfoForTest(Of ForEachStatementSyntax, SemanticModel)(compilation, "a.vb", useParent:=useBlock), ForEachStatementInfo) Else semanticInfoEx = DirectCast(GetBlockOrStatementInfoForTest(Of ForEachStatementSyntax, VBSemanticModel)(compilation, "a.vb", useParent:=useBlock), ForEachStatementInfo) End If Assert.Equal(getEnumerator, semanticInfoEx.GetEnumeratorMethod) Assert.Equal(moveNext, semanticInfoEx.MoveNextMethod) Assert.Equal(current, semanticInfoEx.CurrentProperty) Assert.Equal(dispose, semanticInfoEx.DisposeMethod) Next Next End Sub <Fact()> Public Sub ForEachWithMultiDimensionalArray() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports System Class C1 Public Shared Sub Main() Dim arr(1,1) As Integer arr(0,0) = 1 arr(0,1) = 2 arr(1,0) = 3 arr(1,1) = 4 For Each element as Integer In arr 'BIND:"For Each element as Integer In arr" Console.WriteLine(element) Next End Sub End Class ]]></file> </compilation>) Dim getEnumerator = DirectCast(DirectCast(compilation.GetSpecialType(System_Array), TypeSymbol).GetMember("GetEnumerator"), MethodSymbol) Dim moveNext = DirectCast(compilation.GetSpecialType(System_Object).ContainingAssembly.GetSpecialTypeMember(SpecialMember.System_Collections_IEnumerator__MoveNext), MethodSymbol) Dim current = DirectCast(compilation.GetSpecialType(System_Object).ContainingAssembly.GetSpecialTypeMember(SpecialMember.System_Collections_IEnumerator__Current), PropertySymbol) Dim dispose = DirectCast(compilation.GetSpecialType(System_Object).ContainingAssembly.GetSpecialTypeMember(SpecialMember.System_IDisposable__Dispose), MethodSymbol) For Each useInterface In {True, False} For Each useBlock In {True, False} Dim semanticInfoEx As ForEachStatementInfo If useInterface Then semanticInfoEx = DirectCast(GetBlockOrStatementInfoForTest(Of ForEachStatementSyntax, SemanticModel)(compilation, "a.vb", useParent:=useBlock), ForEachStatementInfo) Else semanticInfoEx = DirectCast(GetBlockOrStatementInfoForTest(Of ForEachStatementSyntax, VBSemanticModel)(compilation, "a.vb", useParent:=useBlock), ForEachStatementInfo) End If Assert.Equal(getEnumerator, semanticInfoEx.GetEnumeratorMethod) Assert.Equal(moveNext, semanticInfoEx.MoveNextMethod) Assert.Equal(current, semanticInfoEx.CurrentProperty) Assert.Equal(dispose, semanticInfoEx.DisposeMethod) Next Next End Sub <Fact()> Public Sub ForEachOverString() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Option Infer On Imports System Class C1 Public Shared Sub Main() Dim coll as String = "Hello!" For Each element In coll 'BIND:"For Each element In coll" Console.WriteLine(element) Next End Sub End Class ]]></file> </compilation>) Dim getEnumerator = DirectCast(DirectCast(compilation.GetSpecialType(System_String), TypeSymbol).GetMember("GetEnumerator"), MethodSymbol) Dim moveNext = DirectCast(getEnumerator.ReturnType.GetMember("MoveNext"), MethodSymbol) Dim current = DirectCast(getEnumerator.ReturnType.GetMember("get_Current"), MethodSymbol) Dim dispose = DirectCast(compilation.GetSpecialType(System_Object).ContainingAssembly.GetSpecialTypeMember(SpecialMember.System_IDisposable__Dispose), MethodSymbol) For Each useInterface In {True, False} For Each useBlock In {True, False} Dim semanticInfoEx As ForEachStatementInfo If useInterface Then semanticInfoEx = DirectCast(GetBlockOrStatementInfoForTest(Of ForEachStatementSyntax, SemanticModel)(compilation, "a.vb", useParent:=useBlock), ForEachStatementInfo) Else semanticInfoEx = DirectCast(GetBlockOrStatementInfoForTest(Of ForEachStatementSyntax, VBSemanticModel)(compilation, "a.vb", useParent:=useBlock), ForEachStatementInfo) End If Assert.Equal(getEnumerator, semanticInfoEx.GetEnumeratorMethod) Assert.Equal(moveNext, semanticInfoEx.MoveNextMethod) Assert.Equal(DirectCast(current.AssociatedSymbol, PropertySymbol), semanticInfoEx.CurrentProperty) Assert.Equal(dispose, semanticInfoEx.DisposeMethod) Next Next End Sub <Fact()> Public Sub ForEachCustomCollection() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports System Imports System.Collections Class Custom Public Function GetEnumerator() As CustomEnumerator Return Nothing End Function Public Class CustomEnumerator Public Function MoveNext() As Boolean Return False End Function Public ReadOnly Property Current As Custom Get Return Nothing End Get End Property End Class End Class Class C1 Public Shared Sub Main() Dim myCustomCollection As Custom = nothing For Each element as Custom In myCustomCollection 'BIND:"For Each element as Custom In myCustomCollection" Console.WriteLine("goo") Next End Sub End Class ]]></file> </compilation>) Dim getEnumerator = DirectCast(compilation.GlobalNamespace.GetTypeMember("Custom").GetMember("GetEnumerator"), MethodSymbol) Dim moveNext = DirectCast(compilation.GlobalNamespace.GetTypeMember("Custom").GetTypeMember("CustomEnumerator").GetMember("MoveNext"), MethodSymbol) Dim current = DirectCast(compilation.GlobalNamespace.GetTypeMember("Custom").GetTypeMember("CustomEnumerator").GetMember("Current"), PropertySymbol) For Each useInterface In {True, False} For Each useBlock In {True, False} Dim semanticInfoEx As ForEachStatementInfo If useInterface Then semanticInfoEx = DirectCast(GetBlockOrStatementInfoForTest(Of ForEachStatementSyntax, SemanticModel)(compilation, "a.vb", useParent:=useBlock), ForEachStatementInfo) Else semanticInfoEx = DirectCast(GetBlockOrStatementInfoForTest(Of ForEachStatementSyntax, VBSemanticModel)(compilation, "a.vb", useParent:=useBlock), ForEachStatementInfo) End If Assert.Equal(getEnumerator, semanticInfoEx.GetEnumeratorMethod) Assert.Equal(moveNext, semanticInfoEx.MoveNextMethod) Assert.Equal(current, semanticInfoEx.CurrentProperty) Assert.Null(semanticInfoEx.DisposeMethod) Next Next End Sub <Fact()> Public Sub ForEachCustomCollectionWithDispose() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports System Imports System.Collections Class Custom Public Function GetEnumerator() As CustomEnumerator Return Nothing End Function Public Class CustomEnumerator Implements IDisposable Public Function MoveNext() As Boolean Return False End Function Public ReadOnly Property Current As Custom Get Return Nothing End Get End Property Public Sub Dispose() implements IDisposable.Dispose End Sub End Class End Class Class C1 Public Shared Sub Main() Dim myCustomCollection As Custom = nothing For Each element as Custom In myCustomCollection 'BIND:"For Each element as Custom In myCustomCollection" Console.WriteLine("goo") Next End Sub End Class ]]></file> </compilation>) Dim getEnumerator = DirectCast(compilation.GlobalNamespace.GetTypeMember("Custom").GetMember("GetEnumerator"), MethodSymbol) Dim moveNext = DirectCast(compilation.GlobalNamespace.GetTypeMember("Custom").GetTypeMember("CustomEnumerator").GetMember("MoveNext"), MethodSymbol) Dim current = DirectCast(compilation.GlobalNamespace.GetTypeMember("Custom").GetTypeMember("CustomEnumerator").GetMember("Current"), PropertySymbol) Dim dispose = DirectCast(compilation.GetSpecialType(System_Object).ContainingAssembly.GetSpecialTypeMember(SpecialMember.System_IDisposable__Dispose), MethodSymbol) For Each useInterface In {True, False} For Each useBlock In {True, False} Dim semanticInfoEx As ForEachStatementInfo If useInterface Then semanticInfoEx = DirectCast(GetBlockOrStatementInfoForTest(Of ForEachStatementSyntax, SemanticModel)(compilation, "a.vb", useParent:=useBlock), ForEachStatementInfo) Else semanticInfoEx = DirectCast(GetBlockOrStatementInfoForTest(Of ForEachStatementSyntax, VBSemanticModel)(compilation, "a.vb", useParent:=useBlock), ForEachStatementInfo) End If Assert.Equal(getEnumerator, semanticInfoEx.GetEnumeratorMethod) Assert.Equal(moveNext, semanticInfoEx.MoveNextMethod) Assert.Equal(current, semanticInfoEx.CurrentProperty) Assert.Equal(dispose, semanticInfoEx.DisposeMethod) Next Next End Sub <Fact()> Public Sub ForEachCustomCollectionWithDisposeError() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports System Imports System.Collections Class Custom Public Function GetEnumerator() As CustomEnumerator Return Nothing End Function Public Class CustomEnumerator Implements IDisposable Public Function MoveNext() As Boolean Return False End Function Public ReadOnly Property Current As Custom Get Return Nothing End Get End Property End Class End Class Class C1 Public Shared Sub Main() Dim myCustomCollection As Custom = nothing For Each element as Custom In myCustomCollection 'BIND:"For Each element as Custom In myCustomCollection" Console.WriteLine("goo") Next End Sub End Class ]]></file> </compilation>) AssertTheseDiagnostics(compilation, <expected> BC30149: Class 'CustomEnumerator' must implement 'Sub Dispose()' for interface 'IDisposable'. Implements IDisposable ~~~~~~~~~~~ </expected>) Dim getEnumerator = DirectCast(compilation.GlobalNamespace.GetTypeMember("Custom").GetMember("GetEnumerator"), MethodSymbol) Dim moveNext = DirectCast(compilation.GlobalNamespace.GetTypeMember("Custom").GetTypeMember("CustomEnumerator").GetMember("MoveNext"), MethodSymbol) Dim current = DirectCast(compilation.GlobalNamespace.GetTypeMember("Custom").GetTypeMember("CustomEnumerator").GetMember("Current"), PropertySymbol) ' the type claimed to implement IDisposable and we believed it ... Dim dispose = DirectCast(compilation.GetSpecialType(System_Object).ContainingAssembly.GetSpecialTypeMember(SpecialMember.System_IDisposable__Dispose), MethodSymbol) For Each useInterface In {True, False} For Each useBlock In {True, False} Dim semanticInfoEx As ForEachStatementInfo If useInterface Then semanticInfoEx = DirectCast(GetBlockOrStatementInfoForTest(Of ForEachStatementSyntax, SemanticModel)(compilation, "a.vb", useParent:=useBlock), ForEachStatementInfo) Else semanticInfoEx = DirectCast(GetBlockOrStatementInfoForTest(Of ForEachStatementSyntax, VBSemanticModel)(compilation, "a.vb", useParent:=useBlock), ForEachStatementInfo) End If Assert.Equal(getEnumerator, semanticInfoEx.GetEnumeratorMethod) Assert.Equal(moveNext, semanticInfoEx.MoveNextMethod) Assert.Equal(current, semanticInfoEx.CurrentProperty) Assert.Equal(dispose, semanticInfoEx.DisposeMethod) Next Next End Sub <Fact()> Public Sub ForEachCustomCollectionWithMissingMoveNext() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports System Imports System.Collections Class Custom Public Function GetEnumerator() As CustomEnumerator Return Nothing End Function Public Class CustomEnumerator Implements IDisposable Public ReadOnly Property Current As Custom Get Return Nothing End Get End Property Public Sub Dispose() implements IDisposable.Dispose End Sub End Class End Class Class C1 Public Shared Sub Main() Dim myCustomCollection As Custom = nothing For Each element as Custom In myCustomCollection 'BIND:"For Each element as Custom In myCustomCollection" Console.WriteLine("goo") Next End Sub End Class ]]></file> </compilation>) Dim getEnumerator = DirectCast(compilation.GlobalNamespace.GetTypeMember("Custom").GetMember("GetEnumerator"), MethodSymbol) For Each useInterface In {True, False} For Each useBlock In {True, False} Dim semanticInfoEx As ForEachStatementInfo If useInterface Then semanticInfoEx = DirectCast(GetBlockOrStatementInfoForTest(Of ForEachStatementSyntax, SemanticModel)(compilation, "a.vb", useParent:=useBlock), ForEachStatementInfo) Else semanticInfoEx = DirectCast(GetBlockOrStatementInfoForTest(Of ForEachStatementSyntax, VBSemanticModel)(compilation, "a.vb", useParent:=useBlock), ForEachStatementInfo) End If Assert.Equal(getEnumerator, semanticInfoEx.GetEnumeratorMethod) ' methods are partly present up to the point where the pattern was violated. Assert.Null(semanticInfoEx.MoveNextMethod) Assert.Null(semanticInfoEx.CurrentProperty) Assert.Null(semanticInfoEx.DisposeMethod) Next Next End Sub <Fact()> Public Sub ForEachNotMatchingDesignPatternIEnumerable() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class C Public Shared Sub Main() For Each x In New Enumerable() 'BIND:"For Each x In New Enumerable()" System.Console.WriteLine(x) Next End Sub End Class Class Enumerable Implements System.Collections.IEnumerable ' Explicit implementation won't match pattern. Private Function System_Collections_IEnumerable_GetEnumerator() As System.Collections.IEnumerator Implements System.Collections.IEnumerable.GetEnumerator Dim list As New System.Collections.Generic.List(Of Integer)() list.Add(3) list.Add(2) list.Add(1) Return list.GetEnumerator() End Function End Class ]]></file> </compilation>) Dim getEnumerator = DirectCast(compilation.GetSpecialType(System_Object).ContainingAssembly.GetSpecialTypeMember(SpecialMember.System_Collections_IEnumerable__GetEnumerator), MethodSymbol) Dim moveNext = DirectCast(compilation.GetSpecialType(System_Object).ContainingAssembly.GetSpecialTypeMember(SpecialMember.System_Collections_IEnumerator__MoveNext), MethodSymbol) Dim current = DirectCast(compilation.GetSpecialType(System_Object).ContainingAssembly.GetSpecialTypeMember(SpecialMember.System_Collections_IEnumerator__Current), PropertySymbol) Dim dispose = DirectCast(compilation.GetSpecialType(System_Object).ContainingAssembly.GetSpecialTypeMember(SpecialMember.System_IDisposable__Dispose), MethodSymbol) For Each useInterface In {True, False} For Each useBlock In {True, False} Dim semanticInfoEx As ForEachStatementInfo If useInterface Then semanticInfoEx = DirectCast(GetBlockOrStatementInfoForTest(Of ForEachStatementSyntax, SemanticModel)(compilation, "a.vb", useParent:=useBlock), ForEachStatementInfo) Else semanticInfoEx = DirectCast(GetBlockOrStatementInfoForTest(Of ForEachStatementSyntax, VBSemanticModel)(compilation, "a.vb", useParent:=useBlock), ForEachStatementInfo) End If Assert.Equal(getEnumerator, semanticInfoEx.GetEnumeratorMethod) Assert.Equal(moveNext, semanticInfoEx.MoveNextMethod) Assert.Equal(current, semanticInfoEx.CurrentProperty) Assert.Equal(dispose, semanticInfoEx.DisposeMethod) Next Next End Sub <Fact()> Public Sub ForEachNotMatchingDesignPatternGenericIEnumerable() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class C Public Shared Sub Main() For Each x In New Enumerable(Of Integer)() 'BIND:"For Each x In New Enumerable(Of Integer)()" System.Console.WriteLine(x) Next End Sub End Class Class Enumerable(Of T) Implements System.Collections.Generic.IEnumerable(Of Integer) ' Explicit implementation won't match pattern. Public Function System_Collections_Generic_IEnumerable_GetEnumerator() As System.Collections.Generic.IEnumerator(Of Integer) Implements System.Collections.Generic.IEnumerable(Of Integer).GetEnumerator Return Nothing End Function Public Function GetEnumerator1() As System.Collections.IEnumerator Implements System.Collections.IEnumerable.GetEnumerator Return Nothing End Function End Class ]]></file> </compilation>) ' IEnumerable is preferred to IEnumerable(Of T) Dim ienumerable = compilation.GetSpecialType(System_Collections_Generic_IEnumerable_T).Construct(ImmutableArray.Create(Of TypeSymbol)(compilation.GetSpecialType(System_Int32))) Dim ienumerator = compilation.GetSpecialType(System_Collections_Generic_IEnumerator_T).Construct(ImmutableArray.Create(Of TypeSymbol)(compilation.GetSpecialType(System_Int32))) Dim getEnumerator = DirectCast(ienumerable.GetMember("GetEnumerator"), MethodSymbol) Dim moveNext = DirectCast(compilation.GetSpecialType(System_Object).ContainingAssembly.GetSpecialTypeMember(SpecialMember.System_Collections_IEnumerator__MoveNext), MethodSymbol) Dim current = DirectCast(ienumerator.GetMember("Current"), PropertySymbol) Dim dispose = DirectCast(compilation.GetSpecialType(System_Object).ContainingAssembly.GetSpecialTypeMember(SpecialMember.System_IDisposable__Dispose), MethodSymbol) For Each useInterface In {True, False} For Each useBlock In {True, False} Dim semanticInfoEx As ForEachStatementInfo If useInterface Then semanticInfoEx = DirectCast(GetBlockOrStatementInfoForTest(Of ForEachStatementSyntax, SemanticModel)(compilation, "a.vb", useParent:=useBlock), ForEachStatementInfo) Else semanticInfoEx = DirectCast(GetBlockOrStatementInfoForTest(Of ForEachStatementSyntax, VBSemanticModel)(compilation, "a.vb", useParent:=useBlock), ForEachStatementInfo) End If Assert.Equal(getEnumerator, semanticInfoEx.GetEnumeratorMethod) Assert.Equal(moveNext, semanticInfoEx.MoveNextMethod) Assert.Equal(current, semanticInfoEx.CurrentProperty) Assert.Equal(dispose, semanticInfoEx.DisposeMethod) Next Next End Sub <Fact()> Public Sub ForEachGenericIEnumerable() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System.Collections.Generic Class C Public Shared Sub Main() Dim collection as IEnumerable(Of Integer) For Each x In collection 'BIND:"For Each x In collection" System.Console.WriteLine(x) Next End Sub End Class ]]></file> </compilation>) ' the first matching symbol on IEnumerable(Of T) Dim moveNext = DirectCast(compilation.GetSpecialType(System_Object).ContainingAssembly.GetSpecialTypeMember(SpecialMember.System_Collections_IEnumerator__MoveNext), MethodSymbol) Dim dispose = DirectCast(compilation.GetSpecialType(System_Object).ContainingAssembly.GetSpecialTypeMember(SpecialMember.System_IDisposable__Dispose), MethodSymbol) For Each useInterface In {True, False} For Each useBlock In {True, False} Dim semanticInfoEx As ForEachStatementInfo If useInterface Then semanticInfoEx = DirectCast(GetBlockOrStatementInfoForTest(Of ForEachStatementSyntax, SemanticModel)(compilation, "a.vb", useParent:=useBlock), ForEachStatementInfo) Else semanticInfoEx = DirectCast(GetBlockOrStatementInfoForTest(Of ForEachStatementSyntax, VBSemanticModel)(compilation, "a.vb", useParent:=useBlock), ForEachStatementInfo) End If Assert.Equal("Function System.Collections.Generic.IEnumerable(Of System.Int32).GetEnumerator() As System.Collections.Generic.IEnumerator(Of System.Int32)", semanticInfoEx.GetEnumeratorMethod.ToDisplayString(SymbolDisplayFormat.TestFormat)) Assert.Equal(moveNext, semanticInfoEx.MoveNextMethod) ' the first matching symbol on IEnumerable(Of T) Assert.Equal("ReadOnly Property System.Collections.Generic.IEnumerator(Of System.Int32).Current As System.Int32", semanticInfoEx.CurrentProperty.ToDisplayString(SymbolDisplayFormat.TestFormat)) Assert.Equal(dispose, semanticInfoEx.DisposeMethod) Next Next End Sub <Fact()> Public Sub ForEachInvalidCollection() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports System Class C1 Public Shared Sub Main() For Each element as Integer In 1 'BIND:"For Each element as Integer In 1" Console.WriteLine(element) Next End Sub End Class ]]></file> </compilation>) For Each useInterface In {True, False} For Each useBlock In {True, False} Dim semanticInfoEx As ForEachStatementInfo If useInterface Then semanticInfoEx = DirectCast(GetBlockOrStatementInfoForTest(Of ForEachStatementSyntax, SemanticModel)(compilation, "a.vb", useParent:=useBlock), ForEachStatementInfo) Else semanticInfoEx = DirectCast(GetBlockOrStatementInfoForTest(Of ForEachStatementSyntax, VBSemanticModel)(compilation, "a.vb", useParent:=useBlock), ForEachStatementInfo) End If Assert.Null(semanticInfoEx.GetEnumeratorMethod) Assert.Null(semanticInfoEx.MoveNextMethod) Assert.Null(semanticInfoEx.CurrentProperty) Assert.Null(semanticInfoEx.DisposeMethod) Next Next End Sub <Fact()> Public Sub ForEachLateBinding() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Option Strict off Class C Public Shared Sub Main() Dim collection as Object = {1, 2, 3} For Each x In collection 'BIND:"For Each x In collection" System.Console.WriteLine(x) Next End Sub End Class ]]></file> </compilation>) ' the first matching symbol on IEnumerable Dim moveNext = DirectCast(compilation.GetSpecialType(System_Object).ContainingAssembly.GetSpecialTypeMember(SpecialMember.System_Collections_IEnumerator__MoveNext), MethodSymbol) Dim dispose = DirectCast(compilation.GetSpecialType(System_Object).ContainingAssembly.GetSpecialTypeMember(SpecialMember.System_IDisposable__Dispose), MethodSymbol) For Each useInterface In {True, False} For Each useBlock In {True, False} Dim semanticInfoEx As ForEachStatementInfo If useInterface Then semanticInfoEx = DirectCast(GetBlockOrStatementInfoForTest(Of ForEachStatementSyntax, SemanticModel)(compilation, "a.vb", useParent:=useBlock), ForEachStatementInfo) Else semanticInfoEx = DirectCast(GetBlockOrStatementInfoForTest(Of ForEachStatementSyntax, VBSemanticModel)(compilation, "a.vb", useParent:=useBlock), ForEachStatementInfo) End If Assert.Equal("Function System.Collections.IEnumerable.GetEnumerator() As System.Collections.IEnumerator", semanticInfoEx.GetEnumeratorMethod.ToDisplayString(SymbolDisplayFormat.TestFormat)) Assert.Equal(moveNext, semanticInfoEx.MoveNextMethod) Assert.Equal("ReadOnly Property System.Collections.IEnumerator.Current As System.Object", semanticInfoEx.CurrentProperty.ToDisplayString(SymbolDisplayFormat.TestFormat)) Assert.Equal(dispose, semanticInfoEx.DisposeMethod) Next Next End Sub <Fact()> Public Sub NewDelegate() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Delegate Sub Del(x As Integer) Module Program Sub Main(args As String()) Dim d As Del d = New Del(AddressOf goo)'BIND:"Del" End Sub Sub goo(x As Integer) End Sub End Module ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticInfo.Type) Assert.Null(semanticInfo.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Del", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub NewDelegate2() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Delegate Sub Del(x As Integer) Module Program Sub Main(args As String()) Dim d As Del d = New Del(AddressOf goo) 'BIND:"New Del(AddressOf goo)" End Sub Sub goo(x As Integer) End Sub End Module ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of ObjectCreationExpressionSyntax)(compilation, "a.vb") Assert.Equal("Del", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Delegate, semanticInfo.Type.TypeKind) Assert.Equal("Del", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Delegate, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub NewDelegateWrongMethodSignature() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Delegate Sub Del(x As Integer) Module Program Sub Main(args As String()) Dim d As Del d = New Del(AddressOf goo)'BIND:"Del" End Sub Sub goo(y As String, z As String) End Sub End Module ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticInfo.Type) Assert.Null(semanticInfo.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Del", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub NewDelegateWrongMethodSignature2() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Delegate Sub Del(x As Integer) Module Program Sub Main(args As String()) Dim d As Del d = New Del(AddressOf goo)'BIND:"New Del(AddressOf goo)" End Sub Sub goo(y As String, z As String) End Sub End Module ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of ObjectCreationExpressionSyntax)(compilation, "a.vb") Assert.Equal("Del", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Delegate, semanticInfo.Type.TypeKind) Assert.Equal("Del", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Delegate, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub NewDelegateOnLambda() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Delegate Sub Del(x As Integer) Module Program Sub Main(args As String()) Dim d As Del d = New Del(Sub(x) Console.WriteLine(x)) 'BIND:"Del"'BIND:"Del" End Sub Sub goo() End Sub End Module ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticInfo.Type) Assert.Null(semanticInfo.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Del", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub NewDelegateOnLambda2() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Delegate Sub Del(x As Integer) Module Program Sub Main(args As String()) Dim d As Del d = New Del(Sub(x) Console.WriteLine(x)) 'BIND:"New Del(Sub(x) Console.WriteLine(x))" End Sub Sub goo() End Sub End Module ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of ObjectCreationExpressionSyntax)(compilation, "a.vb") Assert.Equal("Del", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Delegate, semanticInfo.Type.TypeKind) Assert.Equal("Del", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Delegate, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub NewDelegateOnMismatchedLambda() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Delegate Sub Del(x As Integer) Module Program Sub Main(args As String()) Dim d As Del d = New Del(Sub(x, y) Console.WriteLine(x)) 'BIND:"Del"'BIND:"Del" End Sub Sub goo() End Sub End Module ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticInfo.Type) Assert.Null(semanticInfo.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Del", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub NewDelegateOnMismatchedLambda2() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Delegate Sub Del(x As Integer) Module Program Sub Main(args As String()) Dim d As Del d = New Del(Sub(x, y) Console.WriteLine(x)) 'BIND:"New Del(Sub(x, y) Console.WriteLine(x))" End Sub Sub goo() End Sub End Module ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of ObjectCreationExpressionSyntax)(compilation, "a.vb") Assert.Equal("Del", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Delegate, semanticInfo.Type.TypeKind) Assert.Equal("Del", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Delegate, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub NewOfInaccessibleClass() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Class X Private Class Y End Class End Class Module Program Sub Main(args As String()) Dim o As Object o = New X.Y(3)'BIND:"X.Y" End Sub Sub goo() End Sub End Module ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of QualifiedNameSyntax)(compilation, "a.vb") Assert.Null(semanticInfo.Type) Assert.Null(semanticInfo.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason) Assert.Equal(1, semanticInfo.CandidateSymbols.Length) Assert.Equal("X.Y", semanticInfo.CandidateSymbols(0).ToTestDisplayString()) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub NewOfInaccessibleClass2() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Class X Private Class Y End Class End Class Module Program Sub Main(args As String()) Dim o As Object o = New X.Y(3)'BIND:"New X.Y(3)" End Sub Sub goo() End Sub End Module ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of ObjectCreationExpressionSyntax)(compilation, "a.vb") Assert.Equal("X.Y", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.WideningReference, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason) Assert.Equal(1, semanticInfo.CandidateSymbols.Length) Assert.Equal("Sub X.Y..ctor()", semanticInfo.CandidateSymbols(0).ToTestDisplayString()) Assert.Equal(1, semanticInfo.MemberGroup.Length) Assert.Equal("Sub X.Y..ctor()", semanticInfo.MemberGroup(0).ToTestDisplayString()) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub OverloadResolutionFailureOnNew() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Class X Public Sub New(x As Integer) End Sub End Class Module Program Sub Main(args As String()) Dim o As Object o = New X(3, 4)'BIND:"X" End Sub Sub goo() End Sub End Module ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticInfo.Type) Assert.Null(semanticInfo.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("X", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub OverloadResolutionFailureOnNew2() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Class X Public Sub New(x As Integer) End Sub End Class Module Program Sub Main(args As String()) Dim o As Object o = New X(3, 4)'BIND:"New X(3, 4)" End Sub Sub goo() End Sub End Module ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of ObjectCreationExpressionSyntax)(compilation, "a.vb") Assert.Equal("X", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.WideningReference, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason) Assert.Equal(1, semanticInfo.CandidateSymbols.Length) Dim sortedCandidates = semanticInfo.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub X..ctor(x As System.Int32)", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(0).Kind) Assert.Equal(1, semanticInfo.MemberGroup.Length) Dim sortedMethodGroup = semanticInfo.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub X..ctor(x As System.Int32)", sortedMethodGroup(0).ToTestDisplayString()) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <WorkItem(542695, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542695")> <Fact()> Public Sub TestCandidateReasonForInaccessibleMethod() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class Class1 Private Class NestedClass Private Shared Sub Method1() End Sub End Class Sub Method1 NestedClass.Method1()'BIND:"NestedClass.Method1()" End Sub End Class ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of InvocationExpressionSyntax)(compilation, "a.vb") Assert.Equal("System.Void", semanticSummary.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticSummary.Type.TypeKind) Assert.Equal("System.Void", semanticSummary.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticSummary.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Null(semanticSummary.Symbol) Assert.Equal(CandidateReason.Inaccessible, semanticSummary.CandidateReason) Assert.Equal(1, semanticSummary.CandidateSymbols.Length) Dim sortedCandidates = semanticSummary.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub Class1.NestedClass.Method1()", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(0).Kind) Assert.Equal(0, semanticSummary.MemberGroup.Length) End Sub <WorkItem(542701, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542701")> <Fact()> Public Sub GenericTypeWithNoTypeArgsOnAttribute_AttributeSyntax() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class Gen(Of T) End Class <Gen()>'BIND:"Gen()" Class Test Sub Method1() End Sub End Class ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of AttributeSyntax)(compilation, "a.vb") Assert.Equal("Gen(Of T)", semanticSummary.Type.ToTestDisplayString()) Assert.Equal("Gen(Of T)", semanticSummary.ConvertedType.ToTestDisplayString()) Assert.Null(semanticSummary.Symbol) Assert.Equal(CandidateReason.WrongArity, semanticSummary.CandidateReason) Assert.Equal(1, semanticSummary.CandidateSymbols.Length) Dim sortedCandidates = semanticSummary.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub Gen(Of T)..ctor()", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(0).Kind) Assert.Null(semanticSummary.Alias) Assert.Equal(1, semanticSummary.MemberGroup.Length) Dim sortedMethodGroup = semanticSummary.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub Gen(Of T)..ctor()", sortedMethodGroup(0).ToTestDisplayString()) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact()> Public Sub GenericTypeWithNoTypeArgsOnAttribute_IdentifierSyntax() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class Gen(Of T) End Class <Gen()>'BIND:"Gen" Class Test Sub Method1() End Sub End Class ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("Gen(Of T)", semanticSummary.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.Type.TypeKind) Assert.Equal("Gen(Of T)", semanticSummary.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Null(semanticSummary.Symbol) Assert.Equal(CandidateReason.WrongArity, semanticSummary.CandidateReason) Assert.Equal(1, semanticSummary.CandidateSymbols.Length) Dim sortedCandidates = semanticSummary.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub Gen(Of T)..ctor()", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(0).Kind) Assert.Null(semanticSummary.Alias) Assert.Equal(1, semanticSummary.MemberGroup.Length) Dim sortedMethodGroup = semanticSummary.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub Gen(Of T)..ctor()", sortedMethodGroup(0).ToTestDisplayString()) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact()> Public Sub NextVariable() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class X Sub Goo() For i As Integer = 1 To 10 Next i'BIND:"i" End Sub End Class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("i As System.Int32", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <WorkItem(542009, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542009")> <Fact()> Public Sub Bug8966() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="a.vb"><![CDATA[ Option Strict Off Option Infer On Imports System.Runtime.CompilerServices Imports System Module M Sub Main() Dim s As String = "" Dim x As Action(Of String) = AddressOf s.ToLowerInvariant'BIND:"ToLowerInvariant" x(Nothing) End Sub <Extension()> Sub ToLowerInvariant(ByVal x As Object) Console.WriteLine(1) End Sub End Module ]]></file> </compilation>, {TestMetadata.Net40.SystemCore}, TestOptions.ReleaseExe) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") CompilationUtils.AssertNoErrors(compilation) Assert.Null(semanticInfo.Type) Assert.Null(semanticInfo.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Function System.String.ToLowerInvariant() As System.String", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(2, semanticInfo.MemberGroup.Length) Dim sortedMethodGroup = semanticInfo.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Function System.String.ToLowerInvariant() As System.String", sortedMethodGroup(0).ToTestDisplayString()) Assert.Equal("Sub System.Object.ToLowerInvariant()", sortedMethodGroup(1).ToTestDisplayString()) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub ImplicitLocal1() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Option Explicit Off Option Strict On Option Infer On Imports System Module Program Sub Main(args As String()) If True Then x$ = "hello" 'BIND2:"x$" End If y = x'BIND1:"x" Console.WriteLine(y) End Sub End Module ]]></file> </compilation>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim node1 = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1) Dim node2 = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 2) Dim semanticInfo1 = CompilationUtils.GetSemanticInfoSummary(semanticModel, node1) Assert.Equal("System.String", semanticInfo1.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo1.Type.TypeKind) Assert.Equal("System.Object", semanticInfo1.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo1.ConvertedType.TypeKind) Assert.Equal(ConversionKind.WideningReference, semanticInfo1.ImplicitConversion.Kind) Assert.Equal("x As System.String", semanticInfo1.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Local, semanticInfo1.Symbol.Kind) Dim semanticInfo2 = CompilationUtils.GetSemanticInfoSummary(semanticModel, node2) Assert.Equal("System.String", semanticInfo2.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo2.Type.TypeKind) Assert.Equal("System.String", semanticInfo2.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo2.ConvertedType.TypeKind) Assert.Equal("x As System.String", semanticInfo2.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Local, semanticInfo2.Symbol.Kind) Assert.Same(semanticInfo1.Symbol, semanticInfo2.Symbol) End Sub <Fact()> Public Sub ImplicitLocal2() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Option Explicit Off Option Strict On Option Infer On Imports System Module Program Sub Main(args As String()) Dim a1 As Action = Sub() x$ = "hello"'BIND2:"x$" End Sub Dim a2 As Action = Sub() y = x'BIND1:"x" Console.WriteLine(y) End Sub End Sub End Module ]]></file> </compilation>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim node1 = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1) Dim node2 = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 2) Dim semanticInfo1 = CompilationUtils.GetSemanticInfoSummary(semanticModel, node1) Assert.Equal("System.String", semanticInfo1.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo1.Type.TypeKind) Assert.Equal("System.Object", semanticInfo1.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo1.ConvertedType.TypeKind) Assert.Equal(ConversionKind.WideningReference, semanticInfo1.ImplicitConversion.Kind) Assert.Equal("x As System.String", semanticInfo1.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Local, semanticInfo1.Symbol.Kind) Dim semanticInfo2 = CompilationUtils.GetSemanticInfoSummary(semanticModel, node2) Assert.Equal("System.String", semanticInfo2.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo2.Type.TypeKind) Assert.Equal("System.String", semanticInfo2.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo2.ConvertedType.TypeKind) Assert.Equal("x As System.String", semanticInfo2.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Local, semanticInfo2.Symbol.Kind) Assert.Same(semanticInfo1.Symbol, semanticInfo2.Symbol) End Sub <Fact()> Public Sub ImplicitLocalInLambdaInInitializer() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Option Explicit Off Option Strict On Option Infer On Imports System Module Module1 Dim y As Integer = InvokeMultiple(Function() x% = x% + 1'BIND1:"x%" Return x% End Function, 2) + InvokeMultiple(Function() x% = x% + 1 Return x%'BIND2:"x%" End Function, 7) Function InvokeMultiple(f As Func(Of Integer), times As Integer) As Integer Dim result As Integer = 0 For i As Integer = 1 To times result = f() Next Return result End Function Sub Main() Console.WriteLine(y) End Sub End Module ]]></file> </compilation>) Dim semanticInfo1 = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb", 1) Assert.Equal("System.Int32", semanticInfo1.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo1.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo1.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo1.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo1.ImplicitConversion.Kind) Assert.Equal("x As System.Int32", semanticInfo1.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Local, semanticInfo1.Symbol.Kind) Assert.Equal(0, semanticInfo1.CandidateSymbols.Length) Assert.Equal(SymbolKind.Method, semanticInfo1.Symbol.ContainingSymbol.Kind) Dim containingMethod1 = DirectCast(semanticInfo1.Symbol.ContainingSymbol, MethodSymbol) Assert.True(containingMethod1.IsLambdaMethod, "variable should be contained by a lambda") Dim semanticInfo2 = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb", 2) Assert.Equal("System.Int32", semanticInfo2.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo2.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo2.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo2.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo2.ImplicitConversion.Kind) Assert.Equal("x As System.Int32", semanticInfo2.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Local, semanticInfo2.Symbol.Kind) Assert.Equal(0, semanticInfo2.CandidateSymbols.Length) Assert.Equal(SymbolKind.Method, semanticInfo2.Symbol.ContainingSymbol.Kind) Dim containingMethod2 = DirectCast(semanticInfo2.Symbol.ContainingSymbol, MethodSymbol) Assert.True(containingMethod2.IsLambdaMethod, "variable should be contained by a lambda") ' Should be different variables in different lambdas. Assert.NotSame(semanticInfo1.Symbol, semanticInfo2.Symbol) Assert.NotEqual(semanticInfo1.Symbol, semanticInfo2.Symbol) Assert.NotSame(containingMethod1, containingMethod2) Assert.NotEqual(containingMethod1, containingMethod2) End Sub <WorkItem(542301, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542301")> <Fact()> Public Sub Bug9489() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Collections Imports System.Linq Module Program Sub Main(args As String()) Dim col = New ObjectModel.Collection(Of MetadataReference)() From {ref1, ref2, ref3}'BIND:"Collection(Of MetadataReference)" End Sub End Module ]]></file> </compilation>, {TestMetadata.Net40.SystemCore}, TestOptions.ReleaseExe) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of GenericNameSyntax)(compilation, "a.vb") End Sub <WorkItem(542596, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542596")> <Fact()> Public Sub BindMethodInvocationWhenUnnamedArgFollowsNamed() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module Module1 Sub M1(x As Integer, y As Integer) End Sub Sub Main() M1(x:=2, 3) 'BIND:"M1(x:=2, 3)" End Sub End Module </file> </compilation>, parseOptions:=TestOptions.Regular.WithLanguageVersion(LanguageVersion.VisualBasic15)) compilation.AssertTheseDiagnostics(<errors> BC30241: Named argument expected. Please use language version 15.5 or greater to use non-trailing named arguments. M1(x:=2, 3) 'BIND:"M1(x:=2, 3)" ~ </errors>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of InvocationExpressionSyntax)(compilation, "a.vb") Assert.Equal("Sub Module1.M1(x As System.Int32, y As System.Int32)", semanticInfo.Symbol.ToTestDisplayString()) compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module Module1 Sub M1(x As Integer, y As Integer) End Sub Sub M1(x As Integer, y As Long) End Sub Sub Main() M1(x:=2, 3) 'BIND:"M1(x:=2, 3)" End Sub End Module </file> </compilation>, parseOptions:=TestOptions.Regular.WithLanguageVersion(LanguageVersion.VisualBasic15)) compilation.AssertTheseDiagnostics(<errors> BC30241: Named argument expected. Please use language version 15.5 or greater to use non-trailing named arguments. M1(x:=2, 3) 'BIND:"M1(x:=2, 3)" ~ </errors>) semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of InvocationExpressionSyntax)(compilation, "a.vb") Assert.Equal("Sub Module1.M1(x As System.Int32, y As System.Int32)", semanticInfo.Symbol.ToTestDisplayString()) End Sub <WorkItem(542332, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542332")> <Fact()> Public Sub BindArrayBoundOfField() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class class1 Public zipf As Integer = 7 Public b, quux(zipf) As Integer'BIND:"zipf" End Class ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("System.Int32", semanticSummary.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticSummary.Type.TypeKind) Assert.Equal("System.Int32", semanticSummary.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticSummary.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Equal("class1.zipf As System.Int32", semanticSummary.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Field, semanticSummary.Symbol.Kind) Assert.Equal(0, semanticSummary.CandidateSymbols.Length) Assert.Null(semanticSummary.Alias) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <WorkItem(542858, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542858")> <Fact()> Public Sub TypeNamesInsideCastExpression() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Module Module1 Sub Main(args As String()) Dim func1 As Func(Of Integer, Integer) = Function(x) x + 1 Dim type1 = CType(func1, Func(Of Integer, Integer)) 'BIND:"Func(Of Integer, Integer)" End Sub End Module ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of GenericNameSyntax)(compilation, "a.vb") Assert.Equal("System.Func(Of System.Int32, System.Int32)", semanticSummary.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Delegate, semanticSummary.Type.TypeKind) Assert.Equal("System.Func(Of System.Int32, System.Int32)", semanticSummary.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Delegate, semanticSummary.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Equal("System.Func(Of System.Int32, System.Int32)", semanticSummary.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, semanticSummary.Symbol.Kind) Assert.Equal(0, semanticSummary.CandidateSymbols.Length) Assert.Null(semanticSummary.Alias) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <WorkItem(542933, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542933")> <Fact()> Public Sub CTypeOnALambdaExpr() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Module Program Sub Main(args As String()) Dim f2 As Object = CType(Function(x) x + 5, Func(Of Integer, Integer))'BIND:"CType(Function(x) x + 5, Func(Of Integer, Integer))" End Sub End Module ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of CTypeExpressionSyntax)(compilation, "a.vb") Assert.Equal("System.Func(Of System.Int32, System.Int32)", semanticSummary.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Delegate, semanticSummary.Type.TypeKind) Assert.Equal("System.Object", semanticSummary.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.ConvertedType.TypeKind) Assert.Equal(ConversionKind.WideningReference Or ConversionKind.DelegateRelaxationLevelWideningToNonLambda, semanticSummary.ImplicitConversion.Kind) Assert.Null(semanticSummary.Symbol) Assert.Equal(CandidateReason.None, semanticSummary.CandidateReason) Assert.Equal(0, semanticSummary.CandidateSymbols.Length) Assert.Null(semanticSummary.Alias) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact()> Public Sub AliasInLocalDecl() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports System Imports A = System.String Module Program Sub Main(args As String()) Dim local As A = Nothing'BIND:"A" End Sub End Module ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("System.String", semanticSummary.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.Type.TypeKind) Assert.Equal("System.String", semanticSummary.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Equal("System.String", semanticSummary.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, semanticSummary.Symbol.Kind) Assert.Equal(0, semanticSummary.CandidateSymbols.Length) Assert.Equal("A=System.String", semanticSummary.Alias.ToTestDisplayString()) Assert.Equal(SymbolKind.Alias, semanticSummary.Alias.Kind) Assert.Equal(SymbolKind.NamedType, semanticSummary.Alias.Target.Kind) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact()> Public Sub AliasInTryCast() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports System Imports A = System.String Module Program Sub Main(args As String()) Dim local As A = Nothing Dim x = TryCast(local, A)'BIND:"A" End Sub End Module ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("System.String", semanticSummary.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.Type.TypeKind) Assert.Equal("System.String", semanticSummary.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Equal("System.String", semanticSummary.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, semanticSummary.Symbol.Kind) Assert.Equal(0, semanticSummary.CandidateSymbols.Length) Assert.Equal("A=System.String", semanticSummary.Alias.ToTestDisplayString()) Assert.Equal(SymbolKind.Alias, semanticSummary.Alias.Kind) Assert.Equal(SymbolKind.NamedType, semanticSummary.Alias.Target.Kind) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact()> Public Sub AliasInDirectCast() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports System Imports A = System.String Module Program Sub Main(args As String()) Dim local As A = Nothing Dim x = DirectCast(local, A)'BIND:"A" End Sub End Module ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("System.String", semanticSummary.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.Type.TypeKind) Assert.Equal("System.String", semanticSummary.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Equal("System.String", semanticSummary.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, semanticSummary.Symbol.Kind) Assert.Equal(0, semanticSummary.CandidateSymbols.Length) Assert.Equal("A=System.String", semanticSummary.Alias.ToTestDisplayString()) Assert.Equal(SymbolKind.Alias, semanticSummary.Alias.Kind) Assert.Equal(SymbolKind.NamedType, semanticSummary.Alias.Target.Kind) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact()> Public Sub AliasInCType() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports System Imports A = System.String Module Program Sub Main(args As String()) Dim local As A = Nothing Dim x = CType(local, A)'BIND:"A" End Sub End Module ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("System.String", semanticSummary.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.Type.TypeKind) Assert.Equal("System.String", semanticSummary.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Equal("System.String", semanticSummary.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, semanticSummary.Symbol.Kind) Assert.Equal(0, semanticSummary.CandidateSymbols.Length) Assert.Equal("A=System.String", semanticSummary.Alias.ToTestDisplayString()) Assert.Equal(SymbolKind.Alias, semanticSummary.Alias.Kind) Assert.Equal(SymbolKind.NamedType, semanticSummary.Alias.Target.Kind) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact()> Public Sub AliasInGenericTypeArgument() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports System Imports A = System.String Module Program Sub Main(args As String()) Dim local As A = Nothing Dim x = CType(local, IEnumerable(Of A))'BIND:"A" End Sub End Module ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("System.String", semanticSummary.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.Type.TypeKind) Assert.Equal("System.String", semanticSummary.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Equal("System.String", semanticSummary.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, semanticSummary.Symbol.Kind) Assert.Equal(0, semanticSummary.CandidateSymbols.Length) Assert.Equal("A=System.String", semanticSummary.Alias.ToTestDisplayString()) Assert.Equal(SymbolKind.Alias, semanticSummary.Alias.Kind) Assert.Equal(SymbolKind.NamedType, semanticSummary.Alias.Target.Kind) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <WorkItem(542885, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542885")> <Fact()> Public Sub AliasInGenericArgOfLocal() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System.Threading Imports Thr = System.Threading.Thread Module Program Sub Main(args As String()) Dim q = New List(Of Thr)'BIND:"Thr" End Sub End Module ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("System.Threading.Thread", semanticSummary.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.Type.TypeKind) Assert.Equal("System.Threading.Thread", semanticSummary.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Equal("System.Threading.Thread", semanticSummary.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, semanticSummary.Symbol.Kind) Assert.Equal(0, semanticSummary.CandidateSymbols.Length) Assert.Equal("Thr=System.Threading.Thread", semanticSummary.Alias.ToTestDisplayString()) Assert.Equal(SymbolKind.Alias, semanticSummary.Alias.Kind) Assert.Equal(SymbolKind.NamedType, semanticSummary.Alias.Target.Kind) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <WorkItem(542841, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542841")> <Fact()> Public Sub AliasInArrayCreation() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Imports IClon = System.ICloneable Module M Sub Goo() Dim y = New IClon() {}'BIND:"IClon" End Sub End Module ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("System.ICloneable", semanticSummary.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Interface, semanticSummary.Type.TypeKind) Assert.Equal("System.ICloneable", semanticSummary.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Interface, semanticSummary.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Equal("System.ICloneable", semanticSummary.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, semanticSummary.Symbol.Kind) Assert.Equal(0, semanticSummary.CandidateSymbols.Length) Assert.Equal("IClon=System.ICloneable", semanticSummary.Alias.ToTestDisplayString()) Assert.Equal(SymbolKind.Alias, semanticSummary.Alias.Kind) Assert.Equal(SymbolKind.NamedType, semanticSummary.Alias.Target.Kind) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <WorkItem(542808, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542808")> <Fact()> Public Sub InvocationWithMissingCloseParen() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="a.vb"><![CDATA[ Imports System.Diagnostics Class C Sub M() Dim watch = Stopwatch.StartNew('BIND:"Stopwatch.StartNew" watch.Start() End Sub End Class ]]></file> </compilation>, references:={SystemRef}) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of MemberAccessExpressionSyntax)(compilation, "a.vb") Assert.Null(semanticSummary.Symbol) Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticSummary.CandidateReason) Assert.Equal(1, semanticSummary.CandidateSymbols.Length) Dim sortedCandidates = semanticSummary.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Function System.Diagnostics.Stopwatch.StartNew() As System.Diagnostics.Stopwatch", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(0).Kind) Assert.Equal(1, semanticSummary.MemberGroup.Length) Dim sortedMethodGroup = semanticSummary.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Function System.Diagnostics.Stopwatch.StartNew() As System.Diagnostics.Stopwatch", sortedMethodGroup(0).ToTestDisplayString()) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:="https://github.com/dotnet/roslyn/issues/29531")> Public Sub FailedOverloadResolutionOnCallShouldHaveMemberGroup() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Dim v As A = New A() dim r = v.Goo("hello")'BIND:"Goo" End Sub End Module Class A Public Function Goo() As Integer Return 1 End Function 'Public Function Goo(x as integer, y as Integer) As Integer ' Return 1 'End Function End Class ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticSummary.Symbol) Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticSummary.CandidateReason) Assert.Equal(1, semanticSummary.CandidateSymbols.Length) Dim sortedCandidates = semanticSummary.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Function A.Goo() As System.Int32", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(0).Kind) Assert.Equal(1, semanticSummary.MemberGroup.Length) Dim sortedMethodGroup = semanticSummary.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Function A.Goo() As System.Int32", sortedMethodGroup(0).ToTestDisplayString()) End Sub <Fact()> Public Sub MyBaseNew() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Class B Sub New() Console.WriteLine("B constructor") End Sub End Class Class C Inherits B Sub New() 'Dim q = 42 MyBase.New()'BIND:"New" End Sub End Class ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticSummary.Type) Assert.Null(semanticSummary.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Equal("Sub B..ctor()", semanticSummary.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Method, semanticSummary.Symbol.Kind) Assert.Equal(0, semanticSummary.CandidateSymbols.Length) Assert.Null(semanticSummary.Alias) Assert.Equal(1, semanticSummary.MemberGroup.Length) Dim sortedMethodGroup = semanticSummary.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub B..ctor()", sortedMethodGroup(0).ToTestDisplayString()) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact()> Public Sub MyBaseNew2() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Class B Sub New() Console.WriteLine("B constructor") End Sub End Class Class C Inherits B Sub New() Dim q = 42 MyBase.New()'BIND:"New" End Sub End Class ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticSummary.Type) Assert.Null(semanticSummary.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Equal("Sub B..ctor()", semanticSummary.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Method, semanticSummary.Symbol.Kind) Assert.Equal(0, semanticSummary.CandidateSymbols.Length) Assert.Null(semanticSummary.Alias) Assert.Equal(1, semanticSummary.MemberGroup.Length) Dim sortedMethodGroup = semanticSummary.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub B..ctor()", sortedMethodGroup(0).ToTestDisplayString()) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact()> Public Sub MyBaseNew3() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Class B Sub New() Console.WriteLine("B constructor") End Sub End Class Class C Inherits B Sub New() 'Dim q = 42 MyBase.New()'BIND:"MyBase.New()" End Sub End Class ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of InvocationExpressionSyntax)(compilation, "a.vb") Assert.Equal("System.Void", semanticSummary.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticSummary.Type.TypeKind) Assert.Equal("System.Void", semanticSummary.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticSummary.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Equal("Sub B..ctor()", semanticSummary.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Method, semanticSummary.Symbol.Kind) Assert.Equal(0, semanticSummary.CandidateSymbols.Length) Assert.Null(semanticSummary.Alias) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact()> Public Sub MyBaseNew4() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Class B Sub New() Console.WriteLine("B constructor") End Sub End Class Class C Inherits B Sub New() Dim q = 42 MyBase.New()'BIND:"MyBase.New()" End Sub End Class ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of InvocationExpressionSyntax)(compilation, "a.vb") Assert.Equal("System.Void", semanticSummary.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticSummary.Type.TypeKind) Assert.Equal("System.Void", semanticSummary.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticSummary.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Equal("Sub B..ctor()", semanticSummary.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Method, semanticSummary.Symbol.Kind) Assert.Equal(0, semanticSummary.CandidateSymbols.Length) Assert.Null(semanticSummary.Alias) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <WorkItem(542941, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542941")> <Fact()> Public Sub QualifiedTypeInDim() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class Program Shared Sub Main() Dim c = HttpContext.Current'BIND:"HttpContext" End Sub End Class Class HttpContext Public Shared Property Current As Object End Class ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("HttpContext", semanticSummary.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.Type.TypeKind) Assert.Equal("HttpContext", semanticSummary.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Equal("HttpContext", semanticSummary.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, semanticSummary.Symbol.Kind) Assert.Equal(0, semanticSummary.CandidateSymbols.Length) Assert.Null(semanticSummary.Alias) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <WorkItem(543031, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543031")> <Fact()> Public Sub MissingIdentifierSyntaxNodeIncompleteMethodDecl() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Module Program Sub Main(args As End Sub End Module ]]></file> </compilation>) Dim tree = compilation.SyntaxTrees(0) Dim node As ExpressionSyntax = DirectCast(tree.FindNodeOrTokenByKind(SyntaxKind.IdentifierName).AsNode(), ExpressionSyntax) Dim info = compilation.GetSemanticModel(tree).GetTypeInfo(node) Assert.NotNull(info) Assert.Equal(TypeInfo.None, info) End Sub <WorkItem(543099, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543099")> <Fact()> Public Sub GetSymbolForOptionalParamMethodCall() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Module Program Sub Goo(x As Integer, Optional y As Double = #1/1/2001#) End Sub Sub Main(args As String()) Goo(1)'BIND:"Goo" End Sub End Module ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticSummary.Type) Assert.Null(semanticSummary.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Equal("Sub Program.Goo(x As System.Int32, [y As System.Double])", semanticSummary.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Method, semanticSummary.Symbol.Kind) Assert.Equal(0, semanticSummary.CandidateSymbols.Length) Assert.Null(semanticSummary.Alias) Assert.Equal(1, semanticSummary.MemberGroup.Length) Dim sortedMethodGroup = semanticSummary.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub Program.Goo(x As System.Int32, [y As System.Double])", sortedMethodGroup(0).ToTestDisplayString()) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <WorkItem(10607, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub GetSymbolForOptionalParamMethodCallWithOutParenthesis() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Goo(Optional i As Integer = 1) End Sub Sub Main(args As String()) Goo'BIND:"Goo" End Sub End Module ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of InvocationExpressionSyntax)(compilation, "a.vb") Assert.Equal("System.Void", semanticSummary.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticSummary.Type.TypeKind) Assert.Equal("System.Void", semanticSummary.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticSummary.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Equal("Sub Program.Goo([i As System.Int32 = 1])", semanticSummary.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Method, semanticSummary.Symbol.Kind) Assert.Equal(0, semanticSummary.CandidateSymbols.Length) Assert.Null(semanticSummary.Alias) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <WorkItem(542217, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542217")> <Fact()> Public Sub ConflictingAliases() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports S = System Imports S = System.IO Module Program Sub Main() End Sub End Module ]]></file> </compilation>) Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim aliases = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of SimpleImportsClauseSyntax).ToArray() Assert.Equal(2, aliases.Length) Dim alias1 = model.GetDeclaredSymbol(aliases(0)) Assert.NotNull(alias1) Assert.Equal("System", alias1.Target.ToTestDisplayString()) Dim alias2 = model.GetDeclaredSymbol(aliases(1)) Assert.NotNull(alias2) Assert.Equal("System.IO", alias2.Target.ToTestDisplayString()) Assert.NotEqual(alias1.Locations.Single(), alias2.Locations.Single()) ' This symbol we re-use. Dim alias1b = model.GetDeclaredSymbol(aliases(0)) Assert.Same(alias1, alias1b) ' This symbol we generate on-demand. Dim alias2b = model.GetDeclaredSymbol(aliases(1)) Assert.NotSame(alias2, alias2b) Assert.Equal(alias2, alias2b) End Sub <Fact()> Public Sub StaticLocals() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class C Public Function goo() As Integer Static i As Integer = 23 i = i + 1 Return i End Function Public Shared Sub Main() End Sub End Class ]]></file> </compilation>) Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim staticLocals = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of LocalDeclarationStatementSyntax).ToArray() Assert.Equal(1, staticLocals.Length) Dim SLDeclaration As LocalDeclarationStatementSyntax = staticLocals(0) 'Static Locals are Not Supported for this API Assert.Throws(Of NotSupportedException)(Sub() Dim i = model.GetDeclaredSymbolFromSyntaxNode(SLDeclaration) End Sub) Dim containingType = DirectCast(model, SemanticModel).GetEnclosingSymbol(SLDeclaration.SpanStart) Assert.Equal("Function C.goo() As System.Int32", DirectCast(containingType, Symbol).ToTestDisplayString()) 'GetSymbolInfo 'GetSpeculativeSymbolInfo() 'GetTypeInfo() Dim TI = DirectCast(model, SemanticModel).GetTypeInfo(SLDeclaration) Dim mG = DirectCast(model, SemanticModel).GetAliasInfo(SLDeclaration) Dim lus1 = DirectCast(model, SemanticModel).LookupSymbols(SLDeclaration.SpanStart, name:="i") 'GetAliasImports - only applicable for Imports statements 'ConstantValue End Sub <WorkItem(530631, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530631")> <Fact()> Public Sub Bug16603() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Module Program Sub Main() Dim x As Action = Sub() x = Sub(, y = x End Sub End Module ]]></file> </compilation>) Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim identifiers = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of IdentifierNameSyntax).ToArray() Assert.Equal(4, identifiers.Length) Dim id As IdentifierNameSyntax = identifiers(3) ' No crashes Dim ai = DirectCast(model, SemanticModel).GetAliasInfo(id) Dim si = DirectCast(model, SemanticModel).GetSymbolInfo(id) End Sub <WorkItem(543278, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543278")> <Fact()> Public Sub ModuleNameInObjectCreationExpr() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Module Program Sub Main(args As String()) Dim x1 = New Program() 'BIND:"Program" End Sub End Module ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticSummary.Type) Assert.Null(semanticSummary.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Null(semanticSummary.Symbol) Assert.Equal(CandidateReason.NotCreatable, semanticSummary.CandidateReason) Assert.Null(semanticSummary.Alias) Assert.Equal(1, semanticSummary.CandidateSymbols.Length) Dim sortedCandidates = semanticSummary.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Program", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, sortedCandidates(0).Kind) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact()> Public Sub ModuleNameInObjectCreationExpr2() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Module Program Sub Main(args As String()) Dim x1 = New Program() 'BIND:"New Program()" End Sub End Module ]]></file> </compilation>) compilation.AssertTheseDiagnostics(<expected> BC35000: Requested operation is not available because the runtime library function 'Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute..ctor' is not defined. Module Program ~~~~~~~ BC30371: Module 'Program' cannot be used as a type. Dim x1 = New Program() 'BIND:"New Program()" ~~~~~~~ </expected>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of ObjectCreationExpressionSyntax)(compilation, "a.vb") Assert.Equal("Program", semanticSummary.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Module, semanticSummary.Type.TypeKind) Assert.Equal("Program", semanticSummary.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Module, semanticSummary.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Null(semanticSummary.Symbol) Assert.Equal(CandidateReason.None, semanticSummary.CandidateReason) Assert.Null(semanticSummary.Alias) Assert.Equal(0, semanticSummary.CandidateSymbols.Length) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact()> Public Sub ClassWithInaccessibleConstructorsInObjectCreationExpr() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class C1 private sub new() end Sub end class Module Program Sub Main(args As String()) Dim x1 = New C1() 'BIND:"C1" End Sub public mustinherit class Goo public sub new() end sub end class End Module ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticSummary.Type) Assert.Null(semanticSummary.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Equal("C1", semanticSummary.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, semanticSummary.CandidateReason) Assert.Null(semanticSummary.Alias) Assert.Equal(0, semanticSummary.CandidateSymbols.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact()> Public Sub ClassWithInaccessibleConstructorsInObjectCreationExpr2() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class C1 private sub new() end Sub end class Module Program Sub Main(args As String()) Dim x1 = New C1() 'BIND:"New C1()" End Sub public mustinherit class Goo public sub new() end sub end class End Module ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of ObjectCreationExpressionSyntax)(compilation, "a.vb") Assert.Equal("C1", semanticSummary.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.Type.TypeKind) Assert.Null(semanticSummary.Symbol) Assert.Equal(CandidateReason.Inaccessible, semanticSummary.CandidateReason) Assert.Null(semanticSummary.Alias) Assert.Equal(1, semanticSummary.CandidateSymbols.Length) Assert.Equal("Sub C1..ctor()", semanticSummary.CandidateSymbols(0).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, semanticSummary.CandidateSymbols(0).Kind) Assert.False(semanticSummary.ConstantValue.HasValue) Assert.Equal(1, semanticSummary.MemberGroup.Length) Assert.Equal("Sub C1..ctor()", semanticSummary.MemberGroup(0).ToTestDisplayString()) End Sub <WorkItem(542844, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542844")> <Fact()> Public Sub Bug10246() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class C(Of T) Public Field As T End Class Class D Sub M() Call New C(Of Integer).Field.ToString() 'BIND1:"Field" End Sub End Class ]]></file> </compilation>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel1 = compilation.GetSemanticModel(tree) Dim node1 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1) Dim symbolInfo = semanticModel1.GetSymbolInfo(node1) Assert.Equal(CandidateReason.NotATypeOrNamespace, symbolInfo.CandidateReason) Assert.Equal(1, symbolInfo.CandidateSymbols.Length) Assert.Equal("C(Of System.Int32).Field As System.Int32", symbolInfo.CandidateSymbols(0).ToTestDisplayString()) Assert.Null(symbolInfo.Symbol) End Sub <WorkItem(530093, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530093")> <Fact()> Public Sub Bug530093() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class C Public Shared Field As C = Me 'BIND1:"Me" End Class ]]></file> </compilation>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel1 = compilation.GetSemanticModel(tree) Dim node1 As ExpressionSyntax = CompilationUtils.FindBindingText(Of ExpressionSyntax)(compilation, "a.vb", 1) Dim symbolInfo = semanticModel1.GetSymbolInfo(node1) Assert.Equal(CandidateReason.StaticInstanceMismatch, symbolInfo.CandidateReason) Assert.Equal(1, symbolInfo.CandidateSymbols.Length) Assert.Equal("Me As C", symbolInfo.CandidateSymbols(0).ToTestDisplayString()) Assert.Null(symbolInfo.Symbol) End Sub <WorkItem(530093, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530093")> <Fact()> Public Sub Bug530093b() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class C Public Shared Field As Object = MyBase 'BIND1:"MyBase" End Class ]]></file> </compilation>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel1 = compilation.GetSemanticModel(tree) Dim node1 As ExpressionSyntax = CompilationUtils.FindBindingText(Of ExpressionSyntax)(compilation, "a.vb", 1) Dim symbolInfo = semanticModel1.GetSymbolInfo(node1) Assert.Equal(CandidateReason.StaticInstanceMismatch, symbolInfo.CandidateReason) Assert.Equal(1, symbolInfo.CandidateSymbols.Length) Assert.Equal("Me As C", symbolInfo.CandidateSymbols(0).ToTestDisplayString()) Assert.Null(symbolInfo.Symbol) End Sub <Fact()> Public Sub NewOfModule() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Module Program Sub Main(args As String()) Dim a As Object = New X()'BIND:"X" End Sub End Module Module X End Module ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticSummary.Type) Assert.Null(semanticSummary.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Null(semanticSummary.Symbol) Assert.Equal(CandidateReason.NotCreatable, semanticSummary.CandidateReason) Assert.Equal(1, semanticSummary.CandidateSymbols.Length) Assert.Equal("X", semanticSummary.CandidateSymbols(0).ToTestDisplayString()) Assert.Null(semanticSummary.Alias) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact()> Public Sub NewOfModule2() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Module Program Sub Main(args As String()) Dim a As Object = New X()'BIND:"New X()" End Sub End Module Module X End Module ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of ObjectCreationExpressionSyntax)(compilation, "a.vb") Assert.Equal("X", semanticSummary.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Module, semanticSummary.Type.TypeKind) Assert.Equal("System.Object", semanticSummary.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.ConvertedType.TypeKind) Assert.Equal(ConversionKind.WideningReference, semanticSummary.ImplicitConversion.Kind) Assert.Null(semanticSummary.Symbol) Assert.Equal(CandidateReason.None, semanticSummary.CandidateReason) Assert.Equal(0, semanticSummary.CandidateSymbols.Length) Assert.Null(semanticSummary.Alias) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact()> Public Sub NewOfInterface() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Module Program Sub Main(args As String()) Dim a As Object = New X()'BIND:"X" End Sub End Module Interface X End Interface ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticSummary.Type) Assert.Null(semanticSummary.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Null(semanticSummary.Symbol) Assert.Equal(CandidateReason.NotCreatable, semanticSummary.CandidateReason) Assert.Equal(1, semanticSummary.CandidateSymbols.Length) Assert.Equal("X", semanticSummary.CandidateSymbols(0).ToTestDisplayString()) Assert.Null(semanticSummary.Alias) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact()> Public Sub NewOfInterface2() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Module Program Sub Main(args As String()) Dim a As Object = New X()'BIND:"New X()" End Sub End Module Interface X End Interface ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of ObjectCreationExpressionSyntax)(compilation, "a.vb") Assert.Equal("X", semanticSummary.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Interface, semanticSummary.Type.TypeKind) Assert.Equal("System.Object", semanticSummary.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.ConvertedType.TypeKind) Assert.Equal(ConversionKind.WideningReference, semanticSummary.ImplicitConversion.Kind) Assert.Null(semanticSummary.Symbol) Assert.Equal(CandidateReason.None, semanticSummary.CandidateReason) Assert.Equal(0, semanticSummary.CandidateSymbols.Length) Assert.Null(semanticSummary.Alias) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact()> Public Sub NewOfNotCreatable() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Class C Sub F() Dim a As Object = New X()'BIND:"X" End Sub End Class MustInherit Class X End Class ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticSummary.Type) Assert.Null(semanticSummary.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Null(semanticSummary.Symbol) Assert.Equal(CandidateReason.NotCreatable, semanticSummary.CandidateReason) Assert.Equal(1, semanticSummary.CandidateSymbols.Length) Assert.Equal("X", semanticSummary.CandidateSymbols(0).ToTestDisplayString()) Assert.Null(semanticSummary.Alias) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact()> Public Sub NewOfNotCreatable2() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Class C Sub F() Dim a As Object = New X()'BIND:"New X()" End Sub End Class MustInherit Class X End Class ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of ObjectCreationExpressionSyntax)(compilation, "a.vb") Assert.Equal("X", semanticSummary.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.Type.TypeKind) Assert.Equal("System.Object", semanticSummary.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.ConvertedType.TypeKind) Assert.Equal(ConversionKind.WideningReference, semanticSummary.ImplicitConversion.Kind) Assert.Null(semanticSummary.Symbol) Assert.Equal(CandidateReason.Inaccessible, semanticSummary.CandidateReason) Assert.Equal(1, semanticSummary.CandidateSymbols.Length) Assert.Equal("Sub X..ctor()", semanticSummary.CandidateSymbols(0).ToTestDisplayString()) Assert.Null(semanticSummary.Alias) Assert.Equal(1, semanticSummary.MemberGroup.Length) Dim sortedMethodGroup = semanticSummary.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub X..ctor()", sortedMethodGroup(0).ToTestDisplayString()) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact(), WorkItem(665920, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/665920")> Public Sub NewOfNotCreatable3() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System MustInherit Class X Protected Sub New(x as integer) End Sub Protected Sub New(x as string) End Sub Sub F() Dim a As Object = New X()'BIND1:"New X()" End Sub End Class ]]></file> </compilation>) Dim model = GetSemanticModel(compilation, "a.vb") Dim creation As ObjectCreationExpressionSyntax = CompilationUtils.FindBindingText(Of ObjectCreationExpressionSyntax)(compilation, "a.vb", 1) Dim symbolInfo As SymbolInfo = model.GetSymbolInfo(creation.Type) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.NotCreatable, symbolInfo.CandidateReason) Assert.Equal(1, symbolInfo.CandidateSymbols.Count) Assert.Equal("X", symbolInfo.CandidateSymbols(0).ToTestDisplayString()) Dim memberGroup = model.GetMemberGroup(creation.Type) Assert.Equal(0, memberGroup.Count) Dim typeInfo As TypeInfo = model.GetTypeInfo(creation.Type) Assert.Null(typeInfo.Type) Assert.Null(typeInfo.ConvertedType) Dim conv = model.GetConversion(creation.Type) Assert.True(conv.IsIdentity) memberGroup = model.GetMemberGroup(creation) Dim sortedMethodGroup As ISymbol() = memberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal(2, sortedMethodGroup.Length) Assert.Equal("Sub X..ctor(x As System.Int32)", sortedMethodGroup(0).ToTestDisplayString()) Assert.Equal("Sub X..ctor(x As System.String)", sortedMethodGroup(1).ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(creation) Assert.Null(symbolInfo.Symbol) sortedMethodGroup = symbolInfo.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal(2, sortedMethodGroup.Length) Assert.Equal("Sub X..ctor(x As System.Int32)", sortedMethodGroup(0).ToTestDisplayString()) Assert.Equal("Sub X..ctor(x As System.String)", sortedMethodGroup(1).ToTestDisplayString()) Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason) typeInfo = model.GetTypeInfo(creation) Assert.Equal("X", typeInfo.Type.ToTestDisplayString()) Assert.Equal("System.Object", typeInfo.ConvertedType.ToTestDisplayString()) conv = model.GetConversion(creation) Assert.Equal(ConversionKind.WideningReference, conv.Kind) End Sub <Fact(), WorkItem(665920, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/665920")> Public Sub NewOfNotCreatable4() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System MustInherit Class X Protected Sub New(x as integer) End Sub Protected Sub New(x as string) End Sub Sub F() Dim a As Object = New X(1)'BIND1:"New X(1)" End Sub End Class ]]></file> </compilation>) Dim model = GetSemanticModel(compilation, "a.vb") Dim creation As ObjectCreationExpressionSyntax = CompilationUtils.FindBindingText(Of ObjectCreationExpressionSyntax)(compilation, "a.vb", 1) Dim symbolInfo As SymbolInfo = model.GetSymbolInfo(creation.Type) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.NotCreatable, symbolInfo.CandidateReason) Assert.Equal(1, symbolInfo.CandidateSymbols.Count) Assert.Equal("X", symbolInfo.CandidateSymbols(0).ToTestDisplayString()) Dim memberGroup = model.GetMemberGroup(creation.Type) Assert.Equal(0, memberGroup.Count) Dim typeInfo As TypeInfo = model.GetTypeInfo(creation.Type) Assert.Null(typeInfo.Type) Assert.Null(typeInfo.ConvertedType) Dim conv = model.GetConversion(creation.Type) Assert.True(conv.IsIdentity) memberGroup = model.GetMemberGroup(creation) Dim sortedMethodGroup = memberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal(2, sortedMethodGroup.Length) Assert.Equal("Sub X..ctor(x As System.Int32)", sortedMethodGroup(0).ToTestDisplayString()) Assert.Equal("Sub X..ctor(x As System.String)", sortedMethodGroup(1).ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(creation) Assert.Equal("Sub X..ctor(x As System.Int32)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) typeInfo = model.GetTypeInfo(creation) Assert.Equal("X", typeInfo.Type.ToTestDisplayString()) Assert.Equal("System.Object", typeInfo.ConvertedType.ToTestDisplayString()) conv = model.GetConversion(creation) Assert.Equal(ConversionKind.WideningReference, conv.Kind) End Sub <Fact(), WorkItem(665920, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/665920")> Public Sub NewOfNotCreatable5() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Class C Sub F() Dim a As Object = New X(1)'BIND1:"New X(1)" End Sub End Class MustInherit Class X Protected Sub New(x as integer) End Sub Protected Sub New(x as string) End Sub End Class ]]></file> </compilation>) Dim model = GetSemanticModel(compilation, "a.vb") Dim creation As ObjectCreationExpressionSyntax = CompilationUtils.FindBindingText(Of ObjectCreationExpressionSyntax)(compilation, "a.vb", 1) Dim symbolInfo As SymbolInfo = model.GetSymbolInfo(creation.Type) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.NotCreatable, symbolInfo.CandidateReason) Assert.Equal(1, symbolInfo.CandidateSymbols.Count) Assert.Equal("X", symbolInfo.CandidateSymbols(0).ToTestDisplayString()) Dim memberGroup = model.GetMemberGroup(creation.Type) Assert.Equal(0, memberGroup.Count) Dim typeInfo As TypeInfo = model.GetTypeInfo(creation.Type) Assert.Null(typeInfo.Type) Assert.Null(typeInfo.ConvertedType) Dim conv = model.GetConversion(creation.Type) Assert.True(conv.IsIdentity) memberGroup = model.GetMemberGroup(creation) Dim sortedMethodGroup = memberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal(2, sortedMethodGroup.Length) Assert.Equal("Sub X..ctor(x As System.Int32)", sortedMethodGroup(0).ToTestDisplayString()) Assert.Equal("Sub X..ctor(x As System.String)", sortedMethodGroup(1).ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(creation) Assert.Null(symbolInfo.Symbol) Assert.Equal(1, symbolInfo.CandidateSymbols.Length) Assert.Equal("Sub X..ctor(x As System.Int32)", symbolInfo.CandidateSymbols(0).ToTestDisplayString()) Assert.Equal(CandidateReason.Inaccessible, symbolInfo.CandidateReason) typeInfo = model.GetTypeInfo(creation) Assert.Equal("X", typeInfo.Type.ToTestDisplayString()) Assert.Equal("System.Object", typeInfo.ConvertedType.ToTestDisplayString()) conv = model.GetConversion(creation) Assert.Equal(ConversionKind.WideningReference, conv.Kind) End Sub <Fact(), WorkItem(665920, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/665920")> Public Sub NewOfNotCreatable6() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Class C Sub F() Dim a As Object = New X()'BIND1:"New X()" End Sub End Class MustInherit Class X Protected Sub New(x as integer) End Sub Protected Sub New(x as string) End Sub End Class ]]></file> </compilation>) Dim model = GetSemanticModel(compilation, "a.vb") Dim creation As ObjectCreationExpressionSyntax = CompilationUtils.FindBindingText(Of ObjectCreationExpressionSyntax)(compilation, "a.vb", 1) Dim symbolInfo As SymbolInfo = model.GetSymbolInfo(creation.Type) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.NotCreatable, symbolInfo.CandidateReason) Assert.Equal(1, symbolInfo.CandidateSymbols.Count) Assert.Equal("X", symbolInfo.CandidateSymbols(0).ToTestDisplayString()) Dim memberGroup = model.GetMemberGroup(creation.Type) Assert.Equal(0, memberGroup.Count) Dim typeInfo As TypeInfo = model.GetTypeInfo(creation.Type) Assert.Null(typeInfo.Type) Assert.Null(typeInfo.ConvertedType) Dim conv = model.GetConversion(creation.Type) Assert.True(conv.IsIdentity) memberGroup = model.GetMemberGroup(creation) Dim sortedMethodGroup As ISymbol() = memberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal(2, sortedMethodGroup.Length) Assert.Equal("Sub X..ctor(x As System.Int32)", sortedMethodGroup(0).ToTestDisplayString()) Assert.Equal("Sub X..ctor(x As System.String)", sortedMethodGroup(1).ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(creation) Assert.Null(symbolInfo.Symbol) sortedMethodGroup = symbolInfo.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal(2, sortedMethodGroup.Length) Assert.Equal("Sub X..ctor(x As System.Int32)", sortedMethodGroup(0).ToTestDisplayString()) Assert.Equal("Sub X..ctor(x As System.String)", sortedMethodGroup(1).ToTestDisplayString()) Assert.Equal(CandidateReason.Inaccessible, symbolInfo.CandidateReason) typeInfo = model.GetTypeInfo(creation) Assert.Equal("X", typeInfo.Type.ToTestDisplayString()) Assert.Equal("System.Object", typeInfo.ConvertedType.ToTestDisplayString()) conv = model.GetConversion(creation) Assert.Equal(ConversionKind.WideningReference, conv.Kind) End Sub <Fact(), WorkItem(665920, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/665920")> Public Sub NewOfNotCreatable7() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System MustInherit Class X Protected Sub New(x as integer) End Sub Sub F() Dim a As Object = New X()'BIND1:"New X()" End Sub End Class ]]></file> </compilation>) Dim model = GetSemanticModel(compilation, "a.vb") Dim creation As ObjectCreationExpressionSyntax = CompilationUtils.FindBindingText(Of ObjectCreationExpressionSyntax)(compilation, "a.vb", 1) Dim symbolInfo As SymbolInfo = model.GetSymbolInfo(creation.Type) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.NotCreatable, symbolInfo.CandidateReason) Assert.Equal(1, symbolInfo.CandidateSymbols.Count) Assert.Equal("X", symbolInfo.CandidateSymbols(0).ToTestDisplayString()) Dim memberGroup = model.GetMemberGroup(creation.Type) Assert.Equal(0, memberGroup.Count) Dim typeInfo As TypeInfo = model.GetTypeInfo(creation.Type) Assert.Null(typeInfo.Type) Assert.Null(typeInfo.ConvertedType) Dim conv = model.GetConversion(creation.Type) Assert.True(conv.IsIdentity) memberGroup = model.GetMemberGroup(creation) Dim sortedMethodGroup = memberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal(1, sortedMethodGroup.Length) Assert.Equal("Sub X..ctor(x As System.Int32)", sortedMethodGroup(0).ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(creation) Assert.Null(symbolInfo.Symbol) Assert.Equal(1, symbolInfo.CandidateSymbols.Length) Assert.Equal("Sub X..ctor(x As System.Int32)", symbolInfo.CandidateSymbols(0).ToTestDisplayString()) Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason) typeInfo = model.GetTypeInfo(creation) Assert.Equal("X", typeInfo.Type.ToTestDisplayString()) Assert.Equal("System.Object", typeInfo.ConvertedType.ToTestDisplayString()) conv = model.GetConversion(creation) Assert.Equal(ConversionKind.WideningReference, conv.Kind) End Sub <Fact()> Public Sub NewOfUnconstrainedTypeParameter() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Class C(Of T) Sub F() Dim a As Object = New T()'BIND:"T" End Sub End Class ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticSummary.Type) Assert.Null(semanticSummary.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Null(semanticSummary.Symbol) Assert.Equal(CandidateReason.NotCreatable, semanticSummary.CandidateReason) Assert.Equal(1, semanticSummary.CandidateSymbols.Length) Assert.Equal("T", semanticSummary.CandidateSymbols(0).ToTestDisplayString()) Assert.Null(semanticSummary.Alias) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact()> Public Sub NewOfUnconstrainedTypeParameter2() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Class C(Of T) Sub F() Dim a As Object = New T()'BIND:"New T()" End Sub End Class ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of ObjectCreationExpressionSyntax)(compilation, "a.vb") Assert.Equal("T", semanticSummary.Type.ToTestDisplayString()) Assert.Equal(TypeKind.TypeParameter, semanticSummary.Type.TypeKind) Assert.Null(semanticSummary.Symbol) Assert.Equal(CandidateReason.None, semanticSummary.CandidateReason) Assert.Equal(0, semanticSummary.CandidateSymbols.Length) Assert.Null(semanticSummary.Alias) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <WorkItem(543534, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543534")> <Fact()> Public Sub InterfaceCreationExpression() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Interface I Property X() As Integer End Interface Class Program Private Shared Sub Main() Dim x = New I()'BIND:"I" End Sub End Class ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Null(semanticSummary.Type) Assert.Null(semanticSummary.ConvertedType) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Null(semanticSummary.Symbol) Assert.Equal(CandidateReason.NotCreatable, semanticSummary.CandidateReason) Assert.Equal(1, semanticSummary.CandidateSymbols.Length) Dim sortedCandidates = semanticSummary.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("I", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, sortedCandidates(0).Kind) Assert.Null(semanticSummary.Alias) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <Fact()> Public Sub InterfaceCreationExpression2() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Interface I Property X() As Integer End Interface Class Program Private Shared Sub Main() Dim x = New I()'BIND:"New I()" End Sub End Class ]]></file> </compilation>) compilation.AssertTheseDiagnostics(<expected> BC30375: 'New' cannot be used on an interface. Dim x = New I()'BIND:"New I()" ~~~~~~~ </expected>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of ObjectCreationExpressionSyntax)(compilation, "a.vb") Assert.Equal("I", semanticSummary.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Interface, semanticSummary.Type.TypeKind) Assert.Equal("I", semanticSummary.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Interface, semanticSummary.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Null(semanticSummary.Symbol) Assert.Equal(CandidateReason.None, semanticSummary.CandidateReason) Assert.Equal(0, semanticSummary.CandidateSymbols.Length) Assert.Null(semanticSummary.Alias) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <WorkItem(543515, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543515")> <ConditionalFact(GetType(WindowsOnly), Reason:="https://github.com/dotnet/roslyn/issues/29531")> Public Sub AliasAttributeName() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ imports A = A1 Class A1 Inherits System.Attribute End Class <A> 'BIND:"A" Class C End Class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("A1", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.[Class], semanticInfo.Type.TypeKind) Assert.Equal("A1", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.[Class], semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Sub A1..ctor()", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(1, semanticInfo.MemberGroup.Length) Dim sortedMethodGroup = semanticInfo.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub A1..ctor()", sortedMethodGroup(0).ToTestDisplayString()) Assert.False(semanticInfo.ConstantValue.HasValue) Dim aliasInfo = GetAliasInfoForTest(compilation, "a.vb") Assert.NotNull(aliasInfo) Assert.Equal("A=A1", aliasInfo.ToTestDisplayString()) Assert.Equal(SymbolKind.[Alias], aliasInfo.Kind) End Sub <WorkItem(543515, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543515")> <ConditionalFact(GetType(WindowsOnly), Reason:="https://github.com/dotnet/roslyn/issues/29531")> Public Sub AliasAttributeName_02_AttributeSyntax() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ imports GooAttribute = System.ObsoleteAttribute <Goo> 'BIND:"Goo" Class C End Class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of AttributeSyntax)(compilation, "a.vb") Assert.Equal("System.ObsoleteAttribute", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.[Class], semanticInfo.Type.TypeKind) Assert.Equal("System.ObsoleteAttribute", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.[Class], semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Sub System.ObsoleteAttribute..ctor()", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(3, semanticInfo.MemberGroup.Length) Dim sortedMethodGroup = semanticInfo.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString(), StringComparer.Ordinal).ToArray() Assert.Equal("Sub System.ObsoleteAttribute..ctor()", sortedMethodGroup(0).ToTestDisplayString()) Assert.Equal("Sub System.ObsoleteAttribute..ctor(message As System.String)", sortedMethodGroup(1).ToTestDisplayString()) Assert.Equal("Sub System.ObsoleteAttribute..ctor(message As System.String, [error] As System.Boolean)", sortedMethodGroup(2).ToTestDisplayString()) Assert.[False](semanticInfo.ConstantValue.HasValue) Dim aliasInfo = GetAliasInfoForTest(compilation, "a.vb") Assert.NotNull(aliasInfo) Assert.Equal("GooAttribute=System.ObsoleteAttribute", aliasInfo.ToTestDisplayString()) Assert.Equal(SymbolKind.[Alias], aliasInfo.Kind) End Sub <WorkItem(543515, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543515")> <ConditionalFact(GetType(WindowsOnly), Reason:="https://github.com/dotnet/roslyn/issues/29531")> Public Sub AliasAttributeName_02_IdentifierNameSyntax() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ imports GooAttribute = System.ObsoleteAttribute <Goo> 'BIND:"Goo" Class C End Class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("System.ObsoleteAttribute", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.[Class], semanticInfo.Type.TypeKind) Assert.Equal("System.ObsoleteAttribute", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.[Class], semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Sub System.ObsoleteAttribute..ctor()", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(3, semanticInfo.MemberGroup.Length) Dim sortedMethodGroup = semanticInfo.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString(), StringComparer.Ordinal).ToArray() Assert.Equal("Sub System.ObsoleteAttribute..ctor()", sortedMethodGroup(0).ToTestDisplayString()) Assert.Equal("Sub System.ObsoleteAttribute..ctor(message As System.String)", sortedMethodGroup(1).ToTestDisplayString()) Assert.Equal("Sub System.ObsoleteAttribute..ctor(message As System.String, [error] As System.Boolean)", sortedMethodGroup(2).ToTestDisplayString()) Assert.[False](semanticInfo.ConstantValue.HasValue) Dim aliasInfo = GetAliasInfoForTest(compilation, "a.vb") Assert.NotNull(aliasInfo) Assert.Equal("GooAttribute=System.ObsoleteAttribute", aliasInfo.ToTestDisplayString()) Assert.Equal(SymbolKind.[Alias], aliasInfo.Kind) End Sub <WorkItem(543515, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543515")> <ConditionalFact(GetType(WindowsOnly), Reason:="https://github.com/dotnet/roslyn/issues/29531")> Public Sub AliasAttributeName_03_AttributeSyntax() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ imports GooAttribute = System.ObsoleteAttribute <GooAttribute> 'BIND:"GooAttribute" Class C End Class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of AttributeSyntax)(compilation, "a.vb") Assert.Equal("System.ObsoleteAttribute", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.[Class], semanticInfo.Type.TypeKind) Assert.Equal("System.ObsoleteAttribute", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.[Class], semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Sub System.ObsoleteAttribute..ctor()", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(3, semanticInfo.MemberGroup.Length) Dim sortedMethodGroup = semanticInfo.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString(), StringComparer.Ordinal).ToArray() Assert.Equal("Sub System.ObsoleteAttribute..ctor()", sortedMethodGroup(0).ToTestDisplayString()) Assert.Equal("Sub System.ObsoleteAttribute..ctor(message As System.String)", sortedMethodGroup(1).ToTestDisplayString()) Assert.Equal("Sub System.ObsoleteAttribute..ctor(message As System.String, [error] As System.Boolean)", sortedMethodGroup(2).ToTestDisplayString()) Assert.[False](semanticInfo.ConstantValue.HasValue) Dim aliasInfo = GetAliasInfoForTest(compilation, "a.vb") Assert.NotNull(aliasInfo) Assert.Equal("GooAttribute=System.ObsoleteAttribute", aliasInfo.ToTestDisplayString()) Assert.Equal(SymbolKind.[Alias], aliasInfo.Kind) End Sub <WorkItem(543515, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543515")> <ConditionalFact(GetType(WindowsOnly), Reason:="https://github.com/dotnet/roslyn/issues/29531")> Public Sub AliasAttributeName_03_IdentifierNameSyntax() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ imports GooAttribute = System.ObsoleteAttribute <GooAttribute> 'BIND:"GooAttribute" Class C End Class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("System.ObsoleteAttribute", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.[Class], semanticInfo.Type.TypeKind) Assert.Equal("System.ObsoleteAttribute", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.[Class], semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Sub System.ObsoleteAttribute..ctor()", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(3, semanticInfo.MemberGroup.Length) Dim sortedMethodGroup = semanticInfo.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString(), StringComparer.Ordinal).ToArray() Assert.Equal("Sub System.ObsoleteAttribute..ctor()", sortedMethodGroup(0).ToTestDisplayString()) Assert.Equal("Sub System.ObsoleteAttribute..ctor(message As System.String)", sortedMethodGroup(1).ToTestDisplayString()) Assert.Equal("Sub System.ObsoleteAttribute..ctor(message As System.String, [error] As System.Boolean)", sortedMethodGroup(2).ToTestDisplayString()) Assert.[False](semanticInfo.ConstantValue.HasValue) Dim aliasInfo = GetAliasInfoForTest(compilation, "a.vb") Assert.NotNull(aliasInfo) Assert.Equal("GooAttribute=System.ObsoleteAttribute", aliasInfo.ToTestDisplayString()) Assert.Equal(SymbolKind.[Alias], aliasInfo.Kind) End Sub <WorkItem(543515, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543515")> <Fact()> Public Sub AliasQualifiedAttributeName_01() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ namespace N <global.AttributeClass.SomeClass()> 'BIND:"AttributeClass" class C end class class AttributeClass inherits System.Attribute end class end namespace class AttributeClass inherits System.Attribute class SomeClass end class end class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("AttributeClass", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.[Class], semanticInfo.Type.TypeKind) Assert.Equal("AttributeClass", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.[Class], semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("AttributeClass", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.[False](semanticInfo.ConstantValue.HasValue) Assert.[False](SyntaxFacts.IsAttributeName((DirectCast(semanticInfo.Symbol, SourceNamedTypeSymbol)).SyntaxReferences.First().GetSyntax()), "IsAttributeName can be true only for alias name being qualified") End Sub <Fact()> Public Sub AliasQualifiedAttributeName_02() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ namespace N <global.AttributeClass.SomeClass()> 'BIND:"global.AttributeClass" class C end class class AttributeClass inherits System.Attribute end class end namespace class AttributeClass inherits System.Attribute class SomeClass end class end class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of QualifiedNameSyntax)(compilation, "a.vb") Assert.Equal("AttributeClass", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.[Class], semanticInfo.Type.TypeKind) Assert.Equal("AttributeClass", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.[Class], semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("AttributeClass", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.[False](semanticInfo.ConstantValue.HasValue) Assert.[False](SyntaxFacts.IsAttributeName((DirectCast(semanticInfo.Symbol, SourceNamedTypeSymbol)).SyntaxReferences.First().GetSyntax()), "IsAttributeName can be true only for alias name being qualified") End Sub <Fact()> Public Sub AliasQualifiedAttributeName_03() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ namespace N <global.AttributeClass.SomeClass()> 'BIND:"SomeClass" class C end class class AttributeClass inherits System.Attribute end class end namespace class AttributeClass inherits System.Attribute class SomeClass end class end class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("AttributeClass.SomeClass", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.[Class], semanticInfo.Type.TypeKind) Assert.Equal("AttributeClass.SomeClass", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.[Class], semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.NotAnAttributeType, semanticInfo.CandidateReason) Assert.Equal(1, semanticInfo.CandidateSymbols.Length) Dim sortedCandidates = semanticInfo.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub AttributeClass.SomeClass..ctor()", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(0).Kind) Assert.Equal(1, semanticInfo.MemberGroup.Length) Dim sortedMethodGroup = semanticInfo.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub AttributeClass.SomeClass..ctor()", sortedMethodGroup(0).ToTestDisplayString()) Assert.[False](semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub AliasQualifiedAttributeName_04() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ namespace N <global.AttributeClass.SomeClass()> 'BIND:"global.AttributeClass.SomeClass" class C end class class AttributeClass inherits System.Attribute end class end namespace class AttributeClass inherits System.Attribute class SomeClass end class end class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of QualifiedNameSyntax)(compilation, "a.vb") Assert.Equal("AttributeClass.SomeClass", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.[Class], semanticInfo.Type.TypeKind) Assert.Equal("AttributeClass.SomeClass", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.[Class], semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.NotAnAttributeType, semanticInfo.CandidateReason) Assert.Equal(1, semanticInfo.CandidateSymbols.Length) Dim sortedCandidates = semanticInfo.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub AttributeClass.SomeClass..ctor()", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(0).Kind) Assert.Equal(1, semanticInfo.MemberGroup.Length) Dim sortedMethodGroup = semanticInfo.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub AttributeClass.SomeClass..ctor()", sortedMethodGroup(0).ToTestDisplayString()) Assert.[False](semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub AliasAttributeName_NonAttributeAlias() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ imports GooAttribute = C <GooAttribute> 'BIND:"GooAttribute" Class C end class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("C", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.[Class], semanticInfo.Type.TypeKind) Assert.Equal("C", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.[Class], semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.NotAnAttributeType, semanticInfo.CandidateReason) Assert.Equal(1, semanticInfo.CandidateSymbols.Length) Dim sortedCandidates = semanticInfo.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub C..ctor()", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(0).Kind) Assert.Equal(1, semanticInfo.MemberGroup.Length) Dim sortedMethodGroup = semanticInfo.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub C..ctor()", sortedMethodGroup(0).ToTestDisplayString()) Assert.[False](semanticInfo.ConstantValue.HasValue) Dim aliasInfo = GetAliasInfoForTest(compilation, "a.vb") Assert.Null(aliasInfo) End Sub <Fact()> Public Sub AliasAttributeName_NonAttributeAlias_GenericType() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ imports GooAttribute = Gen(of Integer) <GooAttribute> 'BIND:"GooAttribute" Class Gen(of T) end class ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("Gen(Of System.Int32)", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.[Class], semanticInfo.Type.TypeKind) Assert.Equal("Gen(Of System.Int32)", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.[Class], semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.NotAnAttributeType, semanticInfo.CandidateReason) Assert.Equal(1, semanticInfo.CandidateSymbols.Length) Dim sortedCandidates = semanticInfo.CandidateSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub Gen(Of System.Int32)..ctor()", sortedCandidates(0).ToTestDisplayString()) Assert.Equal(SymbolKind.Method, sortedCandidates(0).Kind) Assert.Equal(1, semanticInfo.MemberGroup.Length) Dim sortedMethodGroup = semanticInfo.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray() Assert.Equal("Sub Gen(Of System.Int32)..ctor()", sortedMethodGroup(0).ToTestDisplayString()) Assert.[False](semanticInfo.ConstantValue.HasValue) Dim aliasInfo = GetAliasInfoForTest(compilation, "a.vb") Assert.Null(aliasInfo) End Sub <Fact(), WorkItem(545085, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545085")> Public Sub ColorColorBug13346() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Public Class Compilation Public Shared Function M(a As Integer) As Boolean Return False End Function End Class Friend Class Program2 Public ReadOnly Property Compilation As Compilation Get Return Nothing End Get End Property Public Sub Main() Dim x = Compilation.M(a:=123)'BIND:"Compilation" End Sub End Class ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("Compilation", semanticSummary.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.Type.TypeKind) Assert.Equal("Compilation", semanticSummary.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticSummary.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Equal("Compilation", semanticSummary.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, semanticSummary.Symbol.Kind) Assert.Equal(0, semanticSummary.CandidateSymbols.Length) Assert.Null(semanticSummary.Alias) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <WorkItem(529702, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529702")> <Fact()> Public Sub ColorColorBug14084() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class C Shared Sub Goo() End Sub End Class Class A(Of T As C) Class B Dim t As T Sub Goo() T.Goo()'BIND:"T" End Sub End Class End Class ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("T", semanticSummary.Type.ToTestDisplayString()) Assert.Equal(TypeKind.TypeParameter, semanticSummary.Type.TypeKind) Assert.Equal("T", semanticSummary.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.TypeParameter, semanticSummary.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind) Assert.Equal("A(Of T).B.t As T", semanticSummary.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Field, semanticSummary.Symbol.Kind) Assert.Equal(0, semanticSummary.CandidateSymbols.Length) Assert.Null(semanticSummary.Alias) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <WorkItem(546097, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546097")> <Fact()> Public Sub LambdaParametersAsOptional() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Module Test Sub Main() Dim s1 = Function(Optional x = 3) x > 5 'BIND:"3" End Sub End Module ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of LiteralExpressionSyntax)(compilation, "a.vb") Assert.Null(semanticSummary.Symbol) compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Module M Private Function F1() As Object Return Nothing End Function Private F2 = Function(Optional o = F1()) Nothing 'BIND:"F1" End Module ]]></file> </compilation>) semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of VisualBasicSyntaxNode)(compilation, "a.vb") CheckSymbol(semanticSummary.Symbol, "Function M.F1() As Object") End Sub <Fact()> Public Sub OptionalParameterOutsideType() ' Method. Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Sub M(Optional o As Object = 3) 'BIND:"3" End Sub ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of LiteralExpressionSyntax)(compilation, "a.vb") Assert.Null(semanticSummary.Symbol) ' Method with type arguments. compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Sub M(Of T)(Optional o As Object = 3) 'BIND:"3" End Sub ]]></file> </compilation>) semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of LiteralExpressionSyntax)(compilation, "a.vb") Assert.Null(semanticSummary.Symbol) ' Property. compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ ReadOnly Property P(Optional o As Object = 3) As Object 'BIND:"3" Get Return Nothing End Get End Property ]]></file> </compilation>) semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of LiteralExpressionSyntax)(compilation, "a.vb") Assert.Null(semanticSummary.Symbol) ' Event. compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Event E(Optional o As Object = 3) 'BIND:"3" ]]></file> </compilation>) semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of LiteralExpressionSyntax)(compilation, "a.vb") Assert.Null(semanticSummary.Symbol) End Sub <Fact> Public Sub ConstantUnevaluatedReceiver() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="a.vb"><![CDATA[ Class A Const F As Object = Nothing Function M() As Object Return Me.F End Function End Class ]]></file> </compilation>, references:=XmlReferences) compilation.AssertNoErrors() Dim tree = compilation.SyntaxTrees(0) Dim semanticModel = compilation.GetSemanticModel(tree) Dim expr = FindNodeOfTypeFromText(Of ExpressionSyntax)(tree, "Me") Dim info = semanticModel.GetSemanticInfoSummary(expr) CheckSymbol(info.Type, "A") End Sub <Fact> Public Sub CallUnevaluatedReceiver() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="a.vb"><![CDATA[ Class A Shared Function F() As Object Return Nothing End Function Function M() As Object Return Me.F() End Function End Class ]]></file> </compilation>, references:=XmlReferences) compilation.AssertNoErrors() Dim tree = compilation.SyntaxTrees(0) Dim semanticModel = compilation.GetSemanticModel(tree) Dim expr = FindNodeOfTypeFromText(Of ExpressionSyntax)(tree, "Me") Dim info = semanticModel.GetSemanticInfoSummary(expr) CheckSymbol(info.Type, "A") End Sub <Fact> Public Sub AddressOfUnevaluatedReceiver() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="a.vb"><![CDATA[ Class A Shared Sub M() End Sub Function F() As System.Action Return AddressOf (Me).M End Function End Class ]]></file> </compilation>, references:=XmlReferences) compilation.AssertNoErrors() Dim tree = compilation.SyntaxTrees(0) Dim semanticModel = compilation.GetSemanticModel(tree) Dim expr = FindNodeOfTypeFromText(Of ExpressionSyntax)(tree, "Me") Dim info = semanticModel.GetSemanticInfoSummary(expr) CheckSymbol(info.Type, "A") End Sub <Fact> Public Sub TypeExpressionUnevaluatedReceiver() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="a.vb"><![CDATA[ Class A Class B Friend Const F As Object = Nothing End Class Function M() As Object Return (Me.B).F End Function End Class ]]></file> </compilation>, references:=XmlReferences) compilation.AssertNoErrors() Dim tree = compilation.SyntaxTrees(0) Dim semanticModel = compilation.GetSemanticModel(tree) Dim expr = FindNodeOfTypeFromText(Of ExpressionSyntax)(tree, "Me") Dim info = semanticModel.GetSemanticInfoSummary(expr) CheckSymbol(info.Type, "A") End Sub ''' <summary> ''' SymbolInfo and TypeInfo should implement IEquatable&lt;T&gt;. ''' </summary> <WorkItem(792647, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/792647")> <Fact> Public Sub ImplementsIEquatable() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class C Function F() Return Me End Function End Class ]]></file> </compilation>) compilation.AssertNoErrors() Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim expr = FindNodeOfTypeFromText(Of ExpressionSyntax)(tree, "Me") Dim symbolInfo1 = model.GetSymbolInfo(expr) Dim symbolInfo2 = model.GetSymbolInfo(expr) Dim symbolComparer = DirectCast(symbolInfo1, IEquatable(Of SymbolInfo)) Assert.True(symbolComparer.Equals(symbolInfo2)) Dim typeInfo1 = model.GetTypeInfo(expr) Dim typeInfo2 = model.GetTypeInfo(expr) Dim typeComparer = DirectCast(typeInfo1, IEquatable(Of TypeInfo)) Assert.True(typeComparer.Equals(typeInfo2)) End Sub <Fact, WorkItem(2805, "https://github.com/dotnet/roslyn/issues/2805")> Public Sub AliasWithAnError() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Imports ShortName = LongNamespace Namespace NS Class Test Public Function Method1() As Object Return (New ShortName.Class1()).Prop End Function End Class End Namespace ]]></file> </compilation>, options:=TestOptions.DebugDll) compilation.AssertTheseDiagnostics(<expected> BC40056: Namespace or type specified in the Imports 'LongNamespace' 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 ShortName = LongNamespace ~~~~~~~~~~~~~ BC30002: Type 'ShortName.Class1' is not defined. Return (New ShortName.Class1()).Prop ~~~~~~~~~~~~~~~~ </expected>) Dim tree = compilation.SyntaxTrees.Single() Dim node = tree.GetRoot().DescendantNodes().OfType(Of IdentifierNameSyntax)().Where(Function(id) id.Identifier.ValueText = "ShortName").Single() Assert.Equal("ShortName.Class1", node.Parent.ToString()) Dim model = compilation.GetSemanticModel(tree) Dim [alias] = model.GetAliasInfo(node) Assert.Equal("ShortName=LongNamespace", [alias].ToTestDisplayString()) Assert.Equal(SymbolKind.ErrorType, [alias].Target.Kind) Assert.Equal("LongNamespace", [alias].Target.ToTestDisplayString()) Dim symbolInfo = model.GetSymbolInfo(node) Assert.Null(symbolInfo.Symbol) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) End Sub End Class End Namespace
1
dotnet/roslyn
56,011
React to string comparison changing on .NET Core
The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
jaredpar
"2021-08-30T17:18:52Z"
"2021-08-30T20:20:04Z"
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
4d99cda6e446e77dbb302e26388c1093bd3ef569
React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
./src/Compilers/VisualBasic/Test/Semantic/Semantics/NameLengthTests.vb
' 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.IO Imports Microsoft.CodeAnalysis.VisualBasic.Symbols 'Imports Microsoft.CodeAnalysis.VisualBasic.Test.Utilities Imports Roslyn.Test.Utilities Imports Xunit Imports Microsoft.Cci Imports System Imports System.Xml.Linq Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class NameLengthTests : Inherits BasicTestBase ' Longest legal symbol name. Private Shared ReadOnly s_longSymbolName As New String("A"c, MetadataWriter.NameLengthLimit) ' Longest legal path name. Private Shared ReadOnly s_longPathName As New String("A"c, MetadataWriter.PathLengthLimit) ' Longest legal local name. Private Shared ReadOnly s_longLocalName As New String("A"c, MetadataWriter.PdbLengthLimit) <Fact> Public Sub UnmangledMemberNames() Dim sourceTemplate = <![CDATA[ Imports System Class Fields Dim {0} As Integer ' Fine Dim {0}1 As Integer ' Too long End Class Class FieldLikeEvents Event {0} as Action ' Fine (except accessors) Event {0}1 as Action ' Fine (except accessors) End Class Class CustomEvents Custom Event {0} As Action ' Fine (except accessors) AddHandler(value As Action) End AddHandler RemoveHandler(value As Action) End RemoveHandler RaiseEvent() End RaiseEvent End Event Custom Event {0}1 As Action ' Too long AddHandler(value As Action) End AddHandler RemoveHandler(value As Action) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class Class AutoProperties Property {0} As Integer ' Fine (except accessors And backing field) Property {0}1 As Integer ' Too long End Class Class CustomProperties Property {0} As Integer ' Fine (except accessors) Get Return 0 End Get Set(value As Integer) End Set End Property Property {0}1 As Integer ' Too long Get Return 0 End Get Set(value As Integer) End Set End Property End Class Class Methods Sub {0}() ' Fine End Sub Sub {0}1() ' Too long End Sub End Class ]]> Dim _longSquiggle_ As New String("~"c, s_longSymbolName.Length) Dim source = Format(sourceTemplate, s_longSymbolName) Dim comp = CreateCompilationWithMscorlib(source) comp.AssertNoDiagnostics() comp.AssertTheseEmitDiagnostics(<errors> BC37220: Name '<%= s_longSymbolName %>1' exceeds the maximum length allowed in metadata. Dim <%= s_longSymbolName %>1 As Integer ' Too long <%= _longSquiggle_ %>~ BC37220: Name '<%= s_longSymbolName %>Event' exceeds the maximum length allowed in metadata. Event <%= s_longSymbolName %> as Action ' Fine (except accessors) <%= _longSquiggle_ %> BC37220: Name 'add_<%= s_longSymbolName %>' exceeds the maximum length allowed in metadata. Event <%= s_longSymbolName %> as Action ' Fine (except accessors) <%= _longSquiggle_ %> BC37220: Name 'remove_<%= s_longSymbolName %>' exceeds the maximum length allowed in metadata. Event <%= s_longSymbolName %> as Action ' Fine (except accessors) <%= _longSquiggle_ %> BC37220: Name '<%= s_longSymbolName %>1' exceeds the maximum length allowed in metadata. Event <%= s_longSymbolName %>1 as Action ' Fine (except accessors) <%= _longSquiggle_ %>~ BC37220: Name '<%= s_longSymbolName %>1Event' exceeds the maximum length allowed in metadata. Event <%= s_longSymbolName %>1 as Action ' Fine (except accessors) <%= _longSquiggle_ %>~ BC37220: Name 'add_<%= s_longSymbolName %>1' exceeds the maximum length allowed in metadata. Event <%= s_longSymbolName %>1 as Action ' Fine (except accessors) <%= _longSquiggle_ %>~ BC37220: Name 'remove_<%= s_longSymbolName %>1' exceeds the maximum length allowed in metadata. Event <%= s_longSymbolName %>1 as Action ' Fine (except accessors) <%= _longSquiggle_ %>~ BC37220: Name 'add_<%= s_longSymbolName %>' exceeds the maximum length allowed in metadata. AddHandler(value As Action) ~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37220: Name 'remove_<%= s_longSymbolName %>' exceeds the maximum length allowed in metadata. RemoveHandler(value As Action) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37220: Name 'raise_<%= s_longSymbolName %>' exceeds the maximum length allowed in metadata. RaiseEvent() ~~~~~~~~~~~~ BC37220: Name '<%= s_longSymbolName %>1' exceeds the maximum length allowed in metadata. Custom Event <%= s_longSymbolName %>1 As Action ' Too long <%= _longSquiggle_ %>~ BC37220: Name 'add_<%= s_longSymbolName %>1' exceeds the maximum length allowed in metadata. AddHandler(value As Action) ~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37220: Name 'remove_<%= s_longSymbolName %>1' exceeds the maximum length allowed in metadata. RemoveHandler(value As Action) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37220: Name 'raise_<%= s_longSymbolName %>1' exceeds the maximum length allowed in metadata. RaiseEvent() ~~~~~~~~~~~~ BC37220: Name '_<%= s_longSymbolName %>' exceeds the maximum length allowed in metadata. Property <%= s_longSymbolName %> As Integer ' Fine (except accessors And backing field) <%= _longSquiggle_ %> BC37220: Name 'get_<%= s_longSymbolName %>' exceeds the maximum length allowed in metadata. Property <%= s_longSymbolName %> As Integer ' Fine (except accessors And backing field) <%= _longSquiggle_ %> BC37220: Name 'set_<%= s_longSymbolName %>' exceeds the maximum length allowed in metadata. Property <%= s_longSymbolName %> As Integer ' Fine (except accessors And backing field) <%= _longSquiggle_ %> BC37220: Name '_<%= s_longSymbolName %>1' exceeds the maximum length allowed in metadata. Property <%= s_longSymbolName %>1 As Integer ' Too long <%= _longSquiggle_ %>~ BC37220: Name '<%= s_longSymbolName %>1' exceeds the maximum length allowed in metadata. Property <%= s_longSymbolName %>1 As Integer ' Too long <%= _longSquiggle_ %>~ BC37220: Name 'get_<%= s_longSymbolName %>1' exceeds the maximum length allowed in metadata. Property <%= s_longSymbolName %>1 As Integer ' Too long <%= _longSquiggle_ %>~ BC37220: Name 'set_<%= s_longSymbolName %>1' exceeds the maximum length allowed in metadata. Property <%= s_longSymbolName %>1 As Integer ' Too long <%= _longSquiggle_ %>~ BC37220: Name 'get_<%= s_longSymbolName %>' exceeds the maximum length allowed in metadata. Get ~~~ BC37220: Name 'set_<%= s_longSymbolName %>' exceeds the maximum length allowed in metadata. Set(value As Integer) ~~~ BC37220: Name '<%= s_longSymbolName %>1' exceeds the maximum length allowed in metadata. Property <%= s_longSymbolName %>1 As Integer ' Too long <%= _longSquiggle_ %>~ BC37220: Name 'get_<%= s_longSymbolName %>1' exceeds the maximum length allowed in metadata. Get ~~~ BC37220: Name 'set_<%= s_longSymbolName %>1' exceeds the maximum length allowed in metadata. Set(value As Integer) ~~~ BC37220: Name '<%= s_longSymbolName %>1' exceeds the maximum length allowed in metadata. Sub <%= s_longSymbolName %>1() ' Too long <%= _longSquiggle_ %>~ </errors>) End Sub <Fact> Public Sub EmptyNamespaces() Dim sourceTemplate = <![CDATA[ Namespace {0} ' Fine. End Namespace Namespace {0}1 ' Too long, but not checked. End Namespace ]]> Dim source = Format(sourceTemplate, s_longSymbolName) Dim comp = CreateCompilationWithMscorlib(source) comp.AssertNoDiagnostics() comp.AssertTheseEmitDiagnostics(<errors/>) End Sub <Fact> Public Sub NonGeneratedTypeNames() ' {n} == LongSymbolName.Substring(n) Dim sourceTemplate = <![CDATA[ Class {0} ' Fine End Class Class {0}1 ' Too long End Class Namespace N Structure {2} ' Fine End Structure Structure {2}1 ' Too long after prepending 'N.' End Structure End Namespace Class Outer Enum {0} ' Fine, since outer class is not prepended A End Enum Enum {0}1 ' Too long A End Enum End Class Interface {2}(Of T) ' Fine End Interface Interface {2}1(Of T) ' Too long after appending '`1' End Interface ]]> Dim substring0 = s_longSymbolName Dim substring1 = s_longSymbolName.Substring(1) Dim substring2 = s_longSymbolName.Substring(2) Dim _squiggle2 As New String("~"c, substring2.Length) Dim source = Format(sourceTemplate, substring0, substring1, substring2) Dim comp = CreateCompilationWithMscorlib(source) comp.AssertNoDiagnostics() comp.AssertTheseEmitDiagnostics(<errors> BC37220: Name '<%= substring2 %>AA1' exceeds the maximum length allowed in metadata. Class <%= substring2 %>AA1 ' Too long <%= _squiggle2 %>~~~ BC37220: Name 'N.<%= substring2 %>1' exceeds the maximum length allowed in metadata. Structure <%= substring2 %>1 ' Too long after prepending 'N.' <%= _squiggle2 %>~ BC37220: Name '<%= substring2 %>AA1' exceeds the maximum length allowed in metadata. Enum <%= substring2 %>AA1 ' Too long <%= _squiggle2 %>~~~ BC37220: Name '<%= substring2 %>1`1' exceeds the maximum length allowed in metadata. Interface <%= substring2 %>1(Of T) ' Too long after appending '`1' <%= _squiggle2 %>~ </errors>) End Sub <Fact> Public Sub ExplicitInterfaceImplementation() Dim sourceTemplate = <![CDATA[ Interface I Sub {0}() Sub {0}1() End Interface Namespace N Interface J(Of T) Sub {0}() Sub {0}1() End Interface End Namespace Class C : Implements I Sub {0}() Implements I.{0} End Sub Sub {0}1() Implements I.{0}1 End Sub End Class Class D : Implements N.J(Of C) Sub {0}() Implements N.J(Of C).{0} End Sub Sub {0}1() Implements N.J(Of C).{0}1 End Sub End Class ]]> ' Unlike in C#, explicit interface implementation members don't have mangled names. Dim source = Format(sourceTemplate, s_longSymbolName) Dim comp = CreateCompilationWithMscorlib(source) Dim _longSquiggle_ As New String("~"c, s_longSymbolName.Length) comp.AssertNoDiagnostics() comp.AssertTheseEmitDiagnostics(<errors> BC37220: Name '<%= s_longSymbolName %>1' exceeds the maximum length allowed in metadata. Sub <%= s_longSymbolName %>1() <%= _longSquiggle_ %>~ BC37220: Name '<%= s_longSymbolName %>1' exceeds the maximum length allowed in metadata. Sub <%= s_longSymbolName %>1() <%= _longSquiggle_ %>~ BC37220: Name '<%= s_longSymbolName %>1' exceeds the maximum length allowed in metadata. Sub <%= s_longSymbolName %>1() <%= _longSquiggle_ %>~ BC37220: Name '<%= s_longSymbolName %>1' exceeds the maximum length allowed in metadata. Sub <%= s_longSymbolName %>1() Implements I.<%= s_longSymbolName %>1 <%= _longSquiggle_ %>~ BC37220: Name '<%= s_longSymbolName %>1' exceeds the maximum length allowed in metadata. Sub <%= s_longSymbolName %>1() Implements N.J(Of C).<%= s_longSymbolName %>1 <%= _longSquiggle_ %>~ </errors>) End Sub <Fact> Public Sub DllImport() Dim sourceTemplate = <![CDATA[ Imports System.Runtime.InteropServices Class C1 <DllImport("goo.dll", EntryPoint:="Short1")> Shared Sub {0}() ' Name is fine, entrypoint is fine. End Sub <DllImport("goo.dll", EntryPoint:="Short2")> Shared Sub {0}1() ' Name is too Long, entrypoint is fine. End Sub End Class Class C2 <DllImport("goo.dll", EntryPoint:="{0}")> Shared Sub Short1() ' Name is fine, entrypoint is fine. End Sub <DllImport("goo.dll", EntryPoint:="{0}1")> Shared Sub Short2() ' Name is fine, entrypoint is too Long. End Sub End Class Class C3 <DllImport("goo.dll")> Shared Sub {0}() ' Name is fine, entrypoint is unspecified. End Sub <DllImport("goo.dll")> Shared Sub {0}1() ' Name is too Long, entrypoint is unspecified. End Sub End Class ]]> Dim source = Format(sourceTemplate, s_longSymbolName) Dim comp = CreateCompilationWithMscorlib(source) Dim _longSquiggle_ As New String("~"c, s_longSymbolName.Length) comp.AssertNoDiagnostics() comp.AssertTheseEmitDiagnostics(<errors> BC37220: Name '<%= s_longSymbolName %>1' exceeds the maximum length allowed in metadata. Shared Sub <%= s_longSymbolName %>1() ' Name is too Long, entrypoint is fine. <%= _longSquiggle_ %>~ BC37220: Name '<%= s_longSymbolName %>1' exceeds the maximum length allowed in metadata. Shared Sub Short2() ' Name is fine, entrypoint is too Long. ~~~~~~ BC37220: Name '<%= s_longSymbolName %>1' exceeds the maximum length allowed in metadata. Shared Sub <%= s_longSymbolName %>1() ' Name is too Long, entrypoint is unspecified. <%= _longSquiggle_ %>~ </errors>) End Sub <Fact> Public Sub Parameters() Dim sourceTemplate = <![CDATA[ Class C Sub M({0} As Short) End Sub Sub M({0}1 As Long) End Sub ReadOnly Property P({0} As Short) As Integer Get Return 0 End Get End Property ReadOnly Property P({0}1 As Long) As Integer Get Return 0 End Get End Property Delegate Sub D1({0} As Short) Delegate Sub D2({0}1 As Long) End Class ]]> Dim source = Format(sourceTemplate, s_longSymbolName) Dim comp = CreateCompilationWithMscorlib(source) Dim _longSquiggle_ As New String("~"c, s_longSymbolName.Length) comp.AssertNoDiagnostics() ' Second report is for Invoke method. Not ideal, but not urgent. comp.AssertTheseEmitDiagnostics(<errors> BC37220: Name '<%= s_longSymbolName %>1' exceeds the maximum length allowed in metadata. Sub M(<%= s_longSymbolName %>1 As Long) <%= _longSquiggle_ %>~ BC37220: Name '<%= s_longSymbolName %>1' exceeds the maximum length allowed in metadata. ReadOnly Property P(<%= s_longSymbolName %>1 As Long) As Integer <%= _longSquiggle_ %>~ BC37220: Name '<%= s_longSymbolName %>1' exceeds the maximum length allowed in metadata. Delegate Sub D2(<%= s_longSymbolName %>1 As Long) <%= _longSquiggle_ %>~ BC37220: Name '<%= s_longSymbolName %>1' exceeds the maximum length allowed in metadata. Delegate Sub D2(<%= s_longSymbolName %>1 As Long) <%= _longSquiggle_ %>~ </errors>) End Sub <Fact> Public Sub TypeParameters() Dim sourceTemplate = <![CDATA[ Class C(Of {0}, {0}1) End Class Delegate Sub D(Of {0}, {0}1)() Class E Sub M(Of {0}, {0}1)() End Sub End Class ]]> Dim source = Format(sourceTemplate, s_longSymbolName) Dim comp = CreateCompilationWithMscorlib(source) Dim __longSpace___ As New String(" "c, s_longSymbolName.Length) Dim _longSquiggle_ As New String("~"c, s_longSymbolName.Length) comp.AssertNoDiagnostics() comp.AssertTheseEmitDiagnostics(<errors> BC37220: Name '<%= s_longSymbolName %>1' exceeds the maximum length allowed in metadata. Class C(Of <%= s_longSymbolName %>, <%= s_longSymbolName %>1) <%= __longSpace___ %><%= _longSquiggle_ %>~ BC37220: Name '<%= s_longSymbolName %>1' exceeds the maximum length allowed in metadata. Delegate Sub D(Of <%= s_longSymbolName %>, <%= s_longSymbolName %>1)() <%= __longSpace___ %><%= _longSquiggle_ %>~ BC37220: Name '<%= s_longSymbolName %>1' exceeds the maximum length allowed in metadata. Sub M(Of <%= s_longSymbolName %>, <%= s_longSymbolName %>1)() <%= __longSpace___ %><%= _longSquiggle_ %>~ </errors>) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub Locals() Dim sourceTemplate = <![CDATA[ Class C Function M() As Long Dim {0} As Short = 1 Dim {0}1 As Long = 1 Return {0} + {0}1 End Function End Class ]]> Dim source = Format(sourceTemplate, s_longLocalName) Dim comp = CompilationUtils.CreateCompilationWithMscorlib40({source}, {}, options:=TestOptions.DebugDll) Dim _longSquiggle_ As New String("~"c, s_longLocalName.Length) comp.AssertNoDiagnostics() comp.AssertTheseEmitDiagnostics(<errors> BC42373: Local name '<%= s_longLocalName %>1' is too long for PDB. Consider shortening or compiling without /debug. Dim <%= s_longLocalName %>1 As Long = 1 <%= _longSquiggle_ %>~ </errors>) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub ConstantLocals() Dim sourceTemplate = <![CDATA[ Class C Function M() As Long Const {0} As Short = 1 Const {0}1 As Long = 1 Return {0} + {0}1 End Function End Class ]]> Dim source = Format(sourceTemplate, s_longLocalName) Dim comp = CompilationUtils.CreateCompilationWithMscorlib40({source}, {}, options:=TestOptions.DebugDll) Dim _longSquiggle_ As New String("~"c, s_longLocalName.Length) comp.AssertNoDiagnostics() comp.AssertTheseEmitDiagnostics(<errors> BC42373: Local name '<%= s_longLocalName %>1' is too long for PDB. Consider shortening or compiling without /debug. Const <%= s_longLocalName %>1 As Long = 1 <%= _longSquiggle_ %>~ </errors>) End Sub <Fact> Public Sub TestStateMachineMethods() Dim sourceTemplate = <![CDATA[ Imports System.Collections.Generic Imports System.Threading.Tasks Class Iterators Iterator Function {0}() As IEnumerable(Of Integer) Yield 1 End Function Iterator Function {0}1() As IEnumerable(Of Integer) Yield 1 End Function End Class Class Async Async Function {0}() As Task Await {0}() End Function Async Function {0}1() As Task Await {0}1() End Function End Class ]]> Dim padding = GeneratedNames.MakeStateMachineTypeName("A", 1, 0).Length - 1 Dim longName = s_longSymbolName.Substring(padding) Dim longSquiggle As New String("~"c, longName.Length) Dim source = Format(sourceTemplate, longName) Dim comp = CreateCompilationWithMscorlib45(source) comp.AssertNoDiagnostics() comp.AssertTheseEmitDiagnostics(<errors> BC37220: Name 'VB$StateMachine_2_<%= longName %>1' exceeds the maximum length allowed in metadata. BC37220: Name 'VB$StateMachine_2_<%= longName %>1' exceeds the maximum length allowed in metadata. </errors>) End Sub <Fact> Public Sub TestResources() Dim comp = CreateCompilationWithMscorlib("Class C : End Class") Dim dataProvider As Func(Of Stream) = Function() New System.IO.MemoryStream() Dim resources = { New ResourceDescription("name1", "path1", dataProvider, False), 'fine New ResourceDescription(s_longSymbolName, "path2", dataProvider, False), 'fine New ResourceDescription("name2", s_longPathName, dataProvider, False), 'fine New ResourceDescription(s_longSymbolName & 1, "path3", dataProvider, False), 'name error New ResourceDescription("name3", s_longPathName & 2, dataProvider, False), 'path error New ResourceDescription(s_longSymbolName & 3, s_longPathName & 4, dataProvider, False) 'name And path errors } Using assemblyStream As New System.IO.MemoryStream() Using pdbStream As New System.IO.MemoryStream() Dim diagnostics = comp.Emit(assemblyStream, pdbStream:=pdbStream, manifestResources:=resources).Diagnostics AssertTheseDiagnostics(diagnostics, <errors> BC37220: Name '<%= s_longPathName %>2' exceeds the maximum length allowed in metadata. BC37220: Name '<%= s_longPathName %>4' exceeds the maximum length allowed in metadata. BC37220: Name '<%= s_longSymbolName %>1' exceeds the maximum length allowed in metadata. BC37220: Name '<%= s_longSymbolName %>3' exceeds the maximum length allowed in metadata. </errors>) End Using End Using End Sub Private Shared Function Format(sourceTemplate As XCData, ParamArray args As Object()) As String Return String.Format(sourceTemplate.Value.Replace(vbCr, vbCrLf), args) End Function Private Function CreateCompilationWithMscorlib(source As String) As VisualBasicCompilation Return CompilationUtils.CreateCompilationWithMscorlib40({source}, {}, TestOptions.ReleaseDll) End Function Private Function CreateCompilationWithMscorlib45(source As String) As VisualBasicCompilation Return VisualBasicCompilation.Create(GetUniqueName(), {VisualBasicSyntaxTree.ParseText(source)}, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseDll) End Function End Class End Namespace
' 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.IO Imports Microsoft.CodeAnalysis.VisualBasic.Symbols 'Imports Microsoft.CodeAnalysis.VisualBasic.Test.Utilities Imports Roslyn.Test.Utilities Imports Xunit Imports Microsoft.Cci Imports System Imports System.Xml.Linq Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class NameLengthTests : Inherits BasicTestBase ' Longest legal symbol name. Private Shared ReadOnly s_longSymbolName As New String("A"c, MetadataWriter.NameLengthLimit) ' Longest legal path name. Private Shared ReadOnly s_longPathName As New String("A"c, MetadataWriter.PathLengthLimit) ' Longest legal local name. Private Shared ReadOnly s_longLocalName As New String("A"c, MetadataWriter.PdbLengthLimit) <Fact> Public Sub UnmangledMemberNames() Dim sourceTemplate = <![CDATA[ Imports System Class Fields Dim {0} As Integer ' Fine Dim {0}1 As Integer ' Too long End Class Class FieldLikeEvents Event {0} as Action ' Fine (except accessors) Event {0}1 as Action ' Fine (except accessors) End Class Class CustomEvents Custom Event {0} As Action ' Fine (except accessors) AddHandler(value As Action) End AddHandler RemoveHandler(value As Action) End RemoveHandler RaiseEvent() End RaiseEvent End Event Custom Event {0}1 As Action ' Too long AddHandler(value As Action) End AddHandler RemoveHandler(value As Action) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class Class AutoProperties Property {0} As Integer ' Fine (except accessors And backing field) Property {0}1 As Integer ' Too long End Class Class CustomProperties Property {0} As Integer ' Fine (except accessors) Get Return 0 End Get Set(value As Integer) End Set End Property Property {0}1 As Integer ' Too long Get Return 0 End Get Set(value As Integer) End Set End Property End Class Class Methods Sub {0}() ' Fine End Sub Sub {0}1() ' Too long End Sub End Class ]]> Dim _longSquiggle_ As New String("~"c, s_longSymbolName.Length) Dim source = Format(sourceTemplate, s_longSymbolName) Dim comp = CreateCompilationWithMscorlib(source) comp.AssertNoDiagnostics() comp.AssertTheseEmitDiagnostics(<errors> BC37220: Name '<%= s_longSymbolName %>1' exceeds the maximum length allowed in metadata. Dim <%= s_longSymbolName %>1 As Integer ' Too long <%= _longSquiggle_ %>~ BC37220: Name '<%= s_longSymbolName %>Event' exceeds the maximum length allowed in metadata. Event <%= s_longSymbolName %> as Action ' Fine (except accessors) <%= _longSquiggle_ %> BC37220: Name 'add_<%= s_longSymbolName %>' exceeds the maximum length allowed in metadata. Event <%= s_longSymbolName %> as Action ' Fine (except accessors) <%= _longSquiggle_ %> BC37220: Name 'remove_<%= s_longSymbolName %>' exceeds the maximum length allowed in metadata. Event <%= s_longSymbolName %> as Action ' Fine (except accessors) <%= _longSquiggle_ %> BC37220: Name '<%= s_longSymbolName %>1' exceeds the maximum length allowed in metadata. Event <%= s_longSymbolName %>1 as Action ' Fine (except accessors) <%= _longSquiggle_ %>~ BC37220: Name '<%= s_longSymbolName %>1Event' exceeds the maximum length allowed in metadata. Event <%= s_longSymbolName %>1 as Action ' Fine (except accessors) <%= _longSquiggle_ %>~ BC37220: Name 'add_<%= s_longSymbolName %>1' exceeds the maximum length allowed in metadata. Event <%= s_longSymbolName %>1 as Action ' Fine (except accessors) <%= _longSquiggle_ %>~ BC37220: Name 'remove_<%= s_longSymbolName %>1' exceeds the maximum length allowed in metadata. Event <%= s_longSymbolName %>1 as Action ' Fine (except accessors) <%= _longSquiggle_ %>~ BC37220: Name 'add_<%= s_longSymbolName %>' exceeds the maximum length allowed in metadata. AddHandler(value As Action) ~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37220: Name 'remove_<%= s_longSymbolName %>' exceeds the maximum length allowed in metadata. RemoveHandler(value As Action) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37220: Name 'raise_<%= s_longSymbolName %>' exceeds the maximum length allowed in metadata. RaiseEvent() ~~~~~~~~~~~~ BC37220: Name '<%= s_longSymbolName %>1' exceeds the maximum length allowed in metadata. Custom Event <%= s_longSymbolName %>1 As Action ' Too long <%= _longSquiggle_ %>~ BC37220: Name 'add_<%= s_longSymbolName %>1' exceeds the maximum length allowed in metadata. AddHandler(value As Action) ~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37220: Name 'remove_<%= s_longSymbolName %>1' exceeds the maximum length allowed in metadata. RemoveHandler(value As Action) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37220: Name 'raise_<%= s_longSymbolName %>1' exceeds the maximum length allowed in metadata. RaiseEvent() ~~~~~~~~~~~~ BC37220: Name '_<%= s_longSymbolName %>' exceeds the maximum length allowed in metadata. Property <%= s_longSymbolName %> As Integer ' Fine (except accessors And backing field) <%= _longSquiggle_ %> BC37220: Name 'get_<%= s_longSymbolName %>' exceeds the maximum length allowed in metadata. Property <%= s_longSymbolName %> As Integer ' Fine (except accessors And backing field) <%= _longSquiggle_ %> BC37220: Name 'set_<%= s_longSymbolName %>' exceeds the maximum length allowed in metadata. Property <%= s_longSymbolName %> As Integer ' Fine (except accessors And backing field) <%= _longSquiggle_ %> BC37220: Name '<%= s_longSymbolName %>1' exceeds the maximum length allowed in metadata. Property <%= s_longSymbolName %>1 As Integer ' Too long <%= _longSquiggle_ %>~ BC37220: Name '_<%= s_longSymbolName %>1' exceeds the maximum length allowed in metadata. Property <%= s_longSymbolName %>1 As Integer ' Too long <%= _longSquiggle_ %>~ BC37220: Name 'get_<%= s_longSymbolName %>1' exceeds the maximum length allowed in metadata. Property <%= s_longSymbolName %>1 As Integer ' Too long <%= _longSquiggle_ %>~ BC37220: Name 'set_<%= s_longSymbolName %>1' exceeds the maximum length allowed in metadata. Property <%= s_longSymbolName %>1 As Integer ' Too long <%= _longSquiggle_ %>~ BC37220: Name 'get_<%= s_longSymbolName %>' exceeds the maximum length allowed in metadata. Get ~~~ BC37220: Name 'set_<%= s_longSymbolName %>' exceeds the maximum length allowed in metadata. Set(value As Integer) ~~~ BC37220: Name '<%= s_longSymbolName %>1' exceeds the maximum length allowed in metadata. Property <%= s_longSymbolName %>1 As Integer ' Too long <%= _longSquiggle_ %>~ BC37220: Name 'get_<%= s_longSymbolName %>1' exceeds the maximum length allowed in metadata. Get ~~~ BC37220: Name 'set_<%= s_longSymbolName %>1' exceeds the maximum length allowed in metadata. Set(value As Integer) ~~~ BC37220: Name '<%= s_longSymbolName %>1' exceeds the maximum length allowed in metadata. Sub <%= s_longSymbolName %>1() ' Too long <%= _longSquiggle_ %>~ </errors>) End Sub <Fact> Public Sub EmptyNamespaces() Dim sourceTemplate = <![CDATA[ Namespace {0} ' Fine. End Namespace Namespace {0}1 ' Too long, but not checked. End Namespace ]]> Dim source = Format(sourceTemplate, s_longSymbolName) Dim comp = CreateCompilationWithMscorlib(source) comp.AssertNoDiagnostics() comp.AssertTheseEmitDiagnostics(<errors/>) End Sub <Fact> Public Sub NonGeneratedTypeNames() ' {n} == LongSymbolName.Substring(n) Dim sourceTemplate = <![CDATA[ Class {0} ' Fine End Class Class {0}1 ' Too long End Class Namespace N Structure {2} ' Fine End Structure Structure {2}1 ' Too long after prepending 'N.' End Structure End Namespace Class Outer Enum {0} ' Fine, since outer class is not prepended A End Enum Enum {0}1 ' Too long A End Enum End Class Interface {2}(Of T) ' Fine End Interface Interface {2}1(Of T) ' Too long after appending '`1' End Interface ]]> Dim substring0 = s_longSymbolName Dim substring1 = s_longSymbolName.Substring(1) Dim substring2 = s_longSymbolName.Substring(2) Dim _squiggle2 As New String("~"c, substring2.Length) Dim source = Format(sourceTemplate, substring0, substring1, substring2) Dim comp = CreateCompilationWithMscorlib(source) comp.AssertNoDiagnostics() comp.AssertTheseEmitDiagnostics(<errors> BC37220: Name '<%= substring2 %>AA1' exceeds the maximum length allowed in metadata. Class <%= substring2 %>AA1 ' Too long <%= _squiggle2 %>~~~ BC37220: Name 'N.<%= substring2 %>1' exceeds the maximum length allowed in metadata. Structure <%= substring2 %>1 ' Too long after prepending 'N.' <%= _squiggle2 %>~ BC37220: Name '<%= substring2 %>AA1' exceeds the maximum length allowed in metadata. Enum <%= substring2 %>AA1 ' Too long <%= _squiggle2 %>~~~ BC37220: Name '<%= substring2 %>1`1' exceeds the maximum length allowed in metadata. Interface <%= substring2 %>1(Of T) ' Too long after appending '`1' <%= _squiggle2 %>~ </errors>) End Sub <Fact> Public Sub ExplicitInterfaceImplementation() Dim sourceTemplate = <![CDATA[ Interface I Sub {0}() Sub {0}1() End Interface Namespace N Interface J(Of T) Sub {0}() Sub {0}1() End Interface End Namespace Class C : Implements I Sub {0}() Implements I.{0} End Sub Sub {0}1() Implements I.{0}1 End Sub End Class Class D : Implements N.J(Of C) Sub {0}() Implements N.J(Of C).{0} End Sub Sub {0}1() Implements N.J(Of C).{0}1 End Sub End Class ]]> ' Unlike in C#, explicit interface implementation members don't have mangled names. Dim source = Format(sourceTemplate, s_longSymbolName) Dim comp = CreateCompilationWithMscorlib(source) Dim _longSquiggle_ As New String("~"c, s_longSymbolName.Length) comp.AssertNoDiagnostics() comp.AssertTheseEmitDiagnostics(<errors> BC37220: Name '<%= s_longSymbolName %>1' exceeds the maximum length allowed in metadata. Sub <%= s_longSymbolName %>1() <%= _longSquiggle_ %>~ BC37220: Name '<%= s_longSymbolName %>1' exceeds the maximum length allowed in metadata. Sub <%= s_longSymbolName %>1() <%= _longSquiggle_ %>~ BC37220: Name '<%= s_longSymbolName %>1' exceeds the maximum length allowed in metadata. Sub <%= s_longSymbolName %>1() <%= _longSquiggle_ %>~ BC37220: Name '<%= s_longSymbolName %>1' exceeds the maximum length allowed in metadata. Sub <%= s_longSymbolName %>1() Implements I.<%= s_longSymbolName %>1 <%= _longSquiggle_ %>~ BC37220: Name '<%= s_longSymbolName %>1' exceeds the maximum length allowed in metadata. Sub <%= s_longSymbolName %>1() Implements N.J(Of C).<%= s_longSymbolName %>1 <%= _longSquiggle_ %>~ </errors>) End Sub <Fact> Public Sub DllImport() Dim sourceTemplate = <![CDATA[ Imports System.Runtime.InteropServices Class C1 <DllImport("goo.dll", EntryPoint:="Short1")> Shared Sub {0}() ' Name is fine, entrypoint is fine. End Sub <DllImport("goo.dll", EntryPoint:="Short2")> Shared Sub {0}1() ' Name is too Long, entrypoint is fine. End Sub End Class Class C2 <DllImport("goo.dll", EntryPoint:="{0}")> Shared Sub Short1() ' Name is fine, entrypoint is fine. End Sub <DllImport("goo.dll", EntryPoint:="{0}1")> Shared Sub Short2() ' Name is fine, entrypoint is too Long. End Sub End Class Class C3 <DllImport("goo.dll")> Shared Sub {0}() ' Name is fine, entrypoint is unspecified. End Sub <DllImport("goo.dll")> Shared Sub {0}1() ' Name is too Long, entrypoint is unspecified. End Sub End Class ]]> Dim source = Format(sourceTemplate, s_longSymbolName) Dim comp = CreateCompilationWithMscorlib(source) Dim _longSquiggle_ As New String("~"c, s_longSymbolName.Length) comp.AssertNoDiagnostics() comp.AssertTheseEmitDiagnostics(<errors> BC37220: Name '<%= s_longSymbolName %>1' exceeds the maximum length allowed in metadata. Shared Sub <%= s_longSymbolName %>1() ' Name is too Long, entrypoint is fine. <%= _longSquiggle_ %>~ BC37220: Name '<%= s_longSymbolName %>1' exceeds the maximum length allowed in metadata. Shared Sub Short2() ' Name is fine, entrypoint is too Long. ~~~~~~ BC37220: Name '<%= s_longSymbolName %>1' exceeds the maximum length allowed in metadata. Shared Sub <%= s_longSymbolName %>1() ' Name is too Long, entrypoint is unspecified. <%= _longSquiggle_ %>~ </errors>) End Sub <Fact> Public Sub Parameters() Dim sourceTemplate = <![CDATA[ Class C Sub M({0} As Short) End Sub Sub M({0}1 As Long) End Sub ReadOnly Property P({0} As Short) As Integer Get Return 0 End Get End Property ReadOnly Property P({0}1 As Long) As Integer Get Return 0 End Get End Property Delegate Sub D1({0} As Short) Delegate Sub D2({0}1 As Long) End Class ]]> Dim source = Format(sourceTemplate, s_longSymbolName) Dim comp = CreateCompilationWithMscorlib(source) Dim _longSquiggle_ As New String("~"c, s_longSymbolName.Length) comp.AssertNoDiagnostics() ' Second report is for Invoke method. Not ideal, but not urgent. comp.AssertTheseEmitDiagnostics(<errors> BC37220: Name '<%= s_longSymbolName %>1' exceeds the maximum length allowed in metadata. Sub M(<%= s_longSymbolName %>1 As Long) <%= _longSquiggle_ %>~ BC37220: Name '<%= s_longSymbolName %>1' exceeds the maximum length allowed in metadata. ReadOnly Property P(<%= s_longSymbolName %>1 As Long) As Integer <%= _longSquiggle_ %>~ BC37220: Name '<%= s_longSymbolName %>1' exceeds the maximum length allowed in metadata. Delegate Sub D2(<%= s_longSymbolName %>1 As Long) <%= _longSquiggle_ %>~ BC37220: Name '<%= s_longSymbolName %>1' exceeds the maximum length allowed in metadata. Delegate Sub D2(<%= s_longSymbolName %>1 As Long) <%= _longSquiggle_ %>~ </errors>) End Sub <Fact> Public Sub TypeParameters() Dim sourceTemplate = <![CDATA[ Class C(Of {0}, {0}1) End Class Delegate Sub D(Of {0}, {0}1)() Class E Sub M(Of {0}, {0}1)() End Sub End Class ]]> Dim source = Format(sourceTemplate, s_longSymbolName) Dim comp = CreateCompilationWithMscorlib(source) Dim __longSpace___ As New String(" "c, s_longSymbolName.Length) Dim _longSquiggle_ As New String("~"c, s_longSymbolName.Length) comp.AssertNoDiagnostics() comp.AssertTheseEmitDiagnostics(<errors> BC37220: Name '<%= s_longSymbolName %>1' exceeds the maximum length allowed in metadata. Class C(Of <%= s_longSymbolName %>, <%= s_longSymbolName %>1) <%= __longSpace___ %><%= _longSquiggle_ %>~ BC37220: Name '<%= s_longSymbolName %>1' exceeds the maximum length allowed in metadata. Delegate Sub D(Of <%= s_longSymbolName %>, <%= s_longSymbolName %>1)() <%= __longSpace___ %><%= _longSquiggle_ %>~ BC37220: Name '<%= s_longSymbolName %>1' exceeds the maximum length allowed in metadata. Sub M(Of <%= s_longSymbolName %>, <%= s_longSymbolName %>1)() <%= __longSpace___ %><%= _longSquiggle_ %>~ </errors>) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub Locals() Dim sourceTemplate = <![CDATA[ Class C Function M() As Long Dim {0} As Short = 1 Dim {0}1 As Long = 1 Return {0} + {0}1 End Function End Class ]]> Dim source = Format(sourceTemplate, s_longLocalName) Dim comp = CompilationUtils.CreateCompilationWithMscorlib40({source}, {}, options:=TestOptions.DebugDll) Dim _longSquiggle_ As New String("~"c, s_longLocalName.Length) comp.AssertNoDiagnostics() comp.AssertTheseEmitDiagnostics(<errors> BC42373: Local name '<%= s_longLocalName %>1' is too long for PDB. Consider shortening or compiling without /debug. Dim <%= s_longLocalName %>1 As Long = 1 <%= _longSquiggle_ %>~ </errors>) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub ConstantLocals() Dim sourceTemplate = <![CDATA[ Class C Function M() As Long Const {0} As Short = 1 Const {0}1 As Long = 1 Return {0} + {0}1 End Function End Class ]]> Dim source = Format(sourceTemplate, s_longLocalName) Dim comp = CompilationUtils.CreateCompilationWithMscorlib40({source}, {}, options:=TestOptions.DebugDll) Dim _longSquiggle_ As New String("~"c, s_longLocalName.Length) comp.AssertNoDiagnostics() comp.AssertTheseEmitDiagnostics(<errors> BC42373: Local name '<%= s_longLocalName %>1' is too long for PDB. Consider shortening or compiling without /debug. Const <%= s_longLocalName %>1 As Long = 1 <%= _longSquiggle_ %>~ </errors>) End Sub <Fact> Public Sub TestStateMachineMethods() Dim sourceTemplate = <![CDATA[ Imports System.Collections.Generic Imports System.Threading.Tasks Class Iterators Iterator Function {0}() As IEnumerable(Of Integer) Yield 1 End Function Iterator Function {0}1() As IEnumerable(Of Integer) Yield 1 End Function End Class Class Async Async Function {0}() As Task Await {0}() End Function Async Function {0}1() As Task Await {0}1() End Function End Class ]]> Dim padding = GeneratedNames.MakeStateMachineTypeName("A", 1, 0).Length - 1 Dim longName = s_longSymbolName.Substring(padding) Dim longSquiggle As New String("~"c, longName.Length) Dim source = Format(sourceTemplate, longName) Dim comp = CreateCompilationWithMscorlib45(source) comp.AssertNoDiagnostics() comp.AssertTheseEmitDiagnostics(<errors> BC37220: Name 'VB$StateMachine_2_<%= longName %>1' exceeds the maximum length allowed in metadata. BC37220: Name 'VB$StateMachine_2_<%= longName %>1' exceeds the maximum length allowed in metadata. </errors>) End Sub <Fact> Public Sub TestResources() Dim comp = CreateCompilationWithMscorlib("Class C : End Class") Dim dataProvider As Func(Of Stream) = Function() New System.IO.MemoryStream() Dim resources = { New ResourceDescription("name1", "path1", dataProvider, False), 'fine New ResourceDescription(s_longSymbolName, "path2", dataProvider, False), 'fine New ResourceDescription("name2", s_longPathName, dataProvider, False), 'fine New ResourceDescription(s_longSymbolName & 1, "path3", dataProvider, False), 'name error New ResourceDescription("name3", s_longPathName & 2, dataProvider, False), 'path error New ResourceDescription(s_longSymbolName & 3, s_longPathName & 4, dataProvider, False) 'name And path errors } Using assemblyStream As New System.IO.MemoryStream() Using pdbStream As New System.IO.MemoryStream() Dim diagnostics = comp.Emit(assemblyStream, pdbStream:=pdbStream, manifestResources:=resources).Diagnostics AssertTheseDiagnostics(diagnostics, <errors> BC37220: Name '<%= s_longPathName %>2' exceeds the maximum length allowed in metadata. BC37220: Name '<%= s_longPathName %>4' exceeds the maximum length allowed in metadata. BC37220: Name '<%= s_longSymbolName %>1' exceeds the maximum length allowed in metadata. BC37220: Name '<%= s_longSymbolName %>3' exceeds the maximum length allowed in metadata. </errors>) End Using End Using End Sub Private Shared Function Format(sourceTemplate As XCData, ParamArray args As Object()) As String Return String.Format(sourceTemplate.Value.Replace(vbCr, vbCrLf), args) End Function Private Function CreateCompilationWithMscorlib(source As String) As VisualBasicCompilation Return CompilationUtils.CreateCompilationWithMscorlib40({source}, {}, TestOptions.ReleaseDll) End Function Private Function CreateCompilationWithMscorlib45(source As String) As VisualBasicCompilation Return VisualBasicCompilation.Create(GetUniqueName(), {VisualBasicSyntaxTree.ParseText(source)}, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseDll) End Function End Class End Namespace
1
dotnet/roslyn
56,011
React to string comparison changing on .NET Core
The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
jaredpar
"2021-08-30T17:18:52Z"
"2021-08-30T20:20:04Z"
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
4d99cda6e446e77dbb302e26388c1093bd3ef569
React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
./src/Compilers/VisualBasic/Test/Semantic/Semantics/TooLongNameTests.vb
' 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.IO Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.SpecialType Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.OverloadResolution Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Public Class TooLongNames Inherits BasicTestBase <WorkItem(531481, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531481")> <Fact> Public Sub NestedTypeNamesShouldNotCountOuterTypes() Dim c As VisualBasicCompilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="AssemblyName"> <file name="a.vb"> <%= SemanticResourceUtil.LongTypeName_vb %> </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(c, <expected></expected>) End Sub <WorkItem(531481, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531481")> <Fact> Public Sub NestedTypeNamesShouldNotCountOuterTypes2() Dim c As VisualBasicCompilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="AssemblyName"> <file name="a.vb"> <%= SemanticResourceUtil.LongTypeNameNative_vb %> </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(c, <expected></expected>) End Sub <WorkItem(530442, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530442")> <Fact> Public Sub StaticLocalWithTooLongName() Dim c As VisualBasicCompilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="AssemblyName"> <file name="a.vb"> Imports System Public Module Module1 Public Sub Main() MaximumLengthIdentifierIn2012() MaximumLengthIdentifierIn2012() MaximumLengthIdentifierIn2012() End Sub Sub MaximumLengthIdentifierIn2012() Static abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZABCDEFGHIJ As Integer = 1 Console.WriteLine(abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZABCDEFGHIJ.ToString) abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZABCDEFGHIJ += 1 End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseEmitDiagnostics(c, <expected> BC37220: Name '$STATIC$MaximumLengthIdentifierIn2012$001$abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZABCDEFGHIJ' exceeds the maximum length allowed in metadata. Static abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZABCDEFGHIJ As Integer = 1 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37220: Name '$STATIC$MaximumLengthIdentifierIn2012$001$abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZABCDEFGHIJ$Init' exceeds the maximum length allowed in metadata. Static abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZABCDEFGHIJ As Integer = 1 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <WorkItem(530442, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530442")> <Fact> Public Sub StaticLocalWithTooLongName2() Dim c As VisualBasicCompilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="AssemblyName"> <file name="a.vb"> Imports System Public Module Module1 Public Sub Main() MaximumLengthIdentifierIn2012() MaximumLengthIdentifierIn2012() MaximumLengthIdentifierIn2012() End Sub Sub MaximumLengthIdentifierIn2012() Static abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZABCDEFGHIJ As Integer Console.WriteLine(abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZABCDEFGHIJ.ToString) abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZABCDEFGHIJ += 1 End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseEmitDiagnostics(c, <expected> BC37220: Name '$STATIC$MaximumLengthIdentifierIn2012$001$abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZABCDEFGHIJ' exceeds the maximum length allowed in metadata. Static abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZABCDEFGHIJ As Integer ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub End Class End Namespace
' 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.IO Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.SpecialType Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.OverloadResolution Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Public Class TooLongNames Inherits BasicTestBase <WorkItem(531481, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531481")> <Fact> Public Sub NestedTypeNamesShouldNotCountOuterTypes() Dim c As VisualBasicCompilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="AssemblyName"> <file name="a.vb"> <%= SemanticResourceUtil.LongTypeName_vb %> </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(c, <expected></expected>) End Sub <WorkItem(531481, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531481")> <Fact> Public Sub NestedTypeNamesShouldNotCountOuterTypes2() Dim c As VisualBasicCompilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="AssemblyName"> <file name="a.vb"> <%= SemanticResourceUtil.LongTypeNameNative_vb %> </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(c, <expected></expected>) End Sub <WorkItem(530442, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530442")> <Fact> Public Sub StaticLocalWithTooLongName() Dim c As VisualBasicCompilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="AssemblyName"> <file name="a.vb"> Imports System Public Module Module1 Public Sub Main() MaximumLengthIdentifierIn2012() MaximumLengthIdentifierIn2012() MaximumLengthIdentifierIn2012() End Sub Sub MaximumLengthIdentifierIn2012() Static abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZABCDEFGHIJ As Integer = 1 Console.WriteLine(abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZABCDEFGHIJ.ToString) abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZABCDEFGHIJ += 1 End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseEmitDiagnostics(c, <expected> BC37220: Name '$STATIC$MaximumLengthIdentifierIn2012$001$abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZABCDEFGHIJ$Init' exceeds the maximum length allowed in metadata. Static abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZABCDEFGHIJ As Integer = 1 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37220: Name '$STATIC$MaximumLengthIdentifierIn2012$001$abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZABCDEFGHIJ' exceeds the maximum length allowed in metadata. Static abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZABCDEFGHIJ As Integer = 1 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <WorkItem(530442, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530442")> <Fact> Public Sub StaticLocalWithTooLongName2() Dim c As VisualBasicCompilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="AssemblyName"> <file name="a.vb"> Imports System Public Module Module1 Public Sub Main() MaximumLengthIdentifierIn2012() MaximumLengthIdentifierIn2012() MaximumLengthIdentifierIn2012() End Sub Sub MaximumLengthIdentifierIn2012() Static abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZABCDEFGHIJ As Integer Console.WriteLine(abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZABCDEFGHIJ.ToString) abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZABCDEFGHIJ += 1 End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseEmitDiagnostics(c, <expected> BC37220: Name '$STATIC$MaximumLengthIdentifierIn2012$001$abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZABCDEFGHIJ' exceeds the maximum length allowed in metadata. Static abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZABCDEFGHIJ As Integer ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub End Class End Namespace
1
dotnet/roslyn
56,011
React to string comparison changing on .NET Core
The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
jaredpar
"2021-08-30T17:18:52Z"
"2021-08-30T20:20:04Z"
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
4d99cda6e446e77dbb302e26388c1093bd3ef569
React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
./src/Compilers/VisualBasic/Test/Semantic/Semantics/UserDefinedForToLoop.vb
' 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.IO Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.SpecialType Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.OverloadResolution Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Public Class UserDefinedForToLoop Inherits BasicTestBase <Fact> Public Sub BasicTest1() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Option Strict Off Imports System Module Module1 Class B1 Private val As Integer Public Sub New(val As Integer) Me.val = val End Sub Shared Operator +(x As B1, y As B1) As B1 System.Console.WriteLine("{0} + {1}", x, y) Return New B1(x.val + y.val) End Operator Shared Operator -(x As B1, y As B1) As B1 System.Console.WriteLine("{0} - {1}", x, y) Return New B1(x.val - y.val) End Operator Shared Operator >=(x As B1, y As B1) As Boolean System.Console.WriteLine("{0} >= {1}", x, y) Return x.val >= y.val End Operator Shared Operator <=(x As B1, y As B1) As Boolean System.Console.WriteLine("{0} <= {1}", x, y) Return x.val <= y.val End Operator Public Overrides Function ToString() As String Return String.Format("B({0})", val) End Function End Class Class B2 Public Val As B1 End Class Dim m_Index As New B2() ReadOnly Property Index As B2 Get System.Console.WriteLine("get_Index") Return m_Index End Get End Property Function Init(val As Integer) As B1 System.Console.WriteLine("Init") Return New B1(val) End Function Function [Step](val As Integer) As B1 System.Console.WriteLine("Step") Return New B1(Val) End Function Function Limit(val As Integer) As B1 System.Console.WriteLine("Limit") Return New B1(Val) End Function Sub Main() For Index.Val = Init(0) To Limit(3) Step [Step](2) System.Console.WriteLine("Body {0}", m_Index.Val) Next System.Console.WriteLine("-----") For Index.Val = Init(3) To Limit(0) Step [Step](-2) System.Console.WriteLine("Body {0}", m_Index.Val) Next End Sub End Module ]]></file> </compilation> Dim verifier = CompileAndVerify(compilationDef, expectedOutput:= <![CDATA[ get_Index Init Limit Step B(2) - B(2) B(2) >= B(0) get_Index B(0) <= B(3) Body B(0) get_Index get_Index B(0) + B(2) get_Index B(2) <= B(3) Body B(2) get_Index get_Index B(2) + B(2) get_Index B(4) <= B(3) ----- get_Index Init Limit Step B(-2) - B(-2) B(-2) >= B(0) get_Index B(3) >= B(0) Body B(3) get_Index get_Index B(3) + B(-2) get_Index B(1) >= B(0) Body B(1) get_Index get_Index B(1) + B(-2) get_Index B(-1) >= B(0) ]]>) End Sub <Fact> Public Sub BasicTest2() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Option Strict Off Imports System Module Module1 Class B1 Private val As Integer Public Sub New(val As Integer) Me.val = val End Sub Shared Operator +(x As B1, y As B1) As B1 System.Console.WriteLine("{0} + {1}", x, y) Return New B1(x.val + y.val) End Operator Shared Operator -(x As B1, y As B1) As B1 System.Console.WriteLine("{0} - {1}", x, y) Return New B1(x.val - y.val) End Operator Shared Operator >=(x As B1, y As B1) As B3 Dim str = String.Format("{0} >= {1}", x, y) System.Console.WriteLine(str) Return New B3(x.val >= y.val, str) End Operator Shared Operator <=(x As B1, y As B1) As B3 Dim str = String.Format("{0} <= {1}", x, y) System.Console.WriteLine(str) Return New B3(x.val <= y.val, str) End Operator Public Overrides Function ToString() As String Return String.Format("B({0})", val) End Function End Class Class B3 Private val As Boolean Private str As String Public Sub New(val As Boolean, str As String) Me.val = val Me.str = str End Sub Shared Operator IsTrue(x As B3) As Boolean System.Console.WriteLine("B3({0}).IsTrue", x.str) Return x.val End Operator Shared Operator IsFalse(x As B3) As Boolean System.Console.WriteLine("B3({0}).IsFalse", x.str) Return x.val End Operator End Class Function Init(val As Integer) As B1 System.Console.WriteLine("Init") Return New B1(val) End Function Function [Step](val As Integer) As B1 System.Console.WriteLine("Step") Return New B1(Val) End Function Function Limit(val As Integer) As B1 System.Console.WriteLine("Limit") Return New B1(Val) End Function Sub Main() For i = Init(0) To Limit(3) Step [Step](2) System.Console.WriteLine("Body {0}", i) Next System.Console.WriteLine("-----") For i = Init(3) To Limit(0) Step [Step](-2) System.Console.WriteLine("Body {0}", i) Next End Sub End Module ]]></file> </compilation> Dim verifier = CompileAndVerify(compilationDef, expectedOutput:= <![CDATA[ Init Limit Step B(2) - B(2) B(2) >= B(0) B3(B(2) >= B(0)).IsTrue B(0) <= B(3) B3(B(0) <= B(3)).IsTrue Body B(0) B(0) + B(2) B(2) <= B(3) B3(B(2) <= B(3)).IsTrue Body B(2) B(2) + B(2) B(4) <= B(3) B3(B(4) <= B(3)).IsTrue ----- Init Limit Step B(-2) - B(-2) B(-2) >= B(0) B3(B(-2) >= B(0)).IsTrue B(3) >= B(0) B3(B(3) >= B(0)).IsTrue Body B(3) B(3) + B(-2) B(1) >= B(0) B3(B(1) >= B(0)).IsTrue Body B(1) B(1) + B(-2) B(-1) >= B(0) B3(B(-1) >= B(0)).IsTrue ]]>) End Sub <Fact> Public Sub BasicTest3() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Option Strict Off Imports System Module Module1 Class B1 Private val As Integer Public Sub New(val As Integer) Me.val = val End Sub Shared Widening Operator CType(x As Integer) As B1 System.Console.WriteLine("CType({0}) As B1", x) Return New B1(x) End Operator Shared Operator +(x As B1, y As B1) As B1 System.Console.WriteLine("{0} + {1}", x, y) Return New B1(x.val + y.val) End Operator Shared Operator -(x As B1, y As B1) As B1 System.Console.WriteLine("{0} - {1}", x, y) Return New B1(x.val - y.val) End Operator Shared Operator >=(x As B1, y As B1) As B3 Dim str = String.Format("{0} >= {1}", x, y) System.Console.WriteLine(str) Return New B3(x.val >= y.val, str) End Operator Shared Operator <=(x As B1, y As B1) As B3 Dim str = String.Format("{0} <= {1}", x, y) System.Console.WriteLine(str) Return New B3(x.val <= y.val, str) End Operator Public Overrides Function ToString() As String Return String.Format("B({0})", val) End Function End Class Class B3 Private val As Boolean Private str As String Public Sub New(val As Boolean, str As String) Me.val = val Me.str = str End Sub Shared Operator IsTrue(x As B3) As Boolean System.Console.WriteLine("B3({0}).IsTrue", x.str) Return x.val End Operator Shared Operator IsFalse(x As B3) As Boolean System.Console.WriteLine("B3({0}).IsFalse", x.str) Return x.val End Operator End Class Function Init(val As Integer) As B1 System.Console.WriteLine("Init") Return New B1(val) End Function Function [Step](val As Integer) As B1 System.Console.WriteLine("Step") Return New B1(Val) End Function Function Limit(val As Integer) As B1 System.Console.WriteLine("Limit") Return New B1(Val) End Function Sub Main() For i = Init(0) To Limit(3) System.Console.WriteLine("Body {0}", i) Next End Sub End Module ]]></file> </compilation> Dim verifier = CompileAndVerify(compilationDef, expectedOutput:= <![CDATA[ Init Limit CType(1) As B1 B(1) - B(1) B(1) >= B(0) B3(B(1) >= B(0)).IsTrue B(0) <= B(3) B3(B(0) <= B(3)).IsTrue Body B(0) B(0) + B(1) B(1) <= B(3) B3(B(1) <= B(3)).IsTrue Body B(1) B(1) + B(1) B(2) <= B(3) B3(B(2) <= B(3)).IsTrue Body B(2) B(2) + B(1) B(3) <= B(3) B3(B(3) <= B(3)).IsTrue Body B(3) B(3) + B(1) B(4) <= B(3) B3(B(4) <= B(3)).IsTrue ]]>) End Sub <Fact(), WorkItem(544375, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544375")> Public Sub BasicTest4() Dim compilationDef = <compilation name="BasicTest4"> <file name="a.vb"><![CDATA[ Option Strict On Imports System Structure S Class C Private val As Boolean Private str As String Public Sub New(val As Boolean, str As String) Me.val = val Me.str = str End Sub Shared Operator IsTrue(x As C) As Boolean Console.WriteLine("C({0}).IsTrue", x.str) Return x.val End Operator Shared Operator IsFalse(x As C) As Boolean Console.WriteLine("C({0}).IsFalse", x.str) Return x.val End Operator End Class Private val As Integer Public Sub New(val As Integer) Me.val = val End Sub Shared Widening Operator CType(x As Integer) As S Console.WriteLine("CType({0}) As S", x) Return New S(x) End Operator Shared Operator +(x As S, y As S) As S Console.WriteLine("{0} + {1}", x, y) Return New S(x.val + y.val) End Operator Shared Operator -(x As S, y As S) As S Console.WriteLine("{0} - {1}", x, y) Return New S(x.val - y.val) End Operator Shared Operator >=(x As S, y As S) As C Dim str = String.Format("{0} >= {1}", x, y) Console.WriteLine(str) Return New C(x.val >= y.val, str) End Operator Shared Operator <=(x As S, y As S) As C Dim str = String.Format("{0} <= {1}", x, y) Console.WriteLine(str) Return New C(x.val <= y.val, str) End Operator Public Overrides Function ToString() As String Return String.Format("S({0})", val) End Function End Structure Module Module1 Sub Main() For i As S = Nothing To Nothing Console.WriteLine("Body {0}", i) Next End Sub End Module ]]></file> </compilation> Dim verifier = CompileAndVerify(compilationDef, expectedOutput:= <![CDATA[ CType(1) As S S(1) - S(1) S(1) >= S(0) C(S(1) >= S(0)).IsTrue S(0) <= S(0) C(S(0) <= S(0)).IsTrue Body S(0) S(0) + S(1) S(1) <= S(0) C(S(1) <= S(0)).IsTrue ]]>) End Sub <Fact> Public Sub MissingCInt() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Option Strict Off Imports System Module Module1 Class B1 Private val As Integer Public Sub New(val As Integer) Me.val = val End Sub End Class Sub Main() For i = New B1(0) To New B1(3) System.Console.WriteLine("Body {0}", i) Next End Sub End Module ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30311: Value of type 'Integer' cannot be converted to 'Module1.B1'. For i = New B1(0) To New B1(3) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact> Public Sub MissingAddSubtractLeGe() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Option Strict Off Imports System Module Module1 Class B1 Private val As Integer Public Sub New(val As Integer) Me.val = val End Sub End Class Sub Main() For i = New B1(0) To New B1(3) Step New B1(2) System.Console.WriteLine("Body {0}", i) Next End Sub End Module ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) CompilationUtils.AssertTheseDiagnostics(compilation, <expected><![CDATA[ BC33038: Type 'Module1.B1' must define operator '-' to be used in a 'For' statement. For i = New B1(0) To New B1(3) Step New B1(2) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC33038: Type 'Module1.B1' must define operator '+' to be used in a 'For' statement. For i = New B1(0) To New B1(3) Step New B1(2) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC33038: Type 'Module1.B1' must define operator '<=' to be used in a 'For' statement. For i = New B1(0) To New B1(3) Step New B1(2) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC33038: Type 'Module1.B1' must define operator '>=' to be used in a 'For' statement. For i = New B1(0) To New B1(3) Step New B1(2) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></expected>) End Sub <Fact> Public Sub MissingSubtractLeGe() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Option Strict Off Imports System Module Module1 Class B1 Private val As Integer Public Sub New(val As Integer) Me.val = val End Sub Shared Operator +(x As B1, y As B1) As B1 System.Console.WriteLine("{0} + {1}", x, y) Return New B1(x.val + y.val) End Operator End Class Sub Main() For i = New B1(0) To New B1(3) Step New B1(2) System.Console.WriteLine("Body {0}", i) Next End Sub End Module ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) CompilationUtils.AssertTheseDiagnostics(compilation, <expected><![CDATA[ BC33038: Type 'Module1.B1' must define operator '-' to be used in a 'For' statement. For i = New B1(0) To New B1(3) Step New B1(2) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC33038: Type 'Module1.B1' must define operator '<=' to be used in a 'For' statement. For i = New B1(0) To New B1(3) Step New B1(2) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC33038: Type 'Module1.B1' must define operator '>=' to be used in a 'For' statement. For i = New B1(0) To New B1(3) Step New B1(2) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></expected>) End Sub <Fact> Public Sub MissingAddLeGe() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Option Strict Off Imports System Module Module1 Class B1 Private val As Integer Public Sub New(val As Integer) Me.val = val End Sub Shared Operator -(x As B1, y As B1) As B1 System.Console.WriteLine("{0} - {1}", x, y) Return New B1(x.val - y.val) End Operator End Class Sub Main() For i = New B1(0) To New B1(3) Step New B1(2) System.Console.WriteLine("Body {0}", i) Next End Sub End Module ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) CompilationUtils.AssertTheseDiagnostics(compilation, <expected><![CDATA[ BC33038: Type 'Module1.B1' must define operator '+' to be used in a 'For' statement. For i = New B1(0) To New B1(3) Step New B1(2) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC33038: Type 'Module1.B1' must define operator '<=' to be used in a 'For' statement. For i = New B1(0) To New B1(3) Step New B1(2) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC33038: Type 'Module1.B1' must define operator '>=' to be used in a 'For' statement. For i = New B1(0) To New B1(3) Step New B1(2) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></expected>) End Sub <Fact> Public Sub MissingLeGe() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Option Strict Off Imports System Module Module1 Class B1 Private val As Integer Public Sub New(val As Integer) Me.val = val End Sub Shared Operator +(x As B1, y As B1) As B1 System.Console.WriteLine("{0} + {1}", x, y) Return New B1(x.val + y.val) End Operator Shared Operator -(x As B1, y As B1) As B1 System.Console.WriteLine("{0} - {1}", x, y) Return New B1(x.val - y.val) End Operator End Class Sub Main() For i = New B1(0) To New B1(3) Step New B1(2) System.Console.WriteLine("Body {0}", i) Next End Sub End Module ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) CompilationUtils.AssertTheseDiagnostics(compilation, <expected><![CDATA[ BC33038: Type 'Module1.B1' must define operator '<=' to be used in a 'For' statement. For i = New B1(0) To New B1(3) Step New B1(2) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC33038: Type 'Module1.B1' must define operator '>=' to be used in a 'For' statement. For i = New B1(0) To New B1(3) Step New B1(2) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></expected>) End Sub <Fact> Public Sub MissingLe() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Option Strict Off Imports System Module Module1 Class B1 Private val As Integer Public Sub New(val As Integer) Me.val = val End Sub Shared Operator +(x As B1, y As B1) As B1 System.Console.WriteLine("{0} + {1}", x, y) Return New B1(x.val + y.val) End Operator Shared Operator -(x As B1, y As B1) As B1 System.Console.WriteLine("{0} - {1}", x, y) Return New B1(x.val - y.val) End Operator Shared Operator >=(x As B1, y As B1) As Boolean Return Nothing End Operator End Class Sub Main() For i = New B1(0) To New B1(3) Step New B1(2) System.Console.WriteLine("Body {0}", i) Next End Sub End Module ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) CompilationUtils.AssertTheseDiagnostics(compilation, <expected><![CDATA[ BC33033: Matching '<=' operator is required for 'Public Shared Operator >=(x As Module1.B1, y As Module1.B1) As Boolean'. Shared Operator >=(x As B1, y As B1) As Boolean ~~ BC33038: Type 'Module1.B1' must define operator '<=' to be used in a 'For' statement. For i = New B1(0) To New B1(3) Step New B1(2) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></expected>) End Sub <Fact> Public Sub MissingGe() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Option Strict Off Imports System Module Module1 Class B1 Private val As Integer Public Sub New(val As Integer) Me.val = val End Sub Shared Operator +(x As B1, y As B1) As B1 System.Console.WriteLine("{0} + {1}", x, y) Return New B1(x.val + y.val) End Operator Shared Operator -(x As B1, y As B1) As B1 System.Console.WriteLine("{0} - {1}", x, y) Return New B1(x.val - y.val) End Operator Shared Operator <=(x As B1, y As B1) As Boolean Return Nothing End Operator End Class Sub Main() For i = New B1(0) To New B1(3) Step New B1(2) System.Console.WriteLine("Body {0}", i) Next End Sub End Module ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) CompilationUtils.AssertTheseDiagnostics(compilation, <expected><![CDATA[ BC33033: Matching '>=' operator is required for 'Public Shared Operator <=(x As Module1.B1, y As Module1.B1) As Boolean'. Shared Operator <=(x As B1, y As B1) As Boolean ~~ BC33038: Type 'Module1.B1' must define operator '>=' to be used in a 'For' statement. For i = New B1(0) To New B1(3) Step New B1(2) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></expected>) End Sub <Fact> Public Sub MissingAddSubAndNonBooleanReturnOfLeGe() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Option Strict Off Imports System Module Module1 Class B1 Private val As Integer Public Sub New(val As Integer) Me.val = val End Sub Shared Operator <=(x As B1, y As B1) As B1 Return Nothing End Operator Shared Operator >=(x As B1, y As B1) As B1 Return Nothing End Operator End Class Sub Main() For i = New B1(0) To New B1(3) Step New B1(2) System.Console.WriteLine("Body {0}", i) Next End Sub End Module ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) CompilationUtils.AssertTheseDiagnostics(compilation, <expected><![CDATA[ BC30311: Value of type 'Module1.B1' cannot be converted to 'Boolean'. For i = New B1(0) To New B1(3) Step New B1(2) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC33038: Type 'Module1.B1' must define operator '-' to be used in a 'For' statement. For i = New B1(0) To New B1(3) Step New B1(2) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC33038: Type 'Module1.B1' must define operator '+' to be used in a 'For' statement. For i = New B1(0) To New B1(3) Step New B1(2) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></expected>) End Sub <Fact> Public Sub InvalidOperators1() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Option Strict Off Imports System Module Module1 Class B1 Private val As Integer Public Sub New(val As Integer) Me.val = val End Sub Shared Widening Operator CType(x As Integer) As B1 Return New B1(x) End Operator Shared Widening Operator CType(x As B1) As Integer Return x.val End Operator Shared Operator +(x As B1, y As B1) As Integer Return Nothing End Operator Shared Operator -(x As B1, y As Integer) As B1 Return Nothing End Operator Shared Operator >=(x As Integer, y As B1) As Boolean Return Nothing End Operator Shared Operator <=(x As Integer, y As B1) As Boolean Return Nothing End Operator End Class Sub Main() For i = New B1(0) To New B1(3) Step New B1(2) System.Console.WriteLine("Body {0}", i) Next End Sub End Module ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) CompilationUtils.AssertTheseDiagnostics(compilation, <expected><![CDATA[ BC33039: Return and parameter types of 'Public Shared Operator -(x As Module1.B1, y As Integer) As Module1.B1' must be 'Module1.B1' to be used in a 'For' statement. For i = New B1(0) To New B1(3) Step New B1(2) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC33039: Return and parameter types of 'Public Shared Operator +(x As Module1.B1, y As Module1.B1) As Integer' must be 'Module1.B1' to be used in a 'For' statement. For i = New B1(0) To New B1(3) Step New B1(2) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC33040: Parameter types of 'Public Shared Operator <=(x As Integer, y As Module1.B1) As Boolean' must be 'Module1.B1' to be used in a 'For' statement. For i = New B1(0) To New B1(3) Step New B1(2) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC33040: Parameter types of 'Public Shared Operator >=(x As Integer, y As Module1.B1) As Boolean' must be 'Module1.B1' to be used in a 'For' statement. For i = New B1(0) To New B1(3) Step New B1(2) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></expected>) End Sub <Fact> Public Sub InvalidOperators2() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Option Strict Off Imports System Module Module1 Structure B1 Shared Widening Operator CType(x As Integer) As B1 Return Nothing End Operator Shared Widening Operator CType(x As B1) As Integer Return Nothing End Operator Shared Operator +(x As B1, y As B1) As B2 Return Nothing End Operator Shared Operator -(x As B1, y As B2) As B1 Return Nothing End Operator Shared Operator >=(x As B2?, y As B1) As Boolean Return Nothing End Operator Shared Operator <=(x As B2?, y As B1) As Boolean Return Nothing End Operator End Structure Structure B2 Shared Widening Operator CType(x As B1) As B2 Return Nothing End Operator End Structure Sub Main() For i = New B1?() To New B1?() Step New B1?() Next End Sub End Module ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) CompilationUtils.AssertTheseDiagnostics(compilation, <expected><![CDATA[ BC33039: Return and parameter types of 'Public Shared Operator -(x As Module1.B1, y As Module1.B2) As Module1.B1' must be 'Module1.B1' to be used in a 'For' statement. For i = New B1?() To New B1?() Step New B1?() ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC33039: Return and parameter types of 'Public Shared Operator +(x As Module1.B1, y As Module1.B1) As Module1.B2' must be 'Module1.B1' to be used in a 'For' statement. For i = New B1?() To New B1?() Step New B1?() ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC33040: Parameter types of 'Public Shared Operator <=(x As Module1.B2?, y As Module1.B1) As Boolean' must be 'Module1.B1?' to be used in a 'For' statement. For i = New B1?() To New B1?() Step New B1?() ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC33040: Parameter types of 'Public Shared Operator >=(x As Module1.B2?, y As Module1.B1) As Boolean' must be 'Module1.B1?' to be used in a 'For' statement. For i = New B1?() To New B1?() Step New B1?() ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></expected>) End Sub End Class End Namespace
' 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.IO Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.SpecialType Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.OverloadResolution Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Public Class UserDefinedForToLoop Inherits BasicTestBase <Fact> Public Sub BasicTest1() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Option Strict Off Imports System Module Module1 Class B1 Private val As Integer Public Sub New(val As Integer) Me.val = val End Sub Shared Operator +(x As B1, y As B1) As B1 System.Console.WriteLine("{0} + {1}", x, y) Return New B1(x.val + y.val) End Operator Shared Operator -(x As B1, y As B1) As B1 System.Console.WriteLine("{0} - {1}", x, y) Return New B1(x.val - y.val) End Operator Shared Operator >=(x As B1, y As B1) As Boolean System.Console.WriteLine("{0} >= {1}", x, y) Return x.val >= y.val End Operator Shared Operator <=(x As B1, y As B1) As Boolean System.Console.WriteLine("{0} <= {1}", x, y) Return x.val <= y.val End Operator Public Overrides Function ToString() As String Return String.Format("B({0})", val) End Function End Class Class B2 Public Val As B1 End Class Dim m_Index As New B2() ReadOnly Property Index As B2 Get System.Console.WriteLine("get_Index") Return m_Index End Get End Property Function Init(val As Integer) As B1 System.Console.WriteLine("Init") Return New B1(val) End Function Function [Step](val As Integer) As B1 System.Console.WriteLine("Step") Return New B1(Val) End Function Function Limit(val As Integer) As B1 System.Console.WriteLine("Limit") Return New B1(Val) End Function Sub Main() For Index.Val = Init(0) To Limit(3) Step [Step](2) System.Console.WriteLine("Body {0}", m_Index.Val) Next System.Console.WriteLine("-----") For Index.Val = Init(3) To Limit(0) Step [Step](-2) System.Console.WriteLine("Body {0}", m_Index.Val) Next End Sub End Module ]]></file> </compilation> Dim verifier = CompileAndVerify(compilationDef, expectedOutput:= <![CDATA[ get_Index Init Limit Step B(2) - B(2) B(2) >= B(0) get_Index B(0) <= B(3) Body B(0) get_Index get_Index B(0) + B(2) get_Index B(2) <= B(3) Body B(2) get_Index get_Index B(2) + B(2) get_Index B(4) <= B(3) ----- get_Index Init Limit Step B(-2) - B(-2) B(-2) >= B(0) get_Index B(3) >= B(0) Body B(3) get_Index get_Index B(3) + B(-2) get_Index B(1) >= B(0) Body B(1) get_Index get_Index B(1) + B(-2) get_Index B(-1) >= B(0) ]]>) End Sub <Fact> Public Sub BasicTest2() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Option Strict Off Imports System Module Module1 Class B1 Private val As Integer Public Sub New(val As Integer) Me.val = val End Sub Shared Operator +(x As B1, y As B1) As B1 System.Console.WriteLine("{0} + {1}", x, y) Return New B1(x.val + y.val) End Operator Shared Operator -(x As B1, y As B1) As B1 System.Console.WriteLine("{0} - {1}", x, y) Return New B1(x.val - y.val) End Operator Shared Operator >=(x As B1, y As B1) As B3 Dim str = String.Format("{0} >= {1}", x, y) System.Console.WriteLine(str) Return New B3(x.val >= y.val, str) End Operator Shared Operator <=(x As B1, y As B1) As B3 Dim str = String.Format("{0} <= {1}", x, y) System.Console.WriteLine(str) Return New B3(x.val <= y.val, str) End Operator Public Overrides Function ToString() As String Return String.Format("B({0})", val) End Function End Class Class B3 Private val As Boolean Private str As String Public Sub New(val As Boolean, str As String) Me.val = val Me.str = str End Sub Shared Operator IsTrue(x As B3) As Boolean System.Console.WriteLine("B3({0}).IsTrue", x.str) Return x.val End Operator Shared Operator IsFalse(x As B3) As Boolean System.Console.WriteLine("B3({0}).IsFalse", x.str) Return x.val End Operator End Class Function Init(val As Integer) As B1 System.Console.WriteLine("Init") Return New B1(val) End Function Function [Step](val As Integer) As B1 System.Console.WriteLine("Step") Return New B1(Val) End Function Function Limit(val As Integer) As B1 System.Console.WriteLine("Limit") Return New B1(Val) End Function Sub Main() For i = Init(0) To Limit(3) Step [Step](2) System.Console.WriteLine("Body {0}", i) Next System.Console.WriteLine("-----") For i = Init(3) To Limit(0) Step [Step](-2) System.Console.WriteLine("Body {0}", i) Next End Sub End Module ]]></file> </compilation> Dim verifier = CompileAndVerify(compilationDef, expectedOutput:= <![CDATA[ Init Limit Step B(2) - B(2) B(2) >= B(0) B3(B(2) >= B(0)).IsTrue B(0) <= B(3) B3(B(0) <= B(3)).IsTrue Body B(0) B(0) + B(2) B(2) <= B(3) B3(B(2) <= B(3)).IsTrue Body B(2) B(2) + B(2) B(4) <= B(3) B3(B(4) <= B(3)).IsTrue ----- Init Limit Step B(-2) - B(-2) B(-2) >= B(0) B3(B(-2) >= B(0)).IsTrue B(3) >= B(0) B3(B(3) >= B(0)).IsTrue Body B(3) B(3) + B(-2) B(1) >= B(0) B3(B(1) >= B(0)).IsTrue Body B(1) B(1) + B(-2) B(-1) >= B(0) B3(B(-1) >= B(0)).IsTrue ]]>) End Sub <Fact> Public Sub BasicTest3() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Option Strict Off Imports System Module Module1 Class B1 Private val As Integer Public Sub New(val As Integer) Me.val = val End Sub Shared Widening Operator CType(x As Integer) As B1 System.Console.WriteLine("CType({0}) As B1", x) Return New B1(x) End Operator Shared Operator +(x As B1, y As B1) As B1 System.Console.WriteLine("{0} + {1}", x, y) Return New B1(x.val + y.val) End Operator Shared Operator -(x As B1, y As B1) As B1 System.Console.WriteLine("{0} - {1}", x, y) Return New B1(x.val - y.val) End Operator Shared Operator >=(x As B1, y As B1) As B3 Dim str = String.Format("{0} >= {1}", x, y) System.Console.WriteLine(str) Return New B3(x.val >= y.val, str) End Operator Shared Operator <=(x As B1, y As B1) As B3 Dim str = String.Format("{0} <= {1}", x, y) System.Console.WriteLine(str) Return New B3(x.val <= y.val, str) End Operator Public Overrides Function ToString() As String Return String.Format("B({0})", val) End Function End Class Class B3 Private val As Boolean Private str As String Public Sub New(val As Boolean, str As String) Me.val = val Me.str = str End Sub Shared Operator IsTrue(x As B3) As Boolean System.Console.WriteLine("B3({0}).IsTrue", x.str) Return x.val End Operator Shared Operator IsFalse(x As B3) As Boolean System.Console.WriteLine("B3({0}).IsFalse", x.str) Return x.val End Operator End Class Function Init(val As Integer) As B1 System.Console.WriteLine("Init") Return New B1(val) End Function Function [Step](val As Integer) As B1 System.Console.WriteLine("Step") Return New B1(Val) End Function Function Limit(val As Integer) As B1 System.Console.WriteLine("Limit") Return New B1(Val) End Function Sub Main() For i = Init(0) To Limit(3) System.Console.WriteLine("Body {0}", i) Next End Sub End Module ]]></file> </compilation> Dim verifier = CompileAndVerify(compilationDef, expectedOutput:= <![CDATA[ Init Limit CType(1) As B1 B(1) - B(1) B(1) >= B(0) B3(B(1) >= B(0)).IsTrue B(0) <= B(3) B3(B(0) <= B(3)).IsTrue Body B(0) B(0) + B(1) B(1) <= B(3) B3(B(1) <= B(3)).IsTrue Body B(1) B(1) + B(1) B(2) <= B(3) B3(B(2) <= B(3)).IsTrue Body B(2) B(2) + B(1) B(3) <= B(3) B3(B(3) <= B(3)).IsTrue Body B(3) B(3) + B(1) B(4) <= B(3) B3(B(4) <= B(3)).IsTrue ]]>) End Sub <Fact(), WorkItem(544375, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544375")> Public Sub BasicTest4() Dim compilationDef = <compilation name="BasicTest4"> <file name="a.vb"><![CDATA[ Option Strict On Imports System Structure S Class C Private val As Boolean Private str As String Public Sub New(val As Boolean, str As String) Me.val = val Me.str = str End Sub Shared Operator IsTrue(x As C) As Boolean Console.WriteLine("C({0}).IsTrue", x.str) Return x.val End Operator Shared Operator IsFalse(x As C) As Boolean Console.WriteLine("C({0}).IsFalse", x.str) Return x.val End Operator End Class Private val As Integer Public Sub New(val As Integer) Me.val = val End Sub Shared Widening Operator CType(x As Integer) As S Console.WriteLine("CType({0}) As S", x) Return New S(x) End Operator Shared Operator +(x As S, y As S) As S Console.WriteLine("{0} + {1}", x, y) Return New S(x.val + y.val) End Operator Shared Operator -(x As S, y As S) As S Console.WriteLine("{0} - {1}", x, y) Return New S(x.val - y.val) End Operator Shared Operator >=(x As S, y As S) As C Dim str = String.Format("{0} >= {1}", x, y) Console.WriteLine(str) Return New C(x.val >= y.val, str) End Operator Shared Operator <=(x As S, y As S) As C Dim str = String.Format("{0} <= {1}", x, y) Console.WriteLine(str) Return New C(x.val <= y.val, str) End Operator Public Overrides Function ToString() As String Return String.Format("S({0})", val) End Function End Structure Module Module1 Sub Main() For i As S = Nothing To Nothing Console.WriteLine("Body {0}", i) Next End Sub End Module ]]></file> </compilation> Dim verifier = CompileAndVerify(compilationDef, expectedOutput:= <![CDATA[ CType(1) As S S(1) - S(1) S(1) >= S(0) C(S(1) >= S(0)).IsTrue S(0) <= S(0) C(S(0) <= S(0)).IsTrue Body S(0) S(0) + S(1) S(1) <= S(0) C(S(1) <= S(0)).IsTrue ]]>) End Sub <Fact> Public Sub MissingCInt() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Option Strict Off Imports System Module Module1 Class B1 Private val As Integer Public Sub New(val As Integer) Me.val = val End Sub End Class Sub Main() For i = New B1(0) To New B1(3) System.Console.WriteLine("Body {0}", i) Next End Sub End Module ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30311: Value of type 'Integer' cannot be converted to 'Module1.B1'. For i = New B1(0) To New B1(3) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact> Public Sub MissingAddSubtractLeGe() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Option Strict Off Imports System Module Module1 Class B1 Private val As Integer Public Sub New(val As Integer) Me.val = val End Sub End Class Sub Main() For i = New B1(0) To New B1(3) Step New B1(2) System.Console.WriteLine("Body {0}", i) Next End Sub End Module ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) CompilationUtils.AssertTheseDiagnostics(compilation, <expected><![CDATA[ BC33038: Type 'Module1.B1' must define operator '+' to be used in a 'For' statement. For i = New B1(0) To New B1(3) Step New B1(2) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC33038: Type 'Module1.B1' must define operator '-' to be used in a 'For' statement. For i = New B1(0) To New B1(3) Step New B1(2) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC33038: Type 'Module1.B1' must define operator '<=' to be used in a 'For' statement. For i = New B1(0) To New B1(3) Step New B1(2) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC33038: Type 'Module1.B1' must define operator '>=' to be used in a 'For' statement. For i = New B1(0) To New B1(3) Step New B1(2) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></expected>) End Sub <Fact> Public Sub MissingSubtractLeGe() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Option Strict Off Imports System Module Module1 Class B1 Private val As Integer Public Sub New(val As Integer) Me.val = val End Sub Shared Operator +(x As B1, y As B1) As B1 System.Console.WriteLine("{0} + {1}", x, y) Return New B1(x.val + y.val) End Operator End Class Sub Main() For i = New B1(0) To New B1(3) Step New B1(2) System.Console.WriteLine("Body {0}", i) Next End Sub End Module ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) CompilationUtils.AssertTheseDiagnostics(compilation, <expected><![CDATA[ BC33038: Type 'Module1.B1' must define operator '-' to be used in a 'For' statement. For i = New B1(0) To New B1(3) Step New B1(2) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC33038: Type 'Module1.B1' must define operator '<=' to be used in a 'For' statement. For i = New B1(0) To New B1(3) Step New B1(2) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC33038: Type 'Module1.B1' must define operator '>=' to be used in a 'For' statement. For i = New B1(0) To New B1(3) Step New B1(2) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></expected>) End Sub <Fact> Public Sub MissingAddLeGe() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Option Strict Off Imports System Module Module1 Class B1 Private val As Integer Public Sub New(val As Integer) Me.val = val End Sub Shared Operator -(x As B1, y As B1) As B1 System.Console.WriteLine("{0} - {1}", x, y) Return New B1(x.val - y.val) End Operator End Class Sub Main() For i = New B1(0) To New B1(3) Step New B1(2) System.Console.WriteLine("Body {0}", i) Next End Sub End Module ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) CompilationUtils.AssertTheseDiagnostics(compilation, <expected><![CDATA[ BC33038: Type 'Module1.B1' must define operator '+' to be used in a 'For' statement. For i = New B1(0) To New B1(3) Step New B1(2) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC33038: Type 'Module1.B1' must define operator '<=' to be used in a 'For' statement. For i = New B1(0) To New B1(3) Step New B1(2) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC33038: Type 'Module1.B1' must define operator '>=' to be used in a 'For' statement. For i = New B1(0) To New B1(3) Step New B1(2) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></expected>) End Sub <Fact> Public Sub MissingLeGe() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Option Strict Off Imports System Module Module1 Class B1 Private val As Integer Public Sub New(val As Integer) Me.val = val End Sub Shared Operator +(x As B1, y As B1) As B1 System.Console.WriteLine("{0} + {1}", x, y) Return New B1(x.val + y.val) End Operator Shared Operator -(x As B1, y As B1) As B1 System.Console.WriteLine("{0} - {1}", x, y) Return New B1(x.val - y.val) End Operator End Class Sub Main() For i = New B1(0) To New B1(3) Step New B1(2) System.Console.WriteLine("Body {0}", i) Next End Sub End Module ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) CompilationUtils.AssertTheseDiagnostics(compilation, <expected><![CDATA[ BC33038: Type 'Module1.B1' must define operator '<=' to be used in a 'For' statement. For i = New B1(0) To New B1(3) Step New B1(2) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC33038: Type 'Module1.B1' must define operator '>=' to be used in a 'For' statement. For i = New B1(0) To New B1(3) Step New B1(2) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></expected>) End Sub <Fact> Public Sub MissingLe() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Option Strict Off Imports System Module Module1 Class B1 Private val As Integer Public Sub New(val As Integer) Me.val = val End Sub Shared Operator +(x As B1, y As B1) As B1 System.Console.WriteLine("{0} + {1}", x, y) Return New B1(x.val + y.val) End Operator Shared Operator -(x As B1, y As B1) As B1 System.Console.WriteLine("{0} - {1}", x, y) Return New B1(x.val - y.val) End Operator Shared Operator >=(x As B1, y As B1) As Boolean Return Nothing End Operator End Class Sub Main() For i = New B1(0) To New B1(3) Step New B1(2) System.Console.WriteLine("Body {0}", i) Next End Sub End Module ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) CompilationUtils.AssertTheseDiagnostics(compilation, <expected><![CDATA[ BC33033: Matching '<=' operator is required for 'Public Shared Operator >=(x As Module1.B1, y As Module1.B1) As Boolean'. Shared Operator >=(x As B1, y As B1) As Boolean ~~ BC33038: Type 'Module1.B1' must define operator '<=' to be used in a 'For' statement. For i = New B1(0) To New B1(3) Step New B1(2) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></expected>) End Sub <Fact> Public Sub MissingGe() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Option Strict Off Imports System Module Module1 Class B1 Private val As Integer Public Sub New(val As Integer) Me.val = val End Sub Shared Operator +(x As B1, y As B1) As B1 System.Console.WriteLine("{0} + {1}", x, y) Return New B1(x.val + y.val) End Operator Shared Operator -(x As B1, y As B1) As B1 System.Console.WriteLine("{0} - {1}", x, y) Return New B1(x.val - y.val) End Operator Shared Operator <=(x As B1, y As B1) As Boolean Return Nothing End Operator End Class Sub Main() For i = New B1(0) To New B1(3) Step New B1(2) System.Console.WriteLine("Body {0}", i) Next End Sub End Module ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) CompilationUtils.AssertTheseDiagnostics(compilation, <expected><![CDATA[ BC33033: Matching '>=' operator is required for 'Public Shared Operator <=(x As Module1.B1, y As Module1.B1) As Boolean'. Shared Operator <=(x As B1, y As B1) As Boolean ~~ BC33038: Type 'Module1.B1' must define operator '>=' to be used in a 'For' statement. For i = New B1(0) To New B1(3) Step New B1(2) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></expected>) End Sub <Fact> Public Sub MissingAddSubAndNonBooleanReturnOfLeGe() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Option Strict Off Imports System Module Module1 Class B1 Private val As Integer Public Sub New(val As Integer) Me.val = val End Sub Shared Operator <=(x As B1, y As B1) As B1 Return Nothing End Operator Shared Operator >=(x As B1, y As B1) As B1 Return Nothing End Operator End Class Sub Main() For i = New B1(0) To New B1(3) Step New B1(2) System.Console.WriteLine("Body {0}", i) Next End Sub End Module ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) CompilationUtils.AssertTheseDiagnostics(compilation, <expected><![CDATA[ BC30311: Value of type 'Module1.B1' cannot be converted to 'Boolean'. For i = New B1(0) To New B1(3) Step New B1(2) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC33038: Type 'Module1.B1' must define operator '+' to be used in a 'For' statement. For i = New B1(0) To New B1(3) Step New B1(2) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC33038: Type 'Module1.B1' must define operator '-' to be used in a 'For' statement. For i = New B1(0) To New B1(3) Step New B1(2) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></expected>) End Sub <Fact> Public Sub InvalidOperators1() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Option Strict Off Imports System Module Module1 Class B1 Private val As Integer Public Sub New(val As Integer) Me.val = val End Sub Shared Widening Operator CType(x As Integer) As B1 Return New B1(x) End Operator Shared Widening Operator CType(x As B1) As Integer Return x.val End Operator Shared Operator +(x As B1, y As B1) As Integer Return Nothing End Operator Shared Operator -(x As B1, y As Integer) As B1 Return Nothing End Operator Shared Operator >=(x As Integer, y As B1) As Boolean Return Nothing End Operator Shared Operator <=(x As Integer, y As B1) As Boolean Return Nothing End Operator End Class Sub Main() For i = New B1(0) To New B1(3) Step New B1(2) System.Console.WriteLine("Body {0}", i) Next End Sub End Module ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) CompilationUtils.AssertTheseDiagnostics(compilation, <expected><![CDATA[ BC33039: Return and parameter types of 'Public Shared Operator +(x As Module1.B1, y As Module1.B1) As Integer' must be 'Module1.B1' to be used in a 'For' statement. For i = New B1(0) To New B1(3) Step New B1(2) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC33039: Return and parameter types of 'Public Shared Operator -(x As Module1.B1, y As Integer) As Module1.B1' must be 'Module1.B1' to be used in a 'For' statement. For i = New B1(0) To New B1(3) Step New B1(2) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC33040: Parameter types of 'Public Shared Operator <=(x As Integer, y As Module1.B1) As Boolean' must be 'Module1.B1' to be used in a 'For' statement. For i = New B1(0) To New B1(3) Step New B1(2) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC33040: Parameter types of 'Public Shared Operator >=(x As Integer, y As Module1.B1) As Boolean' must be 'Module1.B1' to be used in a 'For' statement. For i = New B1(0) To New B1(3) Step New B1(2) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></expected>) End Sub <Fact> Public Sub InvalidOperators2() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Option Strict Off Imports System Module Module1 Structure B1 Shared Widening Operator CType(x As Integer) As B1 Return Nothing End Operator Shared Widening Operator CType(x As B1) As Integer Return Nothing End Operator Shared Operator +(x As B1, y As B1) As B2 Return Nothing End Operator Shared Operator -(x As B1, y As B2) As B1 Return Nothing End Operator Shared Operator >=(x As B2?, y As B1) As Boolean Return Nothing End Operator Shared Operator <=(x As B2?, y As B1) As Boolean Return Nothing End Operator End Structure Structure B2 Shared Widening Operator CType(x As B1) As B2 Return Nothing End Operator End Structure Sub Main() For i = New B1?() To New B1?() Step New B1?() Next End Sub End Module ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) CompilationUtils.AssertTheseDiagnostics(compilation, <expected><![CDATA[ BC33039: Return and parameter types of 'Public Shared Operator +(x As Module1.B1, y As Module1.B1) As Module1.B2' must be 'Module1.B1' to be used in a 'For' statement. For i = New B1?() To New B1?() Step New B1?() ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC33039: Return and parameter types of 'Public Shared Operator -(x As Module1.B1, y As Module1.B2) As Module1.B1' must be 'Module1.B1' to be used in a 'For' statement. For i = New B1?() To New B1?() Step New B1?() ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC33040: Parameter types of 'Public Shared Operator <=(x As Module1.B2?, y As Module1.B1) As Boolean' must be 'Module1.B1?' to be used in a 'For' statement. For i = New B1?() To New B1?() Step New B1?() ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC33040: Parameter types of 'Public Shared Operator >=(x As Module1.B2?, y As Module1.B1) As Boolean' must be 'Module1.B1?' to be used in a 'For' statement. For i = New B1?() To New B1?() Step New B1?() ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></expected>) End Sub End Class End Namespace
1
dotnet/roslyn
56,011
React to string comparison changing on .NET Core
The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
jaredpar
"2021-08-30T17:18:52Z"
"2021-08-30T20:20:04Z"
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
4d99cda6e446e77dbb302e26388c1093bd3ef569
React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
./src/Compilers/VisualBasic/Test/Symbol/DocumentationComments/DocCommentTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.Test.Utilities Imports System.Xml.Linq Imports System.Text Imports System.IO Imports Roslyn.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.VisualBasicCompilation Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class DocCommentTests Inherits BasicTestBase Private Shared ReadOnly s_optionsDiagnoseDocComments As VisualBasicParseOptions = VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose) <Fact> Public Sub DocCommentWriteException() Dim sources = <compilation name="DocCommentException"> <file name="a.vb"> <![CDATA[ ''' <summary> ''' Doc comment for <see href="C" /> ''' </summary> Public Class C ''' <summary> ''' Doc comment for method M ''' </summary> Public Sub M() End Sub End Class ]]> </file> </compilation> Using (new EnsureEnglishUICulture()) Dim comp = CreateCompilationWithMscorlib40(sources) Dim diags = New DiagnosticBag() Dim badStream = New BrokenStream() badStream.BreakHow = BrokenStream.BreakHowType.ThrowOnWrite DocumentationCommentCompiler.WriteDocumentationCommentXml( comp, assemblyName:=Nothing, xmlDocStream:=badStream, diagnostics:=New BindingDiagnosticBag(diags), cancellationToken:=Nothing) AssertTheseDiagnostics(diags.ToReadOnlyAndFree(), <errors><![CDATA[ BC37258: Error writing to XML documentation file: I/O error occurred. ]]></errors>) End Using End Sub <Fact> Public Sub NoXmlResolver() Dim sources = <compilation name="DocumentationMode"> <file name="a.vb"> <![CDATA[ ''' <summary> <include file='abc' path='def' /> </summary> Class C End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40( sources, options:=TestOptions.ReleaseDll.WithXmlReferenceResolver(Nothing), parseOptions:=TestOptions.Regular.WithDocumentationMode(DocumentationMode.Parse)) compilation.VerifyDiagnostics() CheckXmlDocument(compilation, expectedDocXml:= <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> DocumentationMode </name> </assembly> <members> <member name="T:C"> <summary> <!--warning BC42321: Unable to include XML fragment 'def' of file 'abc'. References to XML documents are not supported.--> </summary> </member> </members> </doc> ]]> </xml>, ensureEnglishUICulture:=True) End Sub <Fact> Public Sub DocumentationMode_None() Dim sources = <compilation name="DocumentationMode"> <file name="a.vb"> <![CDATA[ Imports System ''' <summary> </summary Module Module0 End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( sources, parseOptions:=(New VisualBasicParseOptions()).WithDocumentationMode(DocumentationMode.None)) Dim tree = compilation.SyntaxTrees(0) Dim moduleStatement = tree.FindNodeOrTokenByKind(SyntaxKind.ModuleStatement) Assert.True(moduleStatement.IsNode) Dim node = moduleStatement.AsNode() Dim trivia = node.GetLeadingTrivia().ToArray() Assert.True(trivia.Any(Function(x) x.Kind = SyntaxKind.CommentTrivia)) Assert.False(trivia.Any(Function(x) x.Kind = SyntaxKind.DocumentationCommentTrivia)) CompilationUtils.AssertTheseDiagnostics(compilation.GetSemanticModel(tree).GetDiagnostics(), <errors></errors>) End Sub <Fact> Public Sub DocumentationMode_Parse() Dim sources = <compilation name="DocumentationMode"> <file name="a.vb"> <![CDATA[ Imports System ''' <summary> </summary Module Module0 End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( sources, parseOptions:=(New VisualBasicParseOptions()).WithDocumentationMode(DocumentationMode.Parse)) Dim tree = compilation.SyntaxTrees(0) Dim moduleStatement = tree.FindNodeOrTokenByKind(SyntaxKind.ModuleStatement) Assert.True(moduleStatement.IsNode) Dim node = moduleStatement.AsNode() Dim trivia = node.GetLeadingTrivia().ToArray() Assert.False(trivia.Any(Function(x) x.Kind = SyntaxKind.CommentTrivia)) Assert.True(trivia.Any(Function(x) x.Kind = SyntaxKind.DocumentationCommentTrivia)) CompilationUtils.AssertTheseDiagnostics(compilation.GetSemanticModel(tree).GetDiagnostics(), <errors></errors>) End Sub <Fact> Public Sub DocumentationMode_ParseAndDiagnose() Dim sources = <compilation name="DocumentationMode"> <file name="a.vb"> <![CDATA[ Imports System ''' <summary> </summary Module Module0 End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( sources, parseOptions:=s_optionsDiagnoseDocComments) Dim tree = compilation.SyntaxTrees(0) Dim moduleStatement = tree.FindNodeOrTokenByKind(SyntaxKind.ModuleStatement) Assert.True(moduleStatement.IsNode) Dim node = moduleStatement.AsNode() Dim trivia = node.GetLeadingTrivia().ToArray() Assert.False(trivia.Any(Function(x) x.Kind = SyntaxKind.CommentTrivia)) Assert.True(trivia.Any(Function(x) x.Kind = SyntaxKind.DocumentationCommentTrivia)) CompilationUtils.AssertTheseDiagnostics(compilation.GetSemanticModel(tree).GetDiagnostics(), <errors> <![CDATA[ BC42304: XML documentation parse error: '>' expected. XML comment will be ignored. ''' <summary> </summary ~ ]]> </errors>) End Sub <Fact> Public Sub DocCommentOnUnsupportedSymbol() CompileCheckDiagnosticsAndXmlDocument( <compilation name="EmptyCref"> <file name="a.vb"> <![CDATA[ Imports System Class E ReadOnly Property quoteForTheDay() As String ''' <summary></summary> Get Return "hello" End Get End Property End Class ]]> </file> </compilation>, <error> <![CDATA[ BC42312: XML documentation comments must precede member or type declarations. ''' <summary></summary> ~~~~~~~~~~~~~~~~~~~~~ ]]> </error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> EmptyCref </name> </assembly> <members> </members> </doc> ]]> </xml>) End Sub <WorkItem(720931, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720931")> <Fact> Public Sub Bug720931() Dim compilation = CompileCheckDiagnosticsAndXmlDocument( <compilation name="EmptyCref"> <file name="a.vb"> <![CDATA[ Imports System ''' <see cref="Integer"/> ''' <see cref="UShort"/> ''' <see cref="Object"/> ''' <see cref="Date"/> Public Class CLAZZ End Class ]]> </file> </compilation>, <error></error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> EmptyCref </name> </assembly> <members> <member name="T:CLAZZ"> <see cref="T:System.Int32"/> <see cref="T:System.UInt16"/> <see cref="T:System.Object"/> <see cref="T:System.DateTime"/> </member> </members> </doc> ]]> </xml>) End Sub <WorkItem(705788, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/705788")> <Fact> Public Sub Bug705788() Dim compilation = CompileCheckDiagnosticsAndXmlDocument( <compilation name="Bug705788"> <file name="a.vb"> <![CDATA[ Imports System ''' <c name="Scenario1"/> ''' <code name="Scenario1"/> ''' <example name="Scenario1"/> ''' <list name="Scenario1"/> ''' <paramref name="Scenario1"/> ''' <remarks name="Scenario1"/> ''' <summary name="Scenario1"/> Module Scenario1 ''' <para name="Scenario2"/> ''' <paramref name="Scenario2"/> ''' <permission cref="Scenario2" name="Scenario2"/> ''' <see cref="Scenario2" name="Scenario2"/> ''' <seealso cref="Scenario2" name="Scenario2"/> Class Scenario2 End Class Sub Main() End Sub End Module ]]> </file> </compilation>, <error> <![CDATA[ BC42306: XML comment tag 'paramref' is not permitted on a 'module' language element. ''' <paramref name="Scenario1"/> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'paramref' is not permitted on a 'class' language element. ''' <paramref name="Scenario2"/> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]> </error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> Bug705788 </name> </assembly> <members> <member name="T:Scenario1"> <c name="Scenario1"/> <code name="Scenario1"/> <example name="Scenario1"/> <list name="Scenario1"/> <paramref name="Scenario1"/> <remarks name="Scenario1"/> <summary name="Scenario1"/> </member> <member name="T:Scenario1.Scenario2"> <para name="Scenario2"/> <paramref name="Scenario2"/> <permission cref="T:Scenario1.Scenario2" name="Scenario2"/> <see cref="T:Scenario1.Scenario2" name="Scenario2"/> <seealso cref="T:Scenario1.Scenario2" name="Scenario2"/> </member> </members> </doc> ]]> </xml>) End Sub <WorkItem(658453, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/658453")> <Fact> Public Sub Bug658453() Dim compilation = CompileCheckDiagnosticsAndXmlDocument( <compilation name="EmptyCref"> <file name="a.vb"> <![CDATA[ Imports System Namespace Microsoft.VisualBasic ''' <summary> ''' Provides core iterator implementation. ''' </summary> ''' <typeparam name="TState">Type of iterator state data.</typeparam> ''' <typeparam name="TItem">Type of items returned from the iterator.</typeparam> ''' <param name="state">Iteration data.</param> ''' <param name="item">Element produced at this step.</param> ''' <returns>Whether the step was successful.</returns> Friend Delegate Function IteratorStep(Of TState, TItem)( ByRef state As TState, ByRef item As TItem) As Boolean End Namespace ]]> </file> </compilation>, <error></error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> EmptyCref </name> </assembly> <members> <member name="T:Microsoft.VisualBasic.IteratorStep`2"> <summary> Provides core iterator implementation. </summary> <typeparam name="TState">Type of iterator state data.</typeparam> <typeparam name="TItem">Type of items returned from the iterator.</typeparam> <param name="state">Iteration data.</param> <param name="item">Element produced at this step.</param> <returns>Whether the step was successful.</returns> </member> </members> </doc> ]]> </xml>) Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "TState").ToArray() Assert.Equal(2, names.Length) CheckSymbolInfoAndTypeInfo(model, names(0), "TState") End Sub <WorkItem(762687, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/762687")> <Fact> Public Sub Bug762687a() CompileCheckDiagnosticsAndXmlDocument( <compilation name="Bug762687"> <file name="a.vb"> <![CDATA[ Imports System Class B Public Property System As Object End Class Class D Inherits B ''' <see cref="System.Console"/> Public X As Integer End Class ]]> </file> </compilation>, <error></error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> Bug762687 </name> </assembly> <members> <member name="F:D.X"> <see cref="T:System.Console"/> </member> </members> </doc> ]]> </xml>) End Sub <WorkItem(762687, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/762687")> <Fact> Public Sub Bug762687b() CompileCheckDiagnosticsAndXmlDocument( <compilation name="Bug762687"> <file name="a.vb"> <![CDATA[ Imports System Class B Public Property System As Object End Class Class D Inherits B ''' <see cref="System.Console.WriteLine()"/> Public X As Integer End Class ]]> </file> </compilation>, <error></error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> Bug762687 </name> </assembly> <members> <member name="F:D.X"> <see cref="M:System.Console.WriteLine"/> </member> </members> </doc> ]]> </xml>) End Sub <WorkItem(664943, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/664943")> <Fact> Public Sub Bug664943() CompileCheckDiagnosticsAndXmlDocument( <compilation name="EmptyCref"> <file name="a.vb"> <![CDATA[ Imports System ''' <summary></summary> ''' Class E End Class ]]> </file> </compilation>, <error></error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> EmptyCref </name> </assembly> <members> <member name="T:E"> <summary></summary> </member> </members> </doc> ]]> </xml>) End Sub <WorkItem(679833, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/679833")> <Fact> Public Sub Bug679833_DontCrash() CompileCheckDiagnosticsAndXmlDocument( <compilation name="EmptyCref"> <file name="a.vb"> <![CDATA[ Public Sub New() d Sub Public ''' As String ''' summary> End Enum ]]> </file> </compilation>, <error> <![CDATA[ BC30203: Identifier expected. Public ~ BC30026: 'End Sub' expected. Sub New() ~~~~~~~~~ BC30451: 'd' is not declared. It may be inaccessible due to its protection level. d Sub ~ BC36673: Multiline lambda expression is missing 'End Sub'. d Sub ~~~ BC30800: Method arguments must be enclosed in parentheses. d Sub ~~~~ BC30198: ')' expected. d Sub ~ BC30199: '(' expected. d Sub ~ BC30203: Identifier expected. Public ''' As String ~ BC42302: XML comment must be the first statement on a line. XML comment will be ignored. Public ''' As String ~~~~~~~~~~~~~ BC42303: XML comment cannot appear within a method or a property. XML comment will be ignored. ''' ~ BC30201: Expression expected. summary> ~ BC30800: Method arguments must be enclosed in parentheses. summary> ~ BC30201: Expression expected. summary> ~ BC30184: 'End Enum' must be preceded by a matching 'Enum'. End Enum ~~~~~~~~ ]]> </error>) End Sub <WorkItem(665883, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/665883")> <Fact> Public Sub Bug665883() CompileCheckDiagnosticsAndXmlDocument( <compilation name="EmptyCref"> <file name="a.vb"> <![CDATA[ Imports System ''' <see cref="Console.WriteLine"/> Module M End Module ]]> </file> </compilation>, <error></error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> EmptyCref </name> </assembly> <members> <member name="T:M"> <see cref="M:System.Console.WriteLine"/> </member> </members> </doc> ]]> </xml>) End Sub <WorkItem(666241, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/666241")> <Fact> Public Sub Bug666241() Dim compilation = CompileCheckDiagnosticsAndXmlDocument( <compilation name="EmptyCref"> <file name="a.vb"> <![CDATA[ Imports System Namespace System.Drawing ''' <summary> ''' Opt-In flag to look for resources in the another assembly ''' with the "bitmapSuffix" config setting ''' </summary> <AttributeUsage(AttributeTargets.Assembly)> Friend Class BitmapSuffixInSatelliteAssemblyAttribute Inherits Attribute End Class End Namespace ]]> </file> <file name="b.vb"> <![CDATA[ Imports System.Diagnostics.CodeAnalysis Namespace Microsoft.VisualBasic.PowerPacks.Printing.Compatibility.VB6 Public Module SystemColorConstants ''' <include file='doc\Constants.uex' path='docs/doc[@for="SystemColorConstants.vbScrollBars"]/*' /> <SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")> _ <SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")> _ Public Const vbScrollBars As Integer = &H80000000 End Module End Namespace ]]> </file> </compilation>, <error></error>) Dim model = compilation.GetSemanticModel(compilation.SyntaxTrees(0)) CompilationUtils.AssertTheseDiagnostics(model.GetDiagnostics(), <error></error>) model = compilation.GetSemanticModel(compilation.SyntaxTrees(1)) CompilationUtils.AssertTheseDiagnostics(model.GetDiagnostics(), <error></error>) End Sub <WorkItem(658793, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/658793")> <Fact> Public Sub Bug658793() CompileCheckDiagnosticsAndXmlDocument( <compilation name="EmptyCref"> <file name="a.vb"> <![CDATA[ Imports System ''' <summary cref="(" /> ''' Class E End Class ]]> </file> </compilation>, <error> <![CDATA[ BC42309: XML comment has a tag with a 'cref' attribute '(' that could not be resolved. ''' <summary cref="(" /> ~~~~~~~~ ]]> </error>) End Sub <WorkItem(721582, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/721582")> <Fact> Public Sub Bug721582() CompileCheckDiagnosticsAndXmlDocument( <compilation name="EmptyCref"> <file name="a.vb"> <![CDATA[ Imports System ''' <see cref="object"/> ''' <see cref="object.tostring"/> ''' <see cref="system.object"/> ''' <see cref="system.object.tostring"/> ''' <see cref="object.tostring()"/> ''' <see cref="system.object.tostring()"/> Class E End Class ]]> </file> </compilation>, <error></error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> EmptyCref </name> </assembly> <members> <member name="T:E"> <see cref="T:System.Object"/> <see cref="T:System.Object"/> <see cref="T:System.Object"/> <see cref="M:System.Object.ToString"/> <see cref="T:System.Object"/> <see cref="M:System.Object.ToString"/> </member> </members> </doc> ]]> </xml>) End Sub <WorkItem(657426, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/657426")> <Fact> Public Sub Bug657426() CompileCheckDiagnosticsAndXmlDocument( <compilation name="EmptyCref"> <file name="a.vb"> <![CDATA[ Imports System ''' <summary> ''' <see ''' cref="Int32"/> ''' </summary> Class E End Class ]]> </file> </compilation>, <error></error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> EmptyCref </name> </assembly> <members> <member name="T:E"> <summary> <see cref="T:System.Int32"/> </summary> </member> </members> </doc> ]]> </xml>) End Sub <WorkItem(658322, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/658322")> <Fact> Public Sub Bug658322a() CompileCheckDiagnosticsAndXmlDocument( <compilation name="EmptyCref"> <file name="a.vb"> <![CDATA[ Imports System Class E ''' <param name="next">The next binder.</param> Public Sub New([next] As Integer) End Sub End Class ]]> </file> </compilation>, <error></error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> EmptyCref </name> </assembly> <members> <member name="M:E.#ctor(System.Int32)"> <param name="next">The next binder.</param> </member> </members> </doc> ]]> </xml>) End Sub <WorkItem(658322, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/658322")> <Fact> Public Sub Bug658322b() CompileCheckDiagnosticsAndXmlDocument( <compilation name="EmptyCref"> <file name="a.vb"> <![CDATA[ Imports System Namespace Roslyn.Compilers.VisualBasic Partial Class BoundAddressOfOperator ''' <returns>The <see cref="Binder.DelegateResolutionResult">Binder.DelegateResolutionResult</see> for the conversion </returns> Friend Function GetDelegateResolutionResult(ByRef delegateResolutionResult As Binder.DelegateResolutionResult) As Boolean Return Nothing End Function Public Property Binder As Binder End Class End Namespace ]]> </file> <file name="b.vb"> <![CDATA[ Imports System Namespace Roslyn.Compilers.VisualBasic Partial Friend Class Binder Friend Structure DelegateResolutionResult End Structure End Class End Namespace ]]> </file> </compilation>, <error></error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> EmptyCref </name> </assembly> <members> <member name="M:Roslyn.Compilers.VisualBasic.BoundAddressOfOperator.GetDelegateResolutionResult(Roslyn.Compilers.VisualBasic.Binder.DelegateResolutionResult@)"> <returns>The <see cref="T:Roslyn.Compilers.VisualBasic.Binder.DelegateResolutionResult">Binder.DelegateResolutionResult</see> for the conversion </returns> </member> </members> </doc> ]]> </xml>) End Sub <WorkItem(658322, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/658322")> <Fact> Public Sub Bug658322c() CompileCheckDiagnosticsAndXmlDocument( <compilation name="EmptyCref"> <file name="a.vb"> <![CDATA[ Imports System Namespace Roslyn.Compilers.VisualBasic Partial Class BoundAddressOfOperator ''' <returns>The <see cref="Binder.DelegateResolutionResult">Binder.DelegateResolutionResult</see> for the conversion </returns> Friend Function GetDelegateResolutionResult(ByRef delegateResolutionResult As Binder.DelegateResolutionResult) As Boolean Return Nothing End Function Public Binder As Binder End Class End Namespace ]]> </file> <file name="b.vb"> <![CDATA[ Imports System Namespace Roslyn.Compilers.VisualBasic Partial Friend Class Binder Friend Structure DelegateResolutionResult End Structure End Class End Namespace ]]> </file> </compilation>, <error></error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> EmptyCref </name> </assembly> <members> <member name="M:Roslyn.Compilers.VisualBasic.BoundAddressOfOperator.GetDelegateResolutionResult(Roslyn.Compilers.VisualBasic.Binder.DelegateResolutionResult@)"> <returns>The <see cref="T:Roslyn.Compilers.VisualBasic.Binder.DelegateResolutionResult">Binder.DelegateResolutionResult</see> for the conversion </returns> </member> </members> </doc> ]]> </xml>) End Sub <WorkItem(658322, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/658322")> <Fact> Public Sub Bug658322d() CompileCheckDiagnosticsAndXmlDocument( <compilation name="EmptyCref"> <file name="a.vb"> <![CDATA[ Imports System Namespace Roslyn.Compilers.VisualBasic Partial Class BoundAddressOfOperator ''' <returns>The <see cref="Binder.DelegateResolutionResult">Binder.DelegateResolutionResult</see> for the conversion </returns> Friend Function GetDelegateResolutionResult(ByRef delegateResolutionResult As Binder.DelegateResolutionResult) As Boolean Return Nothing End Function Public Function Binder() As Binder Return Nothing End Function End Class End Namespace ]]> </file> <file name="b.vb"> <![CDATA[ Imports System Namespace Roslyn.Compilers.VisualBasic Partial Friend Class Binder Friend Structure DelegateResolutionResult End Structure End Class End Namespace ]]> </file> </compilation>, <error></error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> EmptyCref </name> </assembly> <members> <member name="M:Roslyn.Compilers.VisualBasic.BoundAddressOfOperator.GetDelegateResolutionResult(Roslyn.Compilers.VisualBasic.Binder.DelegateResolutionResult@)"> <returns>The <see cref="T:Roslyn.Compilers.VisualBasic.Binder.DelegateResolutionResult">Binder.DelegateResolutionResult</see> for the conversion </returns> </member> </members> </doc> ]]> </xml>) End Sub <WorkItem(658322, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/658322")> <Fact()> Public Sub Bug658322e() Dim compilation = CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Option Explicit On Imports System Public Class TAttribute : Inherits Attribute End Class ''' <remarks cref="TAttribute">Clazz</remarks> <TAttribute> Public Class Clazz ''' <remarks cref="TAttribute">Clazz</remarks> <TAttribute> Public d As Integer End Class ''' <remarks cref="TAttribute">Clazz</remarks> <TAttribute> Public Enum E1 ''' <remarks cref="TAttribute">Clazz</remarks> <TAttribute> Any End Enum ]]> </file> </compilation>, <error></error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:Clazz"> <remarks cref="T:TAttribute">Clazz</remarks> </member> <member name="F:Clazz.d"> <remarks cref="T:TAttribute">Clazz</remarks> </member> <member name="T:E1"> <remarks cref="T:TAttribute">Clazz</remarks> </member> <member name="F:E1.Any"> <remarks cref="T:TAttribute">Clazz</remarks> </member> </members> </doc> ]]> </xml>) Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "TAttribute").ToArray() Assert.Equal(8, names.Length) CheckSymbolInfoAndTypeInfo(model, names(0), "TAttribute") CheckSymbolInfoAndTypeInfo(model, names(2), "TAttribute") CheckSymbolInfoAndTypeInfo(model, names(4), "TAttribute") CheckSymbolInfoAndTypeInfo(model, names(6), "TAttribute") End Sub <WorkItem(665961, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/665961")> <Fact()> Public Sub Bug665961() Dim compilation = CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Module M Sub Main() ''' <see cref="x"/> Dim x End Sub End Module ]]> </file> </compilation>, <error> <![CDATA[ BC42303: XML comment cannot appear within a method or a property. XML comment will be ignored. ''' <see cref="x"/> ~~~~~~~~~~~~~~~~~ BC42024: Unused local variable: 'x'. Dim x ~ ]]> </error>) Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "x").ToArray() Assert.Equal(1, names.Length) CheckSymbolInfoAndTypeInfo(model, names(0)) Assert.Equal("Public Sub Main()", TryCast(model, SemanticModel).GetEnclosingSymbol(names(0).SpanStart).ToDisplayString()) End Sub <WorkItem(685473, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/685473")> <ConditionalFact(GetType(WindowsDesktopOnly), Reason:=ConditionalSkipReason.TestExecutionNeedsDesktopTypes)> Public Sub Bug685473() CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System.CodeDom Namespace ABCD.PRODUCT.Current.SDK.Legacy.PackageGenerator '''------------</------------------------------------------------ ''' Project : ABCD.PRODUCT.Current.SDK.Legacy ''' Class : ProvideAutomationObject ''' '''------------------------------------------------ ''' <summary> ''' This class models the ProvideAutomationObject attribute ''' in Project : ABCD.PRODUCT.Current.SDK.Legacyry> ''' [user] 11/17/2004 Created ''' </history> '''-------If--------------------------------------- P lic Class ProvideAutomationObject : Inherits VsipCodeAttributeGenerator Public ObjectName As String = Nothing Public Description As String = Nothing '''------------------------------------------------ ''' <summary> ''' Generates the code for this element ''' </summary> ''' <returns>A string representing the code</returns> '''------------------------------------------------ Public Overrides Function Generate() As String ObjectNametr As New CodeAttributeDeclaration(Me.GetAttributeName()) attr.Arguments.Add(New CodeAttributeArgument(New CodePrimitiveExpressi=n(ObjectName))) If Not Description = Nothing hen attr.Arguments.Add(New C------------------------------------------------itiveExpression(Description))) End If Return PackageCodeGenerator.GetAttributeCode(attr) End Functio End Class End Namespace ]]> </file> </compilation>, <error> <![CDATA[BC42312: XML documentation comments must precede member or type declarations. '''------------</------------------------------------------------ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42304: XML documentation parse error: XML end element must be preceded by a matching start element. XML comment will be ignored. '''------------</------------------------------------------------ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42304: XML documentation parse error: Character '-' (&H2D) is not allowed at the beginning of an XML name. XML comment will be ignored. '''------------</------------------------------------------------ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42304: XML documentation parse error: '>' expected. XML comment will be ignored. '''------------</------------------------------------------------ ~ BC42304: XML documentation parse error: Syntax error. XML comment will be ignored. ''' Project : ABCD.PRODUCT.Current.SDK.Legacy ~~~~~~~ BC42304: XML documentation parse error: Element is missing an end tag. XML comment will be ignored. ''' <summary> ~~~~~~~~~ BC42304: XML documentation parse error: End tag </summary> expected. XML comment will be ignored. ''' </history> ~~~~~~~~~~ BC30188: Declaration expected. lic Class ProvideAutomationObject : Inherits VsipCodeAttributeGenerator ~~~ BC30002: Type 'VsipCodeAttributeGenerator' is not defined. lic Class ProvideAutomationObject : Inherits VsipCodeAttributeGenerator ~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30027: 'End Function' expected. Public Overrides Function Generate() As String ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30284: function 'Generate' cannot be declared 'Overrides' because it does not override a function in a base class. Public Overrides Function Generate() As String ~~~~~~~~ BC30451: 'ObjectNametr' is not declared. It may be inaccessible due to its protection level. ObjectNametr As New CodeAttributeDeclaration(Me.GetAttributeName()) ~~~~~~~~~~~~ BC30201: Expression expected. ObjectNametr As New CodeAttributeDeclaration(Me.GetAttributeName()) ~ BC30800: Method arguments must be enclosed in parentheses. ObjectNametr As New CodeAttributeDeclaration(Me.GetAttributeName()) ~ BC30451: 'attr' is not declared. It may be inaccessible due to its protection level. attr.Arguments.Add(New CodeAttributeArgument(New CodePrimitiveExpressi=n(ObjectName))) ~~~~ BC30002: Type 'CodePrimitiveExpressi' is not defined. attr.Arguments.Add(New CodeAttributeArgument(New CodePrimitiveExpressi=n(ObjectName))) ~~~~~~~~~~~~~~~~~~~~~ BC30451: 'n' is not declared. It may be inaccessible due to its protection level. attr.Arguments.Add(New CodeAttributeArgument(New CodePrimitiveExpressi=n(ObjectName))) ~ BC30451: 'hen' is not declared. It may be inaccessible due to its protection level. hen ~~~ BC30451: 'attr' is not declared. It may be inaccessible due to its protection level. attr.Arguments.Add(New C------------------------------------------------itiveExpression(Description))) ~~~~ BC30002: Type 'C' is not defined. attr.Arguments.Add(New C------------------------------------------------itiveExpression(Description))) ~ BC30451: 'itiveExpression' is not declared. It may be inaccessible due to its protection level. attr.Arguments.Add(New C------------------------------------------------itiveExpression(Description))) ~~~~~~~~~~~~~~~ BC30205: End of statement expected. attr.Arguments.Add(New C------------------------------------------------itiveExpression(Description))) ~ BC30451: 'PackageCodeGenerator' is not declared. It may be inaccessible due to its protection level. Return PackageCodeGenerator.GetAttributeCode(attr) ~~~~~~~~~~~~~~~~~~~~ BC30451: 'attr' is not declared. It may be inaccessible due to its protection level. Return PackageCodeGenerator.GetAttributeCode(attr) ~~~~ BC30615: 'End' statement cannot be used in class library projects. End Functio ~~~ BC30678: 'End' statement not valid. End Functio ~~~ ]]> </error>) End Sub <Fact> Public Sub DocCommentOnUnsupportedSymbol_ParseOnly() CompileCheckDiagnosticsAndXmlDocument( <compilation name="EmptyCref"> <file name="a.vb"> <![CDATA[ Imports System Class E ReadOnly Property quoteForTheDay() As String ''' <summary></summary> Get Return "hello" End Get End Property End Class ]]> </file> </compilation>, <error></error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> EmptyCref </name> </assembly> <members> </members> </doc> ]]> </xml>, withDiagnostics:=False) End Sub <Fact> Public Sub EmptyCref() CompileCheckDiagnosticsAndXmlDocument( <compilation name="EmptyCref"> <file name="a.vb"> <![CDATA[ Imports System ''' <summary> ''' See <see cref=""/>. ''' </summary> ''' <remarks></remarks> Module Module0 End Module ]]> </file> </compilation>, <error> <![CDATA[ BC42309: XML comment has a tag with a 'cref' attribute '' that could not be resolved. ''' See <see cref=""/>. ~~~~~~~ ]]> </error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> EmptyCref </name> </assembly> <members> <member name="T:Module0"> <summary> See <see cref="!:"/>. </summary> <remarks></remarks> </member> </members> </doc> ]]> </xml>) End Sub <Fact> Public Sub Cref_Error() CompileCheckDiagnosticsAndXmlDocument( <compilation name="EmptyCref"> <file name="a.vb"> <![CDATA[ Imports System ''' <summary> ''' See <see cref="Module0."/>. ''' See <see cref="Module0. ''' "/>. ''' See <see cref="Module0 ''' "/>. ''' See <see cref="Module0.' ''' "/>. ''' See <see cref="Module0. _ ''' "/>. ''' </summary> ''' <remarks></remarks> Module Module0 End Module ]]> </file> </compilation>, <error> <![CDATA[ BC42309: XML comment has a tag with a 'cref' attribute 'Module0.' that could not be resolved. ''' See <see cref="Module0."/>. ~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'Module0. '''' that could not be resolved. ''' See <see cref="Module0. ~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'Module0.'' that could not be resolved. ''' See <see cref="Module0.' ~~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'Module0. _' that could not be resolved. ''' See <see cref="Module0. _ ~~~~~~~~~~~~~~~~~ ]]> </error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> EmptyCref </name> </assembly> <members> <member name="T:Module0"> <summary> See <see cref="!:Module0."/>. See <see cref="!:Module0. "/>. See <see cref="T:Module0"/>. See <see cref="!:Module0.' "/>. See <see cref="!:Module0. _ "/>. </summary> <remarks></remarks> </member> </members> </doc> ]]> </xml>) End Sub <Fact> Public Sub Cref_Me_MyBase_MyClass() CompileCheckDiagnosticsAndXmlDocument( <compilation name="EmptyCref"> <file name="a.vb"> <![CDATA[ Imports System Public Class BaseClass Public Overridable Sub S() End Sub End Class Public Class DerivedClass : Inherits BaseClass Public Overrides Sub S() End Sub ''' <summary> ''' <see cref="Me.S"/> ''' <see cref="MyClass.S"/> ''' <see cref="MyBase.S"/> ''' </summary> Public F As Integer End Class ]]> </file> </compilation>, <error> <![CDATA[ BC42309: XML comment has a tag with a 'cref' attribute 'Me.S' that could not be resolved. ''' <see cref="Me.S"/> ~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'MyClass.S' that could not be resolved. ''' <see cref="MyClass.S"/> ~~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'MyBase.S' that could not be resolved. ''' <see cref="MyBase.S"/> ~~~~~~~~~~~~~~~ ]]> </error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> EmptyCref </name> </assembly> <members> <member name="F:DerivedClass.F"> <summary> <see cref="!:Me.S"/> <see cref="!:MyClass.S"/> <see cref="!:MyBase.S"/> </summary> </member> </members> </doc> ]]> </xml>) End Sub <Fact> Public Sub Cref_Type_Namespace_Alias() CompileCheckDiagnosticsAndXmlDocument( <compilation name="EmptyCref"> <file name="a.vb"> <![CDATA[ Imports System Imports ABC = System.Collections.Generic Imports ABCD = System.Collections.Generic.IList(Of Integer) Public Class BaseClass ''' <summary> ''' <see cref="System.Collections.Generic"/> ''' <see cref="System.Collections.Generic.IList(Of Integer)"/> ''' <see cref="ABC"/> ''' <see cref="ABC.IList(Of Integer)"/> ''' <see cref="ABCD"/> ''' </summary> Public F As Integer End Class ]]> </file> </compilation>, <error></error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> EmptyCref </name> </assembly> <members> <member name="F:BaseClass.F"> <summary> <see cref="N:System.Collections.Generic"/> <see cref="T:System.Collections.Generic.IList`1"/> <see cref="N:System.Collections.Generic"/> <see cref="T:System.Collections.Generic.IList`1"/> <see cref="T:System.Collections.Generic.IList`1"/> </summary> </member> </members> </doc> ]]> </xml>) End Sub <Fact> Public Sub Name_Error() ' NOTE: the first error is a breaking change CompileCheckDiagnosticsAndXmlDocument( <compilation name="EmptyCref"> <file name="a.vb"> <![CDATA[ Imports System ''' <typeparam name="X ''' "/> ''' <typeparam name="X 'abc ''' "/> Class Clazz(Of X) End Class ]]> </file> </compilation>, <error> <![CDATA[ BC42317: XML comment type parameter 'X ' does not match a type parameter on the corresponding 'class' statement. ''' <typeparam name="X ~~~~~~~~ BC42317: XML comment type parameter 'X 'abc ' does not match a type parameter on the corresponding 'class' statement. ''' <typeparam name="X 'abc ~~~~~~~~~~~~~ ]]> </error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> EmptyCref </name> </assembly> <members> <member name="T:Clazz`1"> <typeparam name="X "/> <typeparam name="X 'abc "/> </member> </members> </doc> ]]> </xml>) End Sub <Fact> Public Sub Cref_Error_ParseOnly() CompileCheckDiagnosticsAndXmlDocument( <compilation name="EmptyCref"> <file name="a.vb"> <![CDATA[ Imports System ''' <summary> ''' See <see cref="Module0."/>. ''' See <see cref="Module0. ''' "/>. ''' See <see cref="Module0 ''' "/>. ''' See <see cref="Module0.' ''' "/>. ''' See <see cref="Module0. _ ''' "/>. ''' </summary> ''' <remarks></remarks> Module Module0 End Module ]]> </file> </compilation>, <error></error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> EmptyCref </name> </assembly> <members> <member name="T:Module0"> <summary> See <see cref="!:Module0."/>. See <see cref="!:Module0. "/>. See <see cref="T:Module0"/>. See <see cref="!:Module0.' "/>. See <see cref="!:Module0. _ "/>. </summary> <remarks></remarks> </member> </members> </doc> ]]> </xml>, withDiagnostics:=False) End Sub <Fact> Public Sub Name_Error_ParseOnly() CompileCheckDiagnosticsAndXmlDocument( <compilation name="EmptyCref"> <file name="a.vb"> <![CDATA[ Imports System ''' <typeparam name="X ''' "/> ''' <typeparam name="X 'abc ''' "/> Class Clazz(Of X) End Class ]]> </file> </compilation>, <error></error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> EmptyCref </name> </assembly> <members> <member name="T:Clazz`1"> <typeparam name="X "/> <typeparam name="X 'abc "/> </member> </members> </doc> ]]> </xml>, withDiagnostics:=False) End Sub <Fact> Public Sub DiagnosticsWithoutEmit() CompileCheckDiagnosticsAndXmlDocument( <compilation name="DiagnosticsWithoutEmit"> <file name="a.vb"> <![CDATA[ Imports System ''' <summary> ''' See <see cref=""/>. ''' </summary> ''' <remarks></remarks> Module Module0 End Module ]]> </file> </compilation>, <error> <![CDATA[ BC42309: XML comment has a tag with a 'cref' attribute '' that could not be resolved. ''' See <see cref=""/>. ~~~~~~~ ]]> </error>, Nothing) End Sub <Fact> Public Sub GeneralDocCommentOnTypes() CompileCheckDiagnosticsAndXmlDocument( <compilation name="GeneralDocCommentOnTypes"> <file name="a.vb"> <![CDATA[ Imports System ''' <summary> ''' Module M ''' commented ''' </summary> Module Module0 End Module ''' <summary> ''' Enum ''' ---======7777777%%% ''' </summary> Enum E123 E1 End Enum ''' <summary> ''' Structure ''' <a></a> iusgdfas '''ciii###### ''' </summary> Structure STR End Structure ''' <summary> ''' ------ Class -------- ''' With nested structure ''' --------------------- ''' </summary> Class Clazz ''' <summary> ''' NestedStr ''' sadjghfcasl ''' asdf ''' 21398470912 '''ciii###### ''' </summary> Public Structure NestedStr End Structure End Class ]]> </file> </compilation>, <error></error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> GeneralDocCommentOnTypes </name> </assembly> <members> <member name="T:Module0"> <summary> Module M commented </summary> </member> <member name="T:E123"> <summary> Enum ---======7777777%%% </summary> </member> <member name="T:STR"> <summary> Structure <a></a> iusgdfas ciii###### </summary> </member> <member name="T:Clazz"> <summary> ------ Class -------- With nested structure --------------------- </summary> </member> <member name="T:Clazz.NestedStr"> <summary> NestedStr sadjghfcasl asdf 21398470912 ciii###### </summary> </member> </members> </doc> ]]> </xml>) End Sub <Fact> Public Sub MultipartDocCommentOnTypes() CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System ''' <summary> ''' Class Part #1 ''' -=-=-=-=-=-=- <aaa> ' Error -- unended tag ''' (o) ''' </summary> Public Partial Class Clazz End Class ''' <summary> ''' (o) ''' Class Part #2 ''' -=-=-=-=-=-=- ''' </summary> Public Partial Class Clazz End Class ]]> </file> </compilation>, <error> <![CDATA[ BC42314: XML comment cannot be applied more than once on a partial class. XML comments for this class will be ignored. ''' <summary> ~~~~~~~~~~~ BC42304: XML documentation parse error: Element is missing an end tag. XML comment will be ignored. ''' -=-=-=-=-=-=- <aaa> ' Error -- unended tag ~~~~~ BC42304: XML documentation parse error: '>' expected. XML comment will be ignored. ''' </summary> ~ BC42304: XML documentation parse error: Expected beginning '<' for an XML tag. XML comment will be ignored. ''' </summary> ~ BC42304: XML documentation parse error: XML name expected. XML comment will be ignored. ''' </summary> ~ BC42314: XML comment cannot be applied more than once on a partial class. XML comments for this class will be ignored. ''' <summary> ~~~~~~~~~~~ ]]> </error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> </members> </doc> ]]> </xml>) End Sub <Fact> Public Sub DocCommentAndAccessibility() CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System ''' <summary> ''' ''' -=( Clazz(Of X, Y) )=- ''' ''' </summary> Public Class Clazz(Of X, Y) ''' <summary> ''' -=( Clazz(Of X, Y).PublicClazz )=- ''' </summary> Public Class PublicClazz End Class ''' <summary> ''' -=( Clazz(Of X, Y).PrivateClazz )=- ''' </summary> Private Class PrivateClazz End Class End Class ''' <summary> ''' ''' -=( Clazz(Of X) )=- ''' ''' </summary> Friend Class Clazz(Of X) ''' <summary> ''' -=( Clazz(Of X).PublicClazz )=- ''' </summary> Public Class PublicClazz End Class ''' <summary> ''' -=( Clazz(Of X).PrivateClazz )=- ''' </summary> Private Class PrivateClazz End Class End Class ]]> </file> </compilation>, <error></error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:Clazz`2"> <summary> -=( Clazz(Of X, Y) )=- </summary> </member> <member name="T:Clazz`2.PublicClazz"> <summary> -=( Clazz(Of X, Y).PublicClazz )=- </summary> </member> <member name="T:Clazz`2.PrivateClazz"> <summary> -=( Clazz(Of X, Y).PrivateClazz )=- </summary> </member> <member name="T:Clazz`1"> <summary> -=( Clazz(Of X) )=- </summary> </member> <member name="T:Clazz`1.PublicClazz"> <summary> -=( Clazz(Of X).PublicClazz )=- </summary> </member> <member name="T:Clazz`1.PrivateClazz"> <summary> -=( Clazz(Of X).PrivateClazz )=- </summary> </member> </members> </doc> ]]> </xml>) End Sub <ConditionalFact(GetType(DesktopOnly), Reason:="https://github.com/dotnet/roslyn/issues/18610")> Public Sub IllegalXmlInDocComment() CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System ''' <summary> ''' ''' -=( <a> )=- ''' ''' </summary> Public Class Clazz(Of X, Y) End Class ]]> </file> </compilation>, <error> <![CDATA[ BC42304: XML documentation parse error: Element is missing an end tag. XML comment will be ignored. ''' -=( <a> )=- ~~~ BC42304: XML documentation parse error: '>' expected. XML comment will be ignored. ''' </summary> ~ BC42304: XML documentation parse error: Expected beginning '<' for an XML tag. XML comment will be ignored. ''' </summary> ~ BC42304: XML documentation parse error: XML name expected. XML comment will be ignored. ''' </summary> ~ ]]> </error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> </members> </doc> ]]> </xml>) End Sub <ConditionalFact(GetType(DesktopOnly), Reason:="https://github.com/dotnet/roslyn/issues/18610")> Public Sub IllegalXmlInDocComment_Schema() CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System ''' <summary> ''' ''' -=( <a x="1" x="2"/> )=- ''' ''' </summary> Public Class Clazz(Of X, Y) End Class ]]> </file> </compilation>, <error> <![CDATA[ BC42304: XML documentation parse error: 'x' is a duplicate attribute name. XML comment will be ignored. ''' <summary> ~~~~~~~~~~~ ]]> </error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> </members> </doc> ]]> </xml>, ensureEnglishUICulture:=True) End Sub <Fact> Public Sub GeneralDocCommentOnFields() CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System ''' <summary> ''' Class ''' Clazz(Of X, Y) ''' Comment ''' </summary> Public Class Clazz(Of X, Y) ''' <summary> (* F1 *) </summary> Public F1 As Integer ''' <summary> ''' F@ 2 % ''' </summary> Private F2 As Integer End Class ]]> </file> </compilation>, <error></error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:Clazz`2"> <summary> Class Clazz(Of X, Y) Comment </summary> </member> <member name="F:Clazz`2.F1"> <summary> (* F1 *) </summary> </member> <member name="F:Clazz`2.F2"> <summary> F@ 2 % </summary> </member> </members> </doc> ]]> </xml>) End Sub <Fact> Public Sub GeneralDocCommentOnEnumConstants() CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System ''' <summary> ''' Some ''' documentation ''' comment ''' </summary> ''' <remarks></remarks> Public Enum En ''' <summary> Just the first value </summary> First ''' <summary> ''' Another value ''' </summary> ''' <remarks></remarks> Second End Enum ]]> </file> </compilation>, <error></error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:En"> <summary> Some documentation comment </summary> <remarks></remarks> </member> <member name="F:En.First"> <summary> Just the first value </summary> </member> <member name="F:En.Second"> <summary> Another value </summary> ''' <remarks></remarks> </member> </members> </doc> ]]> </xml>) End Sub <Fact> Public Sub GeneralDocCommentOnEvents() CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System ''' <summary> Class Clazz(Of X, Y) ''' </summary> Public Class ubClazz(Of X, Y) ''' <summary> ''' (* E(X) </summary> ''' <param name="f1"></param> Public Event E(f1 As X) ''' <summary> Sub P(X,Y) </summary> Private Shared Event P As Action(Of X, Y) End Class ]]> </file> </compilation>, <error></error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:ubClazz`2"> <summary> Class Clazz(Of X, Y) </summary> </member> <member name="E:ubClazz`2.E"> <summary> (* E(X) </summary> <param name="f1"></param> </member> <member name="E:ubClazz`2.P"> <summary> Sub P(X,Y) </summary> </member> </members> </doc> ]]> </xml>) End Sub <Fact> Public Sub GeneralDocCommentOnProperties() CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System ''' <summary> Class Clazz(Of X, Y) </summary> Public Class ubClazz(Of X, Y) ''' <summary> ''' P1</summary> Public Shared Property P1 As Integer ''' <summary> ''' S P(X,Y) ''' </summary> ''' <param name="A"></param> Private ReadOnly Property P2(a As Integer) As String Get Return Nothing End Get End Property End Class ]]> </file> </compilation>, <error></error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:ubClazz`2"> <summary> Class Clazz(Of X, Y) </summary> </member> <member name="P:ubClazz`2.P1"> <summary> P1</summary> </member> <member name="P:ubClazz`2.P2(System.Int32)"> <summary> S P(X,Y) </summary> <param name="A"></param> </member> </members> </doc> ]]> </xml>) End Sub <Fact> Public Sub GeneralDocCommentOnMethods() CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System ''' <summary> Class Clazz(Of X, Y) </summary> Partial Public Class Clazz(Of X, Y) ''' <summary>.cctor()</summary> Shared Sub New() End Sub ''' <summary> F32(Integer) As Integer </summary> ''' <param name="a"></param> ''' <returns></returns> Protected Function F32(a As Integer) As Integer Return Nothing End Function ''' <summary> a*b </summary> Public Shared Operator *(a As Integer, b As Clazz(Of X, Y)) As Clazz(Of Integer, Integer) Return Nothing End Operator ''' <summary>DECL: Priv1(a As Integer)</summary> Partial Private Sub Priv1(a As Integer) End Sub Partial Private Sub Priv2(a As Integer) End Sub ''' <summary>DECL: Priv3(a As Integer)</summary> Partial Private Sub Priv3(a As Integer) End Sub ''' <summary>DECL: Priv4(a As Integer)</summary> Partial Private Sub Priv4(a As Integer) End Sub End Class Partial Public Class Clazz(Of X, Y) ''' <summary>.ctor()</summary> Public Sub New() End Sub ''' <summary> integer -> Clazz(Of X, Y) </summary> Public Shared Narrowing Operator CType(a As Integer) As Clazz(Of X, Y) Return Nothing End Operator ''' <summary>IMPL: Priv1(a As Integer)</summary> Private Sub Priv1(a As Integer) End Sub ''' <summary>IMPL: Priv2(a As Integer)</summary> Private Sub Priv2(a As Integer) End Sub Private Sub Priv3(a As Integer) End Sub End Class ]]> </file> </compilation>, <error></error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:Clazz`2"> <summary> Class Clazz(Of X, Y) </summary> </member> <member name="M:Clazz`2.#cctor"> <summary>.cctor()</summary> </member> <member name="M:Clazz`2.F32(System.Int32)"> <summary> F32(Integer) As Integer </summary> <param name="a"></param> <returns></returns> </member> <member name="M:Clazz`2.op_Multiply(System.Int32,Clazz{`0,`1})"> <summary> a*b </summary> </member> <member name="M:Clazz`2.Priv1(System.Int32)"> <summary>IMPL: Priv1(a As Integer)</summary> </member> <member name="M:Clazz`2.Priv2(System.Int32)"> <summary>IMPL: Priv2(a As Integer)</summary> </member> <member name="M:Clazz`2.Priv3(System.Int32)"> <summary>DECL: Priv3(a As Integer)</summary> </member> <member name="M:Clazz`2.Priv4(System.Int32)"> <summary>DECL: Priv4(a As Integer)</summary> </member> <member name="M:Clazz`2.#ctor"> <summary>.ctor()</summary> </member> <member name="M:Clazz`2.op_Explicit(System.Int32)~Clazz{`0,`1}"> <summary> integer -> Clazz(Of X, Y) </summary> </member> </members> </doc> ]]> </xml>) End Sub <Fact> Public Sub GeneralDocCommentOnDeclMethods() CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System ''' <summary> Class [[Clazz]] </summary> Public Class Clazz ''' <summary> ''' Declared function DeclareFtn ''' </summary> Public Declare Function DeclareFtn Lib "bar" () As Integer End Class ]]> </file> </compilation>, <error></error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:Clazz"> <summary> Class [[Clazz]] </summary> </member> <member name="M:Clazz.DeclareFtn"> <summary> Declared function DeclareFtn </summary> </member> </members> </doc> ]]> </xml>) End Sub <Fact> Public Sub Tags_Summary_C_Code_Example() CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System ''' <summary> ''' Some comment here ''' and here ''' ''' <example> e.g. ''' <code> ''' ' No further processing ''' If docCommentXml Is Nothing Then ''' Debug.Assert(documentedParameters Is Nothing) ''' Debug.Assert(documentedTypeParameters Is Nothing) ''' Return False ''' End If ''' </code> ''' Returns <c>False</c> in the statement above. ''' </example> ''' ''' Done. ''' </summary> ''' <summary a="1"> ''' </summary> ''' <code> ''' If docCommentXml Is Nothing Then ''' Return False ''' End If ''' </code> ''' <example> e.g. </example> ''' Returns <c>False</c> in the statement above. Public Class Clazz End Class ]]> </file> </compilation>, <error></error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:Clazz"> <summary> Some comment here and here <example> e.g. <code> ' No further processing If docCommentXml Is Nothing Then Debug.Assert(documentedParameters Is Nothing) Debug.Assert(documentedTypeParameters Is Nothing) Return False End If </code> Returns <c>False</c> in the statement above. </example> Done. </summary> <summary a="1"> </summary> <code> If docCommentXml Is Nothing Then Return False End If </code> <example> e.g. </example> Returns <c>False</c> in the statement above. </member> </members> </doc> ]]> </xml>) End Sub <Fact> Public Sub Tags_Exception_Errors() CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System ''' <exception cref="Exception">Module0</exception> Public Module Module0 End Module ''' <summary><exception cref="Exception">E inside summary tag</exception></summary> ''' <exception cref="Exception">Clazz</exception> Public Class Clazz(Of X) ''' <summary></summary> ''' <exception cref="11111">X1</exception> Public Sub X1() End Sub ''' <summary><exception cref="Exception">E inside summary tag</exception></summary> ''' <exception cref="Exception">E</exception> Public Event E As Action ''' <summary></summary> ''' <exception cref="X">X2</exception> Public Sub X2() End Sub ''' <summary></summary> ''' <exception cref="Exception">F</exception> Public F As Integer ''' <summary></summary> ''' <exception cref="Exception">P</exception> Public Property P As Integer ''' <summary></summary> ''' <exception cref="Exception">FDelegate</exception> Public Delegate Function FDelegate(a As Integer) As String ''' <summary></summary> ''' <exception cref="Exception">En</exception> Public Enum En : A : End Enum ''' <summary></summary> ''' <exception cref="Exception">STR</exception> Public Structure STR : End Structure ''' <summary></summary> ''' <exception cref="Exception">STR</exception> Public ReadOnly Property A(x As String) As String Get Return x End Get End Property End Class ]]> </file> </compilation>, <error> <![CDATA[ BC42306: XML comment tag 'exception' is not permitted on a 'module' language element. ''' <exception cref="Exception">Module0</exception> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'exception' is not permitted on a 'class' language element. ''' <summary><exception cref="Exception">E inside summary tag</exception></summary> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'exception' is not permitted on a 'class' language element. ''' <exception cref="Exception">Clazz</exception> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute '11111' that could not be resolved. ''' <exception cref="11111">X1</exception> ~~~~~~~~~~~~ BC42375: XML comment has a tag with a 'cref' attribute 'X' that bound to a type parameter. Use the <typeparamref> tag instead. ''' <exception cref="X">X2</exception> ~~~~~~~~ BC42306: XML comment tag 'exception' is not permitted on a 'variable' language element. ''' <exception cref="Exception">F</exception> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'exception' is not permitted on a 'delegate' language element. ''' <exception cref="Exception">FDelegate</exception> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'exception' is not permitted on a 'enum' language element. ''' <exception cref="Exception">En</exception> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'exception' is not permitted on a 'structure' language element. ''' <exception cref="Exception">STR</exception> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]> </error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:Module0"> <exception cref="T:System.Exception">Module0</exception> </member> <member name="T:Clazz`1"> <summary><exception cref="T:System.Exception">E inside summary tag</exception></summary> <exception cref="T:System.Exception">Clazz</exception> </member> <member name="M:Clazz`1.X1"> <summary></summary> <exception cref="!:11111">X1</exception> </member> <member name="E:Clazz`1.E"> <summary><exception cref="T:System.Exception">E inside summary tag</exception></summary> <exception cref="T:System.Exception">E</exception> </member> <member name="M:Clazz`1.X2"> <summary></summary> <exception cref="!:X">X2</exception> </member> <member name="F:Clazz`1.F"> <summary></summary> <exception cref="T:System.Exception">F</exception> </member> <member name="P:Clazz`1.P"> <summary></summary> <exception cref="T:System.Exception">P</exception> </member> <member name="T:Clazz`1.FDelegate"> <summary></summary> <exception cref="T:System.Exception">FDelegate</exception> </member> <member name="T:Clazz`1.En"> <summary></summary> <exception cref="T:System.Exception">En</exception> </member> <member name="T:Clazz`1.STR"> <summary></summary> <exception cref="T:System.Exception">STR</exception> </member> <member name="P:Clazz`1.A(System.String)"> <summary></summary> <exception cref="T:System.Exception">STR</exception> </member> </members> </doc> ]]> </xml>) End Sub <Fact> Public Sub QualifiedCref() CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Public Class Clazz(Of X, Y) Public Class MyException : Inherits Exception ''' <summary> </summary> ''' <exception cref="MyException">Clazz(Of Integer).MyException::S</exception> Public Sub S() End Sub End Class End Class Public Class Clazz Public Class MyException : Inherits Exception ''' <summary> </summary> ''' <exception cref="MyException">Clazz(Of Integer).MyException::S</exception> Public Sub S() End Sub End Class End Class Public Module Module0 ''' <summary> </summary> ''' <exception cref="Clazz.MyException">Module0::S0</exception> Public Sub S0() End Sub ''' <summary> </summary> ''' <exception cref="Clazz(Of ).MyException">Module0::S1</exception> Public Sub S1() End Sub ''' <summary> </summary> ''' <exception cref="Clazz(Of X).MyException">Module0::S2</exception> Public Sub S2() End Sub ''' <summary> </summary> ''' <exception cref="Clazz(Of X, Y).MyException">Module0::S2</exception> Public Sub S2a() End Sub ''' <summary> </summary> ''' <exception cref="Global">Module0::S3</exception> ''' <exception cref="oBjeCt">Module0::S3:OBJECT</exception> Public Sub S3() End Sub ''' <summary> </summary> ''' <exception cref="MyOuterException">Module0::S4</exception> Public Sub S4() End Sub ''' <summary> </summary> ''' <exception cref="MyOuterException(Of )">Module0::S5</exception> Public Sub S5() End Sub ''' <summary> </summary> ''' <exception cref="MyOuterException(Of T)">Module0::S6</exception> Public Sub S6() End Sub ''' <summary> </summary> ''' <exception cref="MyOuterException(Of T, Y)">Module0::S7</exception> Public Sub S7() End Sub End Module Public Class MyOuterException(Of T) : Inherits Exception ''' <summary> </summary> ''' <exception cref="MyOuterException">MyOuterException(Of )::S</exception> Public Sub S() End Sub End Class Public Class MyOuterException : Inherits Exception ''' <summary> </summary> ''' <exception cref="MyOuterException(Of X)">MyOuterException::S</exception> Public Sub S() End Sub End Class ''' <summary><exception cref="Exception">E inside summary tag</exception></summary> Public Class Clazz(Of X) ''' <summary> </summary> ''' <exception cref="MyException">Clazz::S1</exception> Public Sub S1() End Sub ''' <summary> </summary> ''' <exception cref="System.Exception">Clazz::S2</exception> Public Sub S2() End Sub ''' <summary> </summary> ''' <exception cref="Global.System.Exception">Clazz::S3</exception> Public Sub S3() End Sub Public Class MyException : Inherits Exception ''' <summary> </summary> ''' <exception cref="MyException">MyException::S</exception> Public Sub S() End Sub End Class End Class ]]> </file> </compilation>, <error> <![CDATA[ BC42309: XML comment has a tag with a 'cref' attribute 'Clazz(Of ).MyException' that could not be resolved. ''' <exception cref="Clazz(Of ).MyException">Module0::S1</exception> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'Global' that could not be resolved. ''' <exception cref="Global">Module0::S3</exception> ~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'MyOuterException(Of )' that could not be resolved. ''' <exception cref="MyOuterException(Of )">Module0::S5</exception> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'MyOuterException(Of T, Y)' that could not be resolved. ''' <exception cref="MyOuterException(Of T, Y)">Module0::S7</exception> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'exception' is not permitted on a 'class' language element. ''' <summary><exception cref="Exception">E inside summary tag</exception></summary> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]> </error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="M:Clazz`2.MyException.S"> <summary> </summary> <exception cref="T:Clazz`2.MyException">Clazz(Of Integer).MyException::S</exception> </member> <member name="M:Clazz.MyException.S"> <summary> </summary> <exception cref="T:Clazz.MyException">Clazz(Of Integer).MyException::S</exception> </member> <member name="M:Module0.S0"> <summary> </summary> <exception cref="T:Clazz.MyException">Module0::S0</exception> </member> <member name="M:Module0.S1"> <summary> </summary> <exception cref="!:Clazz(Of ).MyException">Module0::S1</exception> </member> <member name="M:Module0.S2"> <summary> </summary> <exception cref="T:Clazz`1.MyException">Module0::S2</exception> </member> <member name="M:Module0.S2a"> <summary> </summary> <exception cref="T:Clazz`2.MyException">Module0::S2</exception> </member> <member name="M:Module0.S3"> <summary> </summary> <exception cref="!:Global">Module0::S3</exception> <exception cref="T:System.Object">Module0::S3:OBJECT</exception> </member> <member name="M:Module0.S4"> <summary> </summary> <exception cref="T:MyOuterException">Module0::S4</exception> </member> <member name="M:Module0.S5"> <summary> </summary> <exception cref="!:MyOuterException(Of )">Module0::S5</exception> </member> <member name="M:Module0.S6"> <summary> </summary> <exception cref="T:MyOuterException`1">Module0::S6</exception> </member> <member name="M:Module0.S7"> <summary> </summary> <exception cref="!:MyOuterException(Of T, Y)">Module0::S7</exception> </member> <member name="M:MyOuterException`1.S"> <summary> </summary> <exception cref="T:MyOuterException">MyOuterException(Of )::S</exception> </member> <member name="M:MyOuterException.S"> <summary> </summary> <exception cref="T:MyOuterException`1">MyOuterException::S</exception> </member> <member name="T:Clazz`1"> <summary><exception cref="T:System.Exception">E inside summary tag</exception></summary> </member> <member name="M:Clazz`1.S1"> <summary> </summary> <exception cref="T:Clazz`1.MyException">Clazz::S1</exception> </member> <member name="M:Clazz`1.S2"> <summary> </summary> <exception cref="T:System.Exception">Clazz::S2</exception> </member> <member name="M:Clazz`1.S3"> <summary> </summary> <exception cref="T:System.Exception">Clazz::S3</exception> </member> <member name="M:Clazz`1.MyException.S"> <summary> </summary> <exception cref="T:Clazz`1.MyException">MyException::S</exception> </member> </members> </doc> ]]> </xml>) End Sub <Fact> Public Sub QualifiedCref_More() CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Module Module1 Public Sub Main() End Sub Public Property PRST As String Public Event EVNT As action End Module Public Class BaseClass ''' <summary> ''' <reference cref="Module1"/> ''' <reference cref="Module1.PRST"/> ''' <reference cref="Module1.get_PRST"/> ''' <reference cref="Module1.EVNT"/> ''' <reference cref="Module1.add_EVNT"/> ''' <reference cref="BaseClass.New"/> ''' <reference cref="BaseClass.op_multiply"/> ''' <reference cref="BaseClass.op_explicit"/> ''' </summary> Public F As Integer Public Shared Operator *(bc As BaseClass, i As Integer) As BaseClass Return bc End Operator Public Shared Narrowing Operator CType(bc As BaseClass) As String Return Nothing End Operator End Class ]]> </file> </compilation>, <error> <![CDATA[ BC42309: XML comment has a tag with a 'cref' attribute 'Module1.get_PRST' that could not be resolved. ''' <reference cref="Module1.get_PRST"/> ~~~~~~~~~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'Module1.add_EVNT' that could not be resolved. ''' <reference cref="Module1.add_EVNT"/> ~~~~~~~~~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'BaseClass.New' that could not be resolved. ''' <reference cref="BaseClass.New"/> ~~~~~~~~~~~~~~~~~~~~ ]]> </error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="F:BaseClass.F"> <summary> <reference cref="T:Module1"/> <reference cref="P:Module1.PRST"/> <reference cref="!:Module1.get_PRST"/> <reference cref="E:Module1.EVNT"/> <reference cref="!:Module1.add_EVNT"/> <reference cref="!:BaseClass.New"/> <reference cref="M:BaseClass.op_Multiply(BaseClass,System.Int32)"/> <reference cref="M:BaseClass.op_Explicit(BaseClass)~System.String"/> </summary> </member> </members> </doc> ]]> </xml>) End Sub <Fact> Public Sub QualifiedCref_GenericMethod() CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System ''' <summary> ''' 1) <see cref="Foo.Method"/> ''' 2) <see cref="Foo.Method(Of T)"/> ''' 3) <see cref="Foo.Method(Of T, U)"/> ''' 4) <see cref="Foo.Method(Of )"/> ''' 5) <see cref="Foo.Method(Of ,)"/> ''' </summary> Public Class Foo Public Sub Method() End Sub End Class ]]> </file> </compilation>, <error> <![CDATA[ BC42309: XML comment has a tag with a 'cref' attribute 'Foo.Method(Of T)' that could not be resolved. ''' 2) <see cref="Foo.Method(Of T)"/> ~~~~~~~~~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'Foo.Method(Of T, U)' that could not be resolved. ''' 3) <see cref="Foo.Method(Of T, U)"/> ~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'Foo.Method(Of )' that could not be resolved. ''' 4) <see cref="Foo.Method(Of )"/> ~~~~~~~~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'Foo.Method(Of ,)' that could not be resolved. ''' 5) <see cref="Foo.Method(Of ,)"/> ~~~~~~~~~~~~~~~~~~~~~~~ ]]> </error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:Foo"> <summary> 1) <see cref="M:Foo.Method"/> 2) <see cref="!:Foo.Method(Of T)"/> 3) <see cref="!:Foo.Method(Of T, U)"/> 4) <see cref="!:Foo.Method(Of )"/> 5) <see cref="!:Foo.Method(Of ,)"/> </summary> </member> </members> </doc> ]]> </xml>) End Sub <Fact> Public Sub Cref_Scopes() CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System ' NOTE: The first "tostring" did not resolve in dev11. ''' <see cref="c.tostring"/> ''' <see cref="tostring"/> Public Class C(Of X, Y) ''' <see cref="c.tostring"/> ''' <see cref="tostring"/> Public Sub New() End Sub End Class ]]> </file> </compilation>, <error></error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:C`2"> <see cref="M:System.Object.ToString"/> <see cref="M:System.Object.ToString"/> </member> <member name="M:C`2.#ctor"> <see cref="M:System.Object.ToString"/> <see cref="M:System.Object.ToString"/> </member> </members> </doc> ]]> </xml>) End Sub <ConditionalFact(GetType(WindowsDesktopOnly), Reason:=ConditionalSkipReason.TestExecutionNeedsDesktopTypes)> Public Sub Tags_Summary_Permission_See_SeeAlso_List_Para() CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Imports System.Collections.Generic ''' <summary> ''' This is the entry point of the Point class testing program. ''' <para>This program tests each method and operator, and ''' is intended to be run after any non-trivial maintenance has ''' been performed on the Point class.</para> ''' </summary> ''' <permission cref="System.Security.PermissionSet"> ''' Everyone can access this class.<see cref="List(Of X)"/> ''' </permission> Public Class TestClass ''' <remarks> ''' Here is an example of a bulleted list: ''' <list type="bullet"> ''' <listheader> ''' <term>term</term> ''' <description>description</description> ''' </listheader> ''' <item> ''' <term>A</term> ''' <description>Item 1.</description> ''' </item> ''' <item> ''' <description>Item 2.</description> ''' </item> ''' </list> ''' </remarks> ''' <list type="bullet"> ''' <item> ''' <description>Item 1.</description> ''' <seealso cref="TestClass"/> ''' </item> ''' </list> Public Shared Sub Main() Dim a As TestClass = Nothing End Sub End Class ]]> </file> </compilation>, <error></error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:TestClass"> <summary> This is the entry point of the Point class testing program. <para>This program tests each method and operator, and is intended to be run after any non-trivial maintenance has been performed on the Point class.</para> </summary> <permission cref="T:System.Security.PermissionSet"> Everyone can access this class.<see cref="T:System.Collections.Generic.List`1"/> </permission> </member> <member name="M:TestClass.Main"> <remarks> Here is an example of a bulleted list: <list type="bullet"> <listheader> <term>term</term> <description>description</description> </listheader> <item> <term>A</term> <description>Item 1.</description> </item> <item> <description>Item 2.</description> </item> </list> </remarks> <list type="bullet"> <item> <description>Item 1.</description> <seealso cref="T:TestClass"/> </item> </list> </member> </members> </doc> ]]> </xml>) End Sub <Fact> Public Sub Tags_ParamRef() CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Imports System.Collections.Generic ''' <summary> ''' <paramref name="P1"></paramref> ''' </summary> ''' <paramref name="P2"></paramref> Public Class TestClass ''' <summary> ''' <paramref name="P3"></paramref> ''' </summary> ''' <paramref name="P4"></paramref> ''' <paramref></paramref> Public Shared Sub M(p3 As Integer, p4 As String) Dim a As TestClass = Nothing End Sub ''' <summary> ''' <paramref name="P5"></paramref> ''' </summary> ''' <paramref name="P6"></paramref> Public F As Integer ''' <summary> ''' <paramref name="P7"></paramref> ''' </summary> ''' <paramref name="P8"></paramref> Public Property P As Integer ''' <summary> ''' <paramref name="P9"></paramref> ''' </summary> ''' <paramref name="P10"></paramref> Public ReadOnly Property P(P9 As String) As Integer Get Return Nothing End Get End Property ''' <summary> ''' <paramref name="P11"></paramref> ''' </summary> ''' <paramref name="P12"></paramref> Public Event EE(p11 As String) End Class ]]> </file> </compilation>, <error> <![CDATA[ BC42306: XML comment tag 'paramref' is not permitted on a 'class' language element. ''' <paramref name="P1"></paramref> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'paramref' is not permitted on a 'class' language element. ''' <paramref name="P2"></paramref> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'paramref' is not permitted on a 'variable' language element. ''' <paramref name="P5"></paramref> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'paramref' is not permitted on a 'variable' language element. ''' <paramref name="P6"></paramref> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42307: XML comment parameter 'P7' does not match a parameter on the corresponding 'property' statement. ''' <paramref name="P7"></paramref> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42307: XML comment parameter 'P8' does not match a parameter on the corresponding 'property' statement. ''' <paramref name="P8"></paramref> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42307: XML comment parameter 'P10' does not match a parameter on the corresponding 'property' statement. ''' <paramref name="P10"></paramref> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42307: XML comment parameter 'P12' does not match a parameter on the corresponding 'event' statement. ''' <paramref name="P12"></paramref> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]> </error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:TestClass"> <summary> <paramref name="P1"></paramref> </summary> <paramref name="P2"></paramref> </member> <member name="M:TestClass.M(System.Int32,System.String)"> <summary> <paramref name="P3"></paramref> </summary> <paramref name="P4"></paramref> <paramref></paramref> </member> <member name="F:TestClass.F"> <summary> <paramref name="P5"></paramref> </summary> <paramref name="P6"></paramref> </member> <member name="P:TestClass.P"> <summary> <paramref name="P7"></paramref> </summary> <paramref name="P8"></paramref> </member> <member name="P:TestClass.P(System.String)"> <summary> <paramref name="P9"></paramref> </summary> <paramref name="P10"></paramref> </member> <member name="E:TestClass.EE"> <summary> <paramref name="P11"></paramref> </summary> <paramref name="P12"></paramref> </member> </members> </doc> ]]> </xml>) End Sub <Fact> Public Sub Tags_ParamRef_NoErrors() CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Imports System.Collections.Generic ''' <summary> ''' <paramref name="P1"></paramref> ''' </summary> ''' <paramref name="P2"></paramref> Public Class TestClass ''' <summary> ''' <paramref name="P3"></paramref> ''' </summary> ''' <paramref name="P4"></paramref> ''' <paramref></paramref> Public Shared Sub M(p3 As Integer, p4 As String) Dim a As TestClass = Nothing End Sub ''' <summary> ''' <paramref name="P5"></paramref> ''' </summary> ''' <paramref name="P6"></paramref> Public F As Integer ''' <summary> ''' <paramref name="P7"></paramref> ''' </summary> ''' <paramref name="P8"></paramref> Public Property P As Integer ''' <summary> ''' <paramref name="P9"></paramref> ''' </summary> ''' <paramref name="P10"></paramref> Public ReadOnly Property P(P9 As String) As Integer Get Return Nothing End Get End Property ''' <summary> ''' <paramref name="P11"></paramref> ''' </summary> ''' <paramref name="P12"></paramref> Public Event EE(p11 As String) End Class ]]> </file> </compilation>, <error></error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:TestClass"> <summary> <paramref name="P1"></paramref> </summary> <paramref name="P2"></paramref> </member> <member name="M:TestClass.M(System.Int32,System.String)"> <summary> <paramref name="P3"></paramref> </summary> <paramref name="P4"></paramref> <paramref></paramref> </member> <member name="F:TestClass.F"> <summary> <paramref name="P5"></paramref> </summary> <paramref name="P6"></paramref> </member> <member name="P:TestClass.P"> <summary> <paramref name="P7"></paramref> </summary> <paramref name="P8"></paramref> </member> <member name="P:TestClass.P(System.String)"> <summary> <paramref name="P9"></paramref> </summary> <paramref name="P10"></paramref> </member> <member name="E:TestClass.EE"> <summary> <paramref name="P11"></paramref> </summary> <paramref name="P12"></paramref> </member> </members> </doc> ]]> </xml>, withDiagnostics:=False) End Sub <Fact> Public Sub Tags_Returns() CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Imports System.Collections.Generic ''' <summary> ''' <paramref name="P1"></paramref> ''' </summary> ''' <returns>TestClass</returns> Public Class TestClass ''' <returns>EN</returns> Public Enum EN : A : End Enum ''' <returns>DelSub</returns> Public Delegate Sub DelSub(a As Integer) ''' <returns>DelFunc</returns> Public Delegate Function DelFunc(a As Integer) As Integer ''' <returns>MSub</returns> Public Shared Sub MSub(p3 As Integer, p4 As String) End Sub ''' <returns>MFunc</returns> Public Shared Function MFunc(p3 As Integer, p4 As String) As Integer Return Nothing End Function ''' <summary><returns nested="true">Field</returns></summary> ''' <returns>Field</returns> Public Field As Integer ''' <returns>FieldWE</returns> WithEvents FieldWE As TestClass ''' <returns>DeclareFtn</returns> Public Declare Function DeclareFtn Lib "bar" () As Integer ''' <returns>DeclareSub</returns> Public Declare Sub DeclareSub Lib "bar" () ''' <returns>PReadOnly</returns> Public ReadOnly Property PReadOnly As Integer Get Return Nothing End Get End Property ''' <returns>PReadWrite</returns> Public Property PReadWrite As Integer Get Return Nothing End Get Set(value As Integer) End Set End Property ''' <returns>PWriteOnly</returns> Public WriteOnly Property PWriteOnly As Integer Set(value As Integer) End Set End Property ''' <returns>EE</returns> Public Event EE(p11 As String) End Class ]]> </file> </compilation>, <error> <![CDATA[ BC42306: XML comment tag 'paramref' is not permitted on a 'class' language element. ''' <paramref name="P1"></paramref> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'returns' is not permitted on a 'class' language element. ''' <returns>TestClass</returns> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'returns' is not permitted on a 'enum' language element. ''' <returns>EN</returns> ~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'returns' is not permitted on a 'delegate sub' language element. ''' <returns>DelSub</returns> ~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'returns' is not permitted on a 'sub' language element. ''' <returns>MSub</returns> ~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'returns' is not permitted on a 'variable' language element. ''' <summary><returns nested="true">Field</returns></summary> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'returns' is not permitted on a 'variable' language element. ''' <returns>Field</returns> ~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'returns' is not permitted on a 'WithEvents variable' language element. ''' <returns>FieldWE</returns> ~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42315: XML comment tag 'returns' is not permitted on a 'declare sub' language element. ''' <returns>DeclareSub</returns> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42313: XML comment tag 'returns' is not permitted on a 'WriteOnly' Property. ''' <returns>PWriteOnly</returns> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'returns' is not permitted on a 'event' language element. ''' <returns>EE</returns> ~~~~~~~~~~~~~~~~~~~~~ ]]> </error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:TestClass"> <summary> <paramref name="P1"></paramref> </summary> <returns>TestClass</returns> </member> <member name="T:TestClass.EN"> <returns>EN</returns> </member> <member name="T:TestClass.DelSub"> <returns>DelSub</returns> </member> <member name="T:TestClass.DelFunc"> <returns>DelFunc</returns> </member> <member name="M:TestClass.MSub(System.Int32,System.String)"> <returns>MSub</returns> </member> <member name="M:TestClass.MFunc(System.Int32,System.String)"> <returns>MFunc</returns> </member> <member name="F:TestClass.Field"> <summary><returns nested="true">Field</returns></summary> <returns>Field</returns> </member> <member name="F:TestClass._FieldWE"> <returns>FieldWE</returns> </member> <member name="M:TestClass.DeclareFtn"> <returns>DeclareFtn</returns> </member> <member name="M:TestClass.DeclareSub"> <returns>DeclareSub</returns> </member> <member name="P:TestClass.PReadOnly"> <returns>PReadOnly</returns> </member> <member name="P:TestClass.PReadWrite"> <returns>PReadWrite</returns> </member> <member name="P:TestClass.PWriteOnly"> <returns>PWriteOnly</returns> </member> <member name="E:TestClass.EE"> <returns>EE</returns> </member> </members> </doc> ]]> </xml>) End Sub <Fact> Public Sub Tags_Param() CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Imports System.Collections.Generic ''' <summary><param name="P_outer + aaa">@TestClass</param></summary> ''' <param name="P">@TestClass</param> Public Class TestClass ''' <param name="P">@EN</param> Public Enum EN : A : End Enum ''' <param name="a">@DelSub</param> Public Delegate Sub DelSub(a As Integer) ''' <param name="a">@DelFunc</param> ''' <summary><param name="P_outer + aaa">@TestClass</param></summary> Public Delegate Function DelFunc(a As Integer) As Integer ''' <param name="a">@MSub</param> Public Shared Sub MSub(p3 As Integer, p4 As String) End Sub ''' <param name="">@MSubWithErrors1</param> Public Shared Sub MSubWithErrors1(p3 As Integer, p4 As String) End Sub ''' <param name="1">@MSubWithErrors2</param> Public Shared Sub MSubWithErrors2(p3 As Integer, p4 As String) End Sub ''' <param>@MSubWithErrors3</param> Public Shared Sub MSubWithErrors3(p3 As Integer, p4 As String) End Sub ''' <param name="p3">@MFunc</param> Public Shared Function MFunc(p3 As Integer, p4 As String) As Integer Return Nothing End Function ''' <param name="p3">@Field</param> Public Field As Integer ''' <param name="p3">@DeclareFtn</param> Public Declare Function DeclareFtn Lib "bar" (p3 As Integer) As Integer ''' <param name="p">@PReadOnly</param> Public ReadOnly Property PReadOnly(p As Integer) As Integer Get Return Nothing End Get End Property ''' <param name="p">@PReadWrite</param> Public Property PReadWrite As Integer ''' <param name="ppp">@EVE</param> Public Event EVE(ppp As Integer) ''' <param name="paramName">@EVE2</param> Public Event EVE2 As Action(Of Integer) ''' <param name="arg1">@EVE3</param> ''' <param name="arg2">@EVE3</param> Public Event EVE3 As Action(Of Integer, Integer) End Class ]]> </file> </compilation>, <error> <![CDATA[ BC42306: XML comment tag 'param' is not permitted on a 'class' language element. ''' <summary><param name="P_outer + aaa">@TestClass</param></summary> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'param' is not permitted on a 'class' language element. ''' <param name="P">@TestClass</param> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'param' is not permitted on a 'enum' language element. ''' <param name="P">@EN</param> ~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42307: XML comment parameter 'P_outer + aaa' does not match a parameter on the corresponding 'function' statement. ''' <summary><param name="P_outer + aaa">@TestClass</param></summary> ~~~~~~~~~~~~~~~~~~~~ BC42307: XML comment parameter 'a' does not match a parameter on the corresponding 'sub' statement. ''' <param name="a">@MSub</param> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42307: XML comment parameter '' does not match a parameter on the corresponding 'sub' statement. ''' <param name="">@MSubWithErrors1</param> ~~~~~~~ BC42307: XML comment parameter '1' does not match a parameter on the corresponding 'sub' statement. ''' <param name="1">@MSubWithErrors2</param> ~~~~~~~~ BC42308: XML comment parameter must have a 'name' attribute. ''' <param>@MSubWithErrors3</param> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'param' is not permitted on a 'variable' language element. ''' <param name="p3">@Field</param> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42307: XML comment parameter 'p' does not match a parameter on the corresponding 'property' statement. ''' <param name="p">@PReadWrite</param> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42307: XML comment parameter 'paramName' does not match a parameter on the corresponding 'event' statement. ''' <param name="paramName">@EVE2</param> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]> </error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:TestClass"> <summary><param name="P_outer + aaa">@TestClass</param></summary> <param name="P">@TestClass</param> </member> <member name="T:TestClass.EN"> <param name="P">@EN</param> </member> <member name="T:TestClass.DelSub"> <param name="a">@DelSub</param> </member> <member name="T:TestClass.DelFunc"> <param name="a">@DelFunc</param> <summary><param name="P_outer + aaa">@TestClass</param></summary> </member> <member name="M:TestClass.MSub(System.Int32,System.String)"> <param name="a">@MSub</param> </member> <member name="M:TestClass.MSubWithErrors1(System.Int32,System.String)"> <param name="">@MSubWithErrors1</param> </member> <member name="M:TestClass.MSubWithErrors2(System.Int32,System.String)"> <param name="1">@MSubWithErrors2</param> </member> <member name="M:TestClass.MSubWithErrors3(System.Int32,System.String)"> <param>@MSubWithErrors3</param> </member> <member name="M:TestClass.MFunc(System.Int32,System.String)"> <param name="p3">@MFunc</param> </member> <member name="F:TestClass.Field"> <param name="p3">@Field</param> </member> <member name="M:TestClass.DeclareFtn(System.Int32)"> <param name="p3">@DeclareFtn</param> </member> <member name="P:TestClass.PReadOnly(System.Int32)"> <param name="p">@PReadOnly</param> </member> <member name="P:TestClass.PReadWrite"> <param name="p">@PReadWrite</param> </member> <member name="E:TestClass.EVE"> <param name="ppp">@EVE</param> </member> <member name="E:TestClass.EVE2"> <param name="paramName">@EVE2</param> </member> <member name="E:TestClass.EVE3"> <param name="arg1">@EVE3</param> <param name="arg2">@EVE3</param> </member> </members> </doc> ]]> </xml>) End Sub <Fact> Public Sub Tags_Param_10Plus() CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Imports System.Collections.Generic Public Class TestClass ''' <param name="a1"/> ''' <param name="a14"/> Private Sub PS(a0 As Integer, 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) End Sub End Class ]]> </file> </compilation>, <error></error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="M:TestClass.PS(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)"> <param name="a1"/> <param name="a14"/> </member> </members> </doc> ]]> </xml>) End Sub <Fact> Public Sub Tags_Value() CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Imports System.Collections.Generic ''' <summary><param name="P_outer + aaa"/>@TestClass</summary> ''' <value>@TestClass</value> Public Class TestClass ''' <value>@EN</value> Public Enum EN : A : End Enum ''' <value>@STR</value> Public Structure STR : End Structure ''' <value>@INTERF</value> Public Interface INTERF : End Interface ''' <value>@DelSub</value> Public Delegate Sub DelSub(a As Integer) ''' <value>@DelFunc</value> Public Delegate Function DelFunc(a As Integer) As Integer ''' <value>@MSub</value> Public Shared Sub MSub(p3 As Integer, p4 As String) End Sub ''' <value>@MFunc</value> Public Shared Function MFunc(p3 As Integer, p4 As String) As Integer Return Nothing End Function ''' <value>@DeclareFtn</value> Public Declare Function DeclareFtn Lib "bar" (p3 As Integer) As Integer ''' <value>@Field</value> Public Field As Integer ''' <value>@PWriteOnly</value> Public WriteOnly Property PWriteOnly(p As Integer) As Integer Set(value As Integer) End Set End Property ''' <value>@PReadWrite</value> Public Property PReadWrite As Integer ''' <value>@EVE</value> Public Event EVE(ppp As Integer) End Class ]]> </file> </compilation>, <error> <![CDATA[ BC42306: XML comment tag 'param' is not permitted on a 'class' language element. ''' <summary><param name="P_outer + aaa"/>@TestClass</summary> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'value' is not permitted on a 'class' language element. ''' <value>@TestClass</value> ~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'value' is not permitted on a 'enum' language element. ''' <value>@EN</value> ~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'value' is not permitted on a 'structure' language element. ''' <value>@STR</value> ~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'value' is not permitted on a 'interface' language element. ''' <value>@INTERF</value> ~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'value' is not permitted on a 'delegate' language element. ''' <value>@DelSub</value> ~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'value' is not permitted on a 'delegate' language element. ''' <value>@DelFunc</value> ~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'value' is not permitted on a 'sub' language element. ''' <value>@MSub</value> ~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'value' is not permitted on a 'function' language element. ''' <value>@MFunc</value> ~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'value' is not permitted on a 'declare' language element. ''' <value>@DeclareFtn</value> ~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'value' is not permitted on a 'variable' language element. ''' <value>@Field</value> ~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'value' is not permitted on a 'event' language element. ''' <value>@EVE</value> ~~~~~~~~~~~~~~~~~~~ ]]> </error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:TestClass"> <summary><param name="P_outer + aaa"/>@TestClass</summary> <value>@TestClass</value> </member> <member name="T:TestClass.EN"> <value>@EN</value> </member> <member name="T:TestClass.STR"> <value>@STR</value> </member> <member name="T:TestClass.INTERF"> <value>@INTERF</value> </member> <member name="T:TestClass.DelSub"> <value>@DelSub</value> </member> <member name="T:TestClass.DelFunc"> <value>@DelFunc</value> </member> <member name="M:TestClass.MSub(System.Int32,System.String)"> <value>@MSub</value> </member> <member name="M:TestClass.MFunc(System.Int32,System.String)"> <value>@MFunc</value> </member> <member name="M:TestClass.DeclareFtn(System.Int32)"> <value>@DeclareFtn</value> </member> <member name="F:TestClass.Field"> <value>@Field</value> </member> <member name="P:TestClass.PWriteOnly(System.Int32)"> <value>@PWriteOnly</value> </member> <member name="P:TestClass.PReadWrite"> <value>@PReadWrite</value> </member> <member name="E:TestClass.EVE"> <value>@EVE</value> </member> </members> </doc> ]]> </xml>) End Sub <Fact> Public Sub Tags_TypeParam() CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Imports System.Collections.Generic ''' <typeparam name="X">@Module0</typeparam> Public Module Module0 End Module ''' <summary><param name="P_outer + aaa"/>@TestClass</summary> ''' <typeparam>@TestClass</typeparam> Public Class TestClass ''' <typeparam name="X">@EN</typeparam> Public Enum EN : A : End Enum ''' <typeparam name="X">@STR</typeparam> Public Structure STR(Of X) : End Structure ''' <typeparam name="Y">@INTERF</typeparam> Public Interface INTERF(Of X, Y) : End Interface ''' <typeparam name="W">@DelSub</typeparam> Public Delegate Sub DelSub(Of W)(a As Integer) ''' <typeparam name="UV">@DelFunc</typeparam> Public Delegate Function DelFunc(Of W)(a As Integer) As Integer ''' <typeparam name="TT">@MSub</typeparam> Public Shared Sub MSub(Of TT)(p3 As Integer, p4 As String) End Sub ''' <typeparam name="TT">@MFunc</typeparam> Public Shared Function MFunc(p3 As Integer, p4 As String) As Integer Return Nothing End Function ''' <typeparam name="TT">@Field</typeparam> Public Field As Integer ''' <typeparam name="TT">@DeclareFtn</typeparam> Public Declare Function DeclareFtn Lib "bar" (p3 As Integer) As Integer ''' <typeparam name="TT">@PWriteOnly</typeparam> Public WriteOnly Property PWriteOnly(p As Integer) As Integer Set(value As Integer) End Set End Property ''' <typeparam name="TT">@PReadWrite</typeparam> Public Property PReadWrite As Integer ''' <typeparam name="TT">@EVE</typeparam> Public Event EVE(ppp As Integer) End Class ]]> </file> </compilation>, <error> <![CDATA[ BC42306: XML comment tag 'typeparam' is not permitted on a 'module' language element. ''' <typeparam name="X">@Module0</typeparam> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'param' is not permitted on a 'class' language element. ''' <summary><param name="P_outer + aaa"/>@TestClass</summary> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42318: XML comment type parameter must have a 'name' attribute. ''' <typeparam>@TestClass</typeparam> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'typeparam' is not permitted on a 'enum' language element. ''' <typeparam name="X">@EN</typeparam> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42317: XML comment type parameter 'UV' does not match a type parameter on the corresponding 'delegate' statement. ''' <typeparam name="UV">@DelFunc</typeparam> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42317: XML comment type parameter 'TT' does not match a type parameter on the corresponding 'function' statement. ''' <typeparam name="TT">@MFunc</typeparam> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'typeparam' is not permitted on a 'variable' language element. ''' <typeparam name="TT">@Field</typeparam> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'typeparam' is not permitted on a 'declare' language element. ''' <typeparam name="TT">@DeclareFtn</typeparam> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'typeparam' is not permitted on a 'property' language element. ''' <typeparam name="TT">@PWriteOnly</typeparam> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'typeparam' is not permitted on a 'property' language element. ''' <typeparam name="TT">@PReadWrite</typeparam> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'typeparam' is not permitted on a 'event' language element. ''' <typeparam name="TT">@EVE</typeparam> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]> </error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:Module0"> <typeparam name="X">@Module0</typeparam> </member> <member name="T:TestClass"> <summary><param name="P_outer + aaa"/>@TestClass</summary> <typeparam>@TestClass</typeparam> </member> <member name="T:TestClass.EN"> <typeparam name="X">@EN</typeparam> </member> <member name="T:TestClass.STR`1"> <typeparam name="X">@STR</typeparam> </member> <member name="T:TestClass.INTERF`2"> <typeparam name="Y">@INTERF</typeparam> </member> <member name="T:TestClass.DelSub`1"> <typeparam name="W">@DelSub</typeparam> </member> <member name="T:TestClass.DelFunc`1"> <typeparam name="UV">@DelFunc</typeparam> </member> <member name="M:TestClass.MSub``1(System.Int32,System.String)"> <typeparam name="TT">@MSub</typeparam> </member> <member name="M:TestClass.MFunc(System.Int32,System.String)"> <typeparam name="TT">@MFunc</typeparam> </member> <member name="F:TestClass.Field"> <typeparam name="TT">@Field</typeparam> </member> <member name="M:TestClass.DeclareFtn(System.Int32)"> <typeparam name="TT">@DeclareFtn</typeparam> </member> <member name="P:TestClass.PWriteOnly(System.Int32)"> <typeparam name="TT">@PWriteOnly</typeparam> </member> <member name="P:TestClass.PReadWrite"> <typeparam name="TT">@PReadWrite</typeparam> </member> <member name="E:TestClass.EVE"> <typeparam name="TT">@EVE</typeparam> </member> </members> </doc> ]]> </xml>) End Sub <Fact> Public Sub BC42300WRN_XMLDocBadXMLLine() CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Option Explicit On Imports System Class C1 '''<remarks>this XML comment does not immediately appear before any type</remarks> '''<remarks>Line#2</remarks> ' this is a regular comment Interface I1 End Interface End Class ]]> </file> </compilation>, <error> <![CDATA[ BC42301: Only one XML comment block is allowed per language element. '''<remarks>this XML comment does not immediately appear before any type</remarks> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42300: XML comment block must immediately precede the language element to which it applies. XML comment will be ignored. '''<remarks>Line#2</remarks> ~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]> </error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> </members> </doc> ]]> </xml>) End Sub <Fact> Public Sub BC42301WRN_XMLDocMoreThanOneCommentBlock() CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Option Explicit On Imports System '''<remarks>Line#1</remarks> 'comment '''<remarks>Line#2</remarks> Class C1 ' this is a regular comment '''<remarks>this XML comment does not immediately appear before any type</remarks> '''<remarks>Line#2</remarks> Interface I1 End Interface End Class ]]> </file> </compilation>, <error> <![CDATA[ BC42301: Only one XML comment block is allowed per language element. '''<remarks>Line#1</remarks> ~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42301: Only one XML comment block is allowed per language element. '''<remarks>this XML comment does not immediately appear before any type</remarks> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]> </error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:C1"> <remarks>Line#2</remarks> </member> <member name="T:C1.I1"> <remarks>Line#2</remarks> </member> </members> </doc> ]]> </xml>) End Sub <Fact> Public Sub WRN_XMLDocInsideMethod() CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Option Explicit On Imports System Module Module11 Public x As Object = Function() ''' Return 1 End Function Public y As Object = Function() _ ''' _ Sub Main2() ''' End Sub Public Property PPP As Object = Function() 1 ''' 1 Public Property PPP2 As Object = Function() ''' Return 1 End Function End Module ]]> </file> </compilation>, <error> <![CDATA[ BC42303: XML comment cannot appear within a method or a property. XML comment will be ignored. ''' ~ BC36674: Multiline lambda expression is missing 'End Function'. Public y As Object = Function() _ ~~~~~~~~~~ BC42105: Function '<anonymous method>' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used. Public y As Object = Function() _ ~ BC42303: XML comment cannot appear within a method or a property. XML comment will be ignored. ''' ~ BC42302: XML comment must be the first statement on a line. XML comment will be ignored. Public Property PPP As Object = Function() 1 ''' 1 ~~~~~ BC42303: XML comment cannot appear within a method or a property. XML comment will be ignored. ''' ~~ ]]> </error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="M:Module11.Main2"> _ </member> </members> </doc> ]]> </xml>) End Sub <Fact> Public Sub WRN_XMLDocInsideMethod_NoError() CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Option Explicit On Imports System Module Module11 Public x As Object = Function() ''' Return 1 End Function Public y As Object = Function() _ ''' _ Sub Main2() ''' End Sub Public Property PPP As Object = Function() 1 ''' 1 Public Property PPP2 As Object = Function() ''' Return 1 End Function End Module ]]> </file> </compilation>, <error> <![CDATA[ BC36674: Multiline lambda expression is missing 'End Function'. Public y As Object = Function() _ ~~~~~~~~~~ BC42105: Function '<anonymous method>' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used. Public y As Object = Function() _ ~ ]]> </error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="M:Module11.Main2"> _ </member> </members> </doc> ]]> </xml>, withDiagnostics:=False) End Sub <ConditionalFact(GetType(WindowsDesktopOnly), Reason:=ConditionalSkipReason.TestExecutionNeedsDesktopTypes)> Public Sub BC42305WRN_XMLDocDuplicateXMLNode() CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Option Explicit On Imports System ''' <summary cref="a b"> ''' </summary> ''' <typeparam name="X"></typeparam> ''' <typeparam name=" X " /> ''' <typeparam name="Y"></typeparam> ''' <typeparam name="X"></typeparam> ''' <summary cref="a B "/> ''' <summary cref=" a b "/> Public Class C(Of X, Y) ''' <include file=" a.vb" path=" c:\ww "/> ''' <include path="c:\ww" file="a.vb"/> Public FLD As String ''' <mysummary cref="SSS"></mysummary> Public FLD2 As String ''' <param name="x"></param> ''' <param name="x"></param> Public Sub SSS(x As Integer) End Sub ''' <remarks x=" A" y="" z = "B"></remarks> ''' <remarks y="" z = "B" x="A "/> ''' <remarks y=" " z = "B" x="a"/> ''' <remarks y=" " x="A" z = "B"/> Public F As Integer ''' <returns what="a"></returns> ''' <returns what="b"></returns> ''' <returns what=" b "/> Public Shared Operator -(a As C(Of X, Y), b As Integer) As C(Of X, Y) Return Nothing End Operator ''' <permission cref="System.Security.PermissionSet"/> ''' <permission cref="System.Security.PermissionSet "></permission> ''' <permission cref="System.Security. PermissionSet"></permission> Public Shared Narrowing Operator CType(a As C(Of X, Y)) As Integer Return Nothing End Operator End Class ''' <remarks x=" A" y=""></remarks> ''' <remarks y="" x="A "/> Module M ''' <remarks></remarks> ''' <remarks/> ''' <param name="x"></param> ''' <param name="x"></param> Public Event A(x As Integer, x As Integer) ''' <param name="a" noname="b"></param> ''' <param noname=" b " name="a"></param> ''' <value></value> ''' <value/> Public WriteOnly Property PROP(a As String) As String Set(value As String) End Set End Property End Module ]]> </file> </compilation>, <error> <![CDATA[ BC42309: XML comment has a tag with a 'cref' attribute 'a b' that could not be resolved. ''' <summary cref="a b"> ~~~~~~~~~~ BC42305: XML comment tag 'typeparam' appears with identical attributes more than once in the same XML comment block. ''' <typeparam name=" X " /> ~~~~~~~~~~~~~~~~~~~~~~~~ BC42305: XML comment tag 'typeparam' appears with identical attributes more than once in the same XML comment block. ''' <typeparam name="X"></typeparam> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'a B' that could not be resolved. ''' <summary cref="a B "/> ~~~~~~~~~~~ BC42305: XML comment tag 'summary' appears with identical attributes more than once in the same XML comment block. ''' <summary cref=" a b "/> ~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute ' a b' that could not be resolved. ''' <summary cref=" a b "/> ~~~~~~~~~~~~~~~~ BC42305: XML comment tag 'include' appears with identical attributes more than once in the same XML comment block. ''' <include path="c:\ww" file="a.vb"/> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42305: XML comment tag 'param' appears with identical attributes more than once in the same XML comment block. ''' <param name="x"></param> ~~~~~~~~~~~~~~~~~~~~~~~~ BC42305: XML comment tag 'remarks' appears with identical attributes more than once in the same XML comment block. ''' <remarks y="" z = "B" x="A "/> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42305: XML comment tag 'remarks' appears with identical attributes more than once in the same XML comment block. ''' <remarks y=" " x="A" z = "B"/> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42305: XML comment tag 'returns' appears with identical attributes more than once in the same XML comment block. ''' <returns what=" b "/> ~~~~~~~~~~~~~~~~~~~~~~ BC42305: XML comment tag 'permission' appears with identical attributes more than once in the same XML comment block. ''' <permission cref="System.Security.PermissionSet "></permission> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42305: XML comment tag 'remarks' appears with identical attributes more than once in the same XML comment block. ''' <remarks y="" x="A "/> ~~~~~~~~~~~~~~~~~~~~~~~~~ BC42305: XML comment tag 'remarks' appears with identical attributes more than once in the same XML comment block. ''' <remarks/> ~~~~~~~~~~ BC42305: XML comment tag 'param' appears with identical attributes more than once in the same XML comment block. ''' <param noname=" b " name="a"></param> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42305: XML comment tag 'value' appears with identical attributes more than once in the same XML comment block. ''' <value/> ~~~~~~~~ ]]> </error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:C`2"> <summary cref="!:a b"> </summary> <typeparam name="X"></typeparam> <typeparam name=" X " /> <typeparam name="Y"></typeparam> <typeparam name="X"></typeparam> <summary cref="!:a B "/> <summary cref="!: a b "/> </member> <member name="F:C`2.FLD"> <!--warning BC42321: Unable to include XML fragment ' c:\ww ' of file ' a.vb'. File not found.--> <!--warning BC42321: Unable to include XML fragment 'c:\ww' of file 'a.vb'. File not found.--> </member> <member name="F:C`2.FLD2"> <mysummary cref="M:C`2.SSS(System.Int32)"></mysummary> </member> <member name="M:C`2.SSS(System.Int32)"> <param name="x"></param> <param name="x"></param> </member> <member name="F:C`2.F"> <remarks x=" A" y="" z = "B"></remarks> <remarks y="" z = "B" x="A "/> <remarks y=" " z = "B" x="a"/> <remarks y=" " x="A" z = "B"/> </member> <member name="M:C`2.op_Subtraction(C{`0,`1},System.Int32)"> <returns what="a"></returns> <returns what="b"></returns> <returns what=" b "/> </member> <member name="M:C`2.op_Explicit(C{`0,`1})~System.Int32"> <permission cref="T:System.Security.PermissionSet"/> <permission cref="T:System.Security.PermissionSet"></permission> <permission cref="T:System.Security.PermissionSet"></permission> </member> <member name="T:M"> <remarks x=" A" y=""></remarks> <remarks y="" x="A "/> </member> <member name="E:M.A"> <remarks></remarks> <remarks/> <param name="x"></param> <param name="x"></param> </member> <member name="P:M.PROP(System.String)"> <param name="a" noname="b"></param> <param noname=" b " name="a"></param> <value></value> <value/> </member> </members> </doc> ]]> </xml>, ensureEnglishUICulture:=True) End Sub <ConditionalFact(GetType(WindowsDesktopOnly), Reason:=ConditionalSkipReason.TestExecutionNeedsDesktopTypes)> Public Sub BC42305WRN_XMLDocDuplicateXMLNode_NoError() CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Option Explicit On Imports System ''' <summary cref="a b"> ''' </summary> ''' <typeparam name="X"></typeparam> ''' <typeparam name=" X " /> ''' <typeparam name="Y"></typeparam> ''' <typeparam name="X"></typeparam> ''' <summary cref="a B "/> ''' <summary cref=" a b "/> Public Class C(Of X, Y) ''' <include file=" a.vb" path=" c:\ww "/> ''' <include path="c:\ww" file="a.vb"/> Public FLD As String ''' <mysummary cref="SSS"></mysummary> Public FLD2 As String ''' <param name="x"></param> ''' <param name="x"></param> Public Sub SSS(x As Integer) End Sub ''' <remarks x=" A" y="" z = "B"></remarks> ''' <remarks y="" z = "B" x="A "/> ''' <remarks y=" " z = "B" x="a"/> ''' <remarks y=" " x="A" z = "B"/> Public F As Integer ''' <returns what="a"></returns> ''' <returns what="b"></returns> ''' <returns what=" b "/> Public Shared Operator -(a As C(Of X, Y), b As Integer) As C(Of X, Y) Return Nothing End Operator ''' <permission cref="System.Security.PermissionSet"/> ''' <permission cref="System.Security.PermissionSet "></permission> ''' <permission cref="System.Security. PermissionSet"></permission> Public Shared Narrowing Operator CType(a As C(Of X, Y)) As Integer Return Nothing End Operator End Class ''' <remarks x=" A" y=""></remarks> ''' <remarks y="" x="A "/> Module M ''' <remarks></remarks> ''' <remarks/> ''' <param name="x"></param> ''' <param name="x"></param> Public Event A(x As Integer, x As Integer) ''' <param name="a" noname="b"></param> ''' <param noname=" b " name="a"></param> ''' <value></value> ''' <value/> Public WriteOnly Property PROP(a As String) As String Set(value As String) End Set End Property End Module ]]> </file> </compilation>, <error></error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:C`2"> <summary cref="!:a b"> </summary> <typeparam name="X"></typeparam> <typeparam name=" X " /> <typeparam name="Y"></typeparam> <typeparam name="X"></typeparam> <summary cref="!:a B "/> <summary cref="!: a b "/> </member> <member name="F:C`2.FLD"> <!--warning BC42321: Unable to include XML fragment ' c:\ww ' of file ' a.vb'. File not found.--> <!--warning BC42321: Unable to include XML fragment 'c:\ww' of file 'a.vb'. File not found.--> </member> <member name="F:C`2.FLD2"> <mysummary cref="M:C`2.SSS(System.Int32)"></mysummary> </member> <member name="M:C`2.SSS(System.Int32)"> <param name="x"></param> <param name="x"></param> </member> <member name="F:C`2.F"> <remarks x=" A" y="" z = "B"></remarks> <remarks y="" z = "B" x="A "/> <remarks y=" " z = "B" x="a"/> <remarks y=" " x="A" z = "B"/> </member> <member name="M:C`2.op_Subtraction(C{`0,`1},System.Int32)"> <returns what="a"></returns> <returns what="b"></returns> <returns what=" b "/> </member> <member name="M:C`2.op_Explicit(C{`0,`1})~System.Int32"> <permission cref="T:System.Security.PermissionSet"/> <permission cref="T:System.Security.PermissionSet"></permission> <permission cref="T:System.Security.PermissionSet"></permission> </member> <member name="T:M"> <remarks x=" A" y=""></remarks> <remarks y="" x="A "/> </member> <member name="E:M.A"> <remarks></remarks> <remarks/> <param name="x"></param> <param name="x"></param> </member> <member name="P:M.PROP(System.String)"> <param name="a" noname="b"></param> <param noname=" b " name="a"></param> <value></value> <value/> </member> </members> </doc> ]]> </xml>, withDiagnostics:=False, ensureEnglishUICulture:=True) End Sub <Fact> Public Sub ByRefByValOverloading() CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Public Structure TestStruct ''' <see cref="S1(ByVal TestStruct)"/> ''' <see cref="S1(ByRef TestStruct)"/> ''' <see cref="S2(ByVal TestStruct)"/> ''' <see cref="S2(ByRef TestStruct)"/> Public Shared field As Integer Public Sub S1(i As TestStruct) End Sub Public Sub S2(ByRef i As TestStruct) End Sub End Structure ]]> </file> </compilation>, <error> <![CDATA[ BC42309: XML comment has a tag with a 'cref' attribute 'S1(ByRef TestStruct)' that could not be resolved. ''' <see cref="S1(ByRef TestStruct)"/> ~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'S2(ByVal TestStruct)' that could not be resolved. ''' <see cref="S2(ByVal TestStruct)"/> ~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]> </error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="F:TestStruct.field"> <see cref="M:TestStruct.S1(TestStruct)"/> <see cref="!:S1(ByRef TestStruct)"/> <see cref="!:S2(ByVal TestStruct)"/> <see cref="M:TestStruct.S2(TestStruct@)"/> </member> </members> </doc> ]]> </xml>) End Sub <WorkItem(751828, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/751828")> <Fact()> Public Sub GetSymbolInfo_Bug_751828() Dim compilation = CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Option Explicit On Imports System Imports <xmlns="http://www.w3.org/2005/Atom"> Public Class C End Class ]]> </file> </compilation>, <error></error>) Dim tree = compilation.SyntaxTrees(0) Dim names = FindNodesOfTypeFromText(Of XmlStringSyntax)(tree, "http://www.w3.org/2005/Atom").ToArray() Assert.Equal(1, names.Length) Dim model = compilation.GetSemanticModel(tree) Dim expSymInfo1 = model.GetSymbolInfo(names(0)) Assert.True(expSymInfo1.IsEmpty) End Sub <WorkItem(768639, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768639")> <Fact()> Public Sub GetSymbolInfo_Bug_768639a() Dim compilation = CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Interface I Sub Bar() End Interface MustInherit Class C Public MustOverride Sub Bar() End Class Class B : Inherits C : Implements I ''' <see cref="Bar"/> Public Overrides Sub Bar() Implements I.Bar End Sub End Class ]]> </file> </compilation>, <error></error>) Dim tree = compilation.SyntaxTrees(0) Dim names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "Bar").ToArray() Assert.Equal(2, names.Length) Dim model = compilation.GetSemanticModel(tree) Dim expSymInfo1 = model.GetSymbolInfo(names(0)) Assert.NotNull(expSymInfo1.Symbol) End Sub <WorkItem(768639, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768639")> <Fact()> Public Sub GetSymbolInfo_Bug_768639b() Dim compilation = CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ MustInherit Class C Public MustOverride Property PPP End Class Class B : Inherits C ''' <see cref="PPP"/> Public Overrides Property PPP As Object Get Return Nothing End Get Set(value As Object) End Set End Property End Class ]]> </file> </compilation>, <error></error>) Dim tree = compilation.SyntaxTrees(0) Dim names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "PPP").ToArray() Assert.Equal(1, names.Length) Dim model = compilation.GetSemanticModel(tree) Dim expSymInfo1 = model.GetSymbolInfo(names(0)) Assert.NotNull(expSymInfo1.Symbol) End Sub <WorkItem(768639, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768639")> <Fact()> Public Sub GetSymbolInfo_Bug_768639c() Dim compilation = CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Interface I Sub Bar() End Interface MustInherit Class C Public MustOverride Sub Bar() End Class Class B : Inherits C : Implements I ''' <see cref="Bar()"/> Public Overrides Sub Bar() Implements I.Bar End Sub End Class ]]> </file> </compilation>, <error></error>) Dim tree = compilation.SyntaxTrees(0) Dim names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "Bar").ToArray() Assert.Equal(2, names.Length) Dim model = compilation.GetSemanticModel(tree) Dim expSymInfo1 = model.GetSymbolInfo(names(0)) Assert.NotNull(expSymInfo1.Symbol) End Sub <WorkItem(768639, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768639")> <Fact()> Public Sub GetSymbolInfo_Bug_768639d() Dim compilation = CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ MustInherit Class C Public MustOverride Property PPP End Class Class B : Inherits C ''' <see cref="PPP()"/> Public Overrides Property PPP As Object Get Return Nothing End Get Set(value As Object) End Set End Property End Class ]]> </file> </compilation>, <error></error>) Dim tree = compilation.SyntaxTrees(0) Dim names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "PPP").ToArray() Assert.Equal(1, names.Length) Dim model = compilation.GetSemanticModel(tree) Dim expSymInfo1 = model.GetSymbolInfo(names(0)) Assert.NotNull(expSymInfo1.Symbol) End Sub <Fact()> Public Sub GetSymbolInfo_PredefinedTypeSyntax_UShort() Dim compilation = CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Option Explicit On Imports System ''' <see cref="UShort"/> ''' <see cref="UShort.ToString()S"/> Public Class C End Class ]]> </file> </compilation>, <error></error>) Dim tree = compilation.SyntaxTrees(0) Dim names = FindNodesOfTypeFromText(Of PredefinedTypeSyntax)(tree, "UShort").ToArray() Assert.Equal(2, names.Length) Dim model = compilation.GetSemanticModel(tree) TestSymbolAndTypeInfoForType(model, names(0), compilation.GetSpecialType(SpecialType.System_UInt16)) TestSymbolAndTypeInfoForType(model, names(1), compilation.GetSpecialType(SpecialType.System_UInt16)) End Sub <Fact()> Public Sub GetSymbolInfo_PredefinedTypeSyntax_String() Dim compilation = CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Option Explicit On Imports System ''' <see cref="String"/> ''' <see cref="String.GetHashCode()S"/> Public Class C End Class ]]> </file> </compilation>, <error></error>) Dim tree = compilation.SyntaxTrees(0) Dim names = FindNodesOfTypeFromText(Of PredefinedTypeSyntax)(tree, "String").ToArray() Assert.Equal(2, names.Length) Dim model = compilation.GetSemanticModel(tree) TestSymbolAndTypeInfoForType(model, names(0), compilation.GetSpecialType(SpecialType.System_String)) TestSymbolAndTypeInfoForType(model, names(1), compilation.GetSpecialType(SpecialType.System_String)) End Sub <Fact()> Public Sub GetSymbolInfo_NameSyntax_Type() Dim compilation = CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Option Explicit On Imports System Public Class C(Of X) End Class ''' <see cref="Y"/> ' failed in dev11 ''' <see cref="S"/> ' failed in dev11 Public Class C(Of X, Y) Public FLD As String ''' <see cref="X"/> ''' <see cref="T"/> ''' <see cref="C"/> ''' <see cref="C(of x)"/> ''' <see cref="C(of x, y)"/> ''' <see cref="C(of x, y).s"/> Public Shared Sub S(Of T)() C(Of X, Y).S(Of Integer)() Dim a As C(Of X, Y) = Nothing Dim b As C(Of X) = Nothing End Sub End Class ]]> </file> </compilation>, <error> <![CDATA[ BC42375: XML comment has a tag with a 'cref' attribute 'Y' that bound to a type parameter. Use the <typeparamref> tag instead. ''' <see cref="Y"/> ' failed in dev11 ~~~~~~~~ BC42375: XML comment has a tag with a 'cref' attribute 'X' that bound to a type parameter. Use the <typeparamref> tag instead. ''' <see cref="X"/> ~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'T' that could not be resolved. ''' <see cref="T"/> ~~~~~~~~ ]]> </error>) Dim tree = compilation.SyntaxTrees(0) Dim names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "C").ToArray() Assert.Equal(7, names.Length) Dim model = compilation.GetSemanticModel(tree) Dim expSymInfo1 = model.GetSymbolInfo(names(4)) Assert.NotNull(expSymInfo1.Symbol) TestSymbolAndTypeInfoForType(model, names(5), expSymInfo1.Symbol.OriginalDefinition) Dim expSymInfo3 = model.GetSymbolInfo(names(6)) Assert.NotNull(expSymInfo3.Symbol) Assert.NotSame(expSymInfo1.Symbol.OriginalDefinition, expSymInfo3.Symbol.OriginalDefinition) Dim actSymInfo1 = model.GetSymbolInfo(names(0)) Assert.Equal(CandidateReason.Ambiguous, actSymInfo1.CandidateReason) Assert.Equal(2, actSymInfo1.CandidateSymbols.Length) Dim list = actSymInfo1.CandidateSymbols.ToArray() Array.Sort(list, Function(x As ISymbol, y As ISymbol) compilation.CompareSourceLocations(x.Locations(0), y.Locations(0))) Assert.Same(expSymInfo3.Symbol.OriginalDefinition, list(0).OriginalDefinition) Assert.Same(expSymInfo1.Symbol.OriginalDefinition, list(1).OriginalDefinition) TestSymbolAndTypeInfoForType(model, names(1), expSymInfo3.Symbol.OriginalDefinition) TestSymbolAndTypeInfoForType(model, names(2), expSymInfo1.Symbol.OriginalDefinition) TestSymbolAndTypeInfoForType(model, names(3), expSymInfo1.Symbol.OriginalDefinition) names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "X").ToArray() Assert.Equal(4, names.Length) Dim typeParamSymInfo = model.GetSymbolInfo(names(0)) Assert.Null(typeParamSymInfo.Symbol) Assert.Equal(SymbolKind.TypeParameter, typeParamSymInfo.CandidateSymbols.Single().Kind) Assert.Equal(CandidateReason.NotReferencable, typeParamSymInfo.CandidateReason) End Sub <Fact()> Public Sub GetSymbolInfo_NameSyntax() Dim compilation = CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Option Explicit On Imports System Class OuterClass Public Class C(Of X) End Class Public Class C(Of X, Y) Public F As Integer End Class End Class Public Class OtherClass ''' <see cref="OuterClass.C"/> ''' <see cref="OuterClass.C(of x)"/> ''' <see cref="OuterClass.C(of x, y)"/> ''' <see cref="OuterClass.C(of x, y).f"/> ''' <see cref="OuterClass.C(of x, y).X"/> Public Shared Sub S(Of T)() End Sub End Class ]]> </file> </compilation>, <error> <![CDATA[ BC42309: XML comment has a tag with a 'cref' attribute 'OuterClass.C(of x, y).X' that could not be resolved. ''' <see cref="OuterClass.C(of x, y).X"/> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]> </error>) Dim tree = compilation.SyntaxTrees(0) Dim names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "C").ToArray() Assert.Equal(5, names.Length) Dim model = compilation.GetSemanticModel(tree) CheckSymbolInfoAndTypeInfo(model, names(0), "OuterClass.C(Of X)", "OuterClass.C(Of X, Y)") CheckSymbolInfoAndTypeInfo(model, names(1), "OuterClass.C(Of x)") CheckSymbolInfoAndTypeInfo(model, names(2), "OuterClass.C(Of x, y)") CheckSymbolInfoAndTypeInfo(model, names(3), "OuterClass.C(Of x, y)") CheckSymbolInfoAndTypeInfo(model, names(4), "OuterClass.C(Of x, y)") End Sub <Fact()> Public Sub GetSymbolInfo_LegacyMode_1() Dim compilation = CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Option Explicit On Imports System Public Class OtherClass ''' <see cref="New"/> ''' <see cref="OtherClass.New"/> ''' <see cref="Operator"/> ''' <see cref="Operator+"/> ''' <see cref="OtherClass.Operator"/> ''' <see cref="OtherClass.Operator+"/> Public Shared Sub S(Of T)() End Sub End Class ]]> </file> </compilation>, <error> <![CDATA[ BC42309: XML comment has a tag with a 'cref' attribute 'New' that could not be resolved. ''' <see cref="New"/> ~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'OtherClass.New' that could not be resolved. ''' <see cref="OtherClass.New"/> ~~~~~~~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'Operator' that could not be resolved. ''' <see cref="Operator"/> ~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'Operator+' that could not be resolved. ''' <see cref="Operator+"/> ~~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'OtherClass.Operator' that could not be resolved. ''' <see cref="OtherClass.Operator"/> ~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'OtherClass.Operator+' that could not be resolved. ''' <see cref="OtherClass.Operator+"/> ~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]> </error>) Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "New").ToArray() Assert.Equal(2, names.Length) CheckSymbolInfoAndTypeInfo(model, names(0)) CheckSymbolInfoAndTypeInfo(model, names(1)) names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "OtherClass").ToArray() Assert.Equal(3, names.Length) CheckSymbolInfoAndTypeInfo(model, names(0), "OtherClass") CheckSymbolInfoAndTypeInfo(model, names(1), "OtherClass") CheckSymbolInfoAndTypeInfo(model, names(2), "OtherClass") Dim crefOperator = FindNodesOfTypeFromText(Of CrefOperatorReferenceSyntax)(tree, "Operator").ToArray() Assert.Equal(4, crefOperator.Length) CheckSymbolInfoAndTypeInfo(model, crefOperator(0)) CheckSymbolInfoAndTypeInfo(model, crefOperator(1)) CheckSymbolInfoAndTypeInfo(model, crefOperator(2)) CheckSymbolInfoAndTypeInfo(model, crefOperator(3)) End Sub <Fact()> Public Sub GetSymbolInfo_LegacyMode_2() Dim compilation = CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Option Explicit On Imports System Public Class OtherClass ''' <see cref="New Public Shared Sub S0(Of T)() End Sub ''' <see cref="OtherClass.New Public Shared Sub S1(Of T)() End Sub ''' <see cref="Operator Public Shared Sub S2(Of T)() End Sub ''' <see cref="Operator+ Public Shared Sub S3(Of T)() End Sub ''' <see cref="OtherClass.Operator Public Shared Sub S4(Of T)() End Sub ''' <see cref="OtherClass.Operator+ Public Shared Sub S5(Of T)() End Sub End Class ]]> </file> </compilation>, <error> <![CDATA[ BC42304: XML documentation parse error: Element is missing an end tag. XML comment will be ignored. ''' <see cref="New ~~~~~~~~~~~~~~~ BC42304: XML documentation parse error: '>' expected. XML comment will be ignored. Public Shared Sub S0(Of T)() ~ BC42304: XML documentation parse error: '>' expected. XML comment will be ignored. Public Shared Sub S0(Of T)() ~ BC42304: XML documentation parse error: Expected beginning '<' for an XML tag. XML comment will be ignored. Public Shared Sub S0(Of T)() ~ BC42304: XML documentation parse error: Element is missing an end tag. XML comment will be ignored. ''' <see cref="OtherClass.New ~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42304: XML documentation parse error: '>' expected. XML comment will be ignored. Public Shared Sub S1(Of T)() ~ BC42304: XML documentation parse error: '>' expected. XML comment will be ignored. Public Shared Sub S1(Of T)() ~ BC42304: XML documentation parse error: Expected beginning '<' for an XML tag. XML comment will be ignored. Public Shared Sub S1(Of T)() ~ BC42304: XML documentation parse error: Element is missing an end tag. XML comment will be ignored. ''' <see cref="Operator ~~~~~~~~~~~~~~~~~~~~ BC42304: XML documentation parse error: '>' expected. XML comment will be ignored. Public Shared Sub S2(Of T)() ~ BC42304: XML documentation parse error: '>' expected. XML comment will be ignored. Public Shared Sub S2(Of T)() ~ BC42304: XML documentation parse error: Expected beginning '<' for an XML tag. XML comment will be ignored. Public Shared Sub S2(Of T)() ~ BC42304: XML documentation parse error: Element is missing an end tag. XML comment will be ignored. ''' <see cref="Operator+ ~~~~~~~~~~~~~~~~~~~~~ BC42304: XML documentation parse error: '>' expected. XML comment will be ignored. Public Shared Sub S3(Of T)() ~ BC42304: XML documentation parse error: '>' expected. XML comment will be ignored. Public Shared Sub S3(Of T)() ~ BC42304: XML documentation parse error: Expected beginning '<' for an XML tag. XML comment will be ignored. Public Shared Sub S3(Of T)() ~ BC42304: XML documentation parse error: Element is missing an end tag. XML comment will be ignored. ''' <see cref="OtherClass.Operator ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42304: XML documentation parse error: '>' expected. XML comment will be ignored. Public Shared Sub S4(Of T)() ~ BC42304: XML documentation parse error: '>' expected. XML comment will be ignored. Public Shared Sub S4(Of T)() ~ BC42304: XML documentation parse error: Expected beginning '<' for an XML tag. XML comment will be ignored. Public Shared Sub S4(Of T)() ~ BC42304: XML documentation parse error: Element is missing an end tag. XML comment will be ignored. ''' <see cref="OtherClass.Operator+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42304: XML documentation parse error: '>' expected. XML comment will be ignored. Public Shared Sub S5(Of T)() ~ BC42304: XML documentation parse error: '>' expected. XML comment will be ignored. Public Shared Sub S5(Of T)() ~ BC42304: XML documentation parse error: Expected beginning '<' for an XML tag. XML comment will be ignored. Public Shared Sub S5(Of T)() ~ ]]> </error>) Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "New").ToArray() Assert.Equal(2, names.Length) CheckSymbolInfoAndTypeInfo(model, names(0)) CheckSymbolInfoAndTypeInfo(model, names(1)) names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "OtherClass").ToArray() Assert.Equal(3, names.Length) CheckSymbolInfoAndTypeInfo(model, names(0), "OtherClass") CheckSymbolInfoAndTypeInfo(model, names(1), "OtherClass") CheckSymbolInfoAndTypeInfo(model, names(2), "OtherClass") Dim crefOperator = FindNodesOfTypeFromText(Of CrefOperatorReferenceSyntax)(tree, "Operator").ToArray() Assert.Equal(4, crefOperator.Length) CheckSymbolInfoAndTypeInfo(model, crefOperator(0)) CheckSymbolInfoAndTypeInfo(model, crefOperator(1)) CheckSymbolInfoAndTypeInfo(model, crefOperator(2)) CheckSymbolInfoAndTypeInfo(model, crefOperator(3)) End Sub <Fact()> Public Sub GetSymbolInfo_NameSyntax_Method_1() Dim compilation = CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Public Class C(Of X) Public Shared Sub Sub1(a As Integer) End Sub Public Shared Sub Sub1(a As Integer, b As Integer) End Sub End Class ''' <see cref="C.Sub1"/> ''' <see cref="C.Sub1(Of A)"/> ''' <see cref="C.Sub1(Of A, B)"/> Public Class OtherClass End Class ]]> </file> </compilation>, <errors> <![CDATA[ BC42309: XML comment has a tag with a 'cref' attribute 'C.Sub1(Of A)' that could not be resolved. ''' <see cref="C.Sub1(Of A)"/> ~~~~~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'C.Sub1(Of A, B)' that could not be resolved. ''' <see cref="C.Sub1(Of A, B)"/> ~~~~~~~~~~~~~~~~~~~~~~ ]]> </errors>) Dim tree = compilation.SyntaxTrees(0) Dim names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "C").ToArray() Assert.Equal(3, names.Length) Dim model = compilation.GetSemanticModel(tree) CheckSymbolInfoOnly(model, DirectCast(names(0).Parent, ExpressionSyntax), "Sub C(Of X).Sub1(a As System.Int32)", "Sub C(Of X).Sub1(a As System.Int32, b As System.Int32)") CheckSymbolInfoOnly(model, DirectCast(names(1).Parent, ExpressionSyntax)) CheckSymbolInfoOnly(model, DirectCast(names(2).Parent, ExpressionSyntax)) End Sub <Fact()> Public Sub GetSymbolInfo_NameSyntax_Method_2() Dim compilation = CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Public Class C(Of X) Public Shared Sub Sub1(a As Integer) End Sub Public Shared Sub Sub1(Of Y)(a As Integer) End Sub End Class ''' <see cref="C.Sub1"/> ''' <see cref="C.Sub1(Of A)"/> ''' <see cref="C.Sub1(Of A, B)"/> Public Class OtherClass End Class ]]> </file> </compilation>, <errors> <![CDATA[ BC42309: XML comment has a tag with a 'cref' attribute 'C.Sub1(Of A, B)' that could not be resolved. ''' <see cref="C.Sub1(Of A, B)"/> ~~~~~~~~~~~~~~~~~~~~~~ ]]> </errors>) Dim tree = compilation.SyntaxTrees(0) Dim names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "C").ToArray() Assert.Equal(3, names.Length) Dim model = compilation.GetSemanticModel(tree) CheckSymbolInfoOnly(model, DirectCast(names(0).Parent, ExpressionSyntax), "Sub C(Of X).Sub1(a As System.Int32)") CheckSymbolInfoOnly(model, DirectCast(names(1).Parent, ExpressionSyntax), "Sub C(Of X).Sub1(Of A)(a As System.Int32)") CheckSymbolInfoOnly(model, DirectCast(names(2).Parent, ExpressionSyntax)) End Sub <Fact()> Public Sub GetSymbolInfo_NameSyntax_Method_3() Dim compilation = CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Public Class C(Of X) Public Shared Sub Sub1(Of Y, Z)(a As Integer) End Sub Public Shared Sub Sub1(Of Y)(a As Integer) End Sub End Class ''' <see cref="C.Sub1"/> ''' <see cref="C.Sub1(Of A)"/> ''' <see cref="C.Sub1(Of A, B)"/> Public Class OtherClass End Class ]]> </file> </compilation>, <errors></errors>) Dim tree = compilation.SyntaxTrees(0) Dim names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "C").ToArray() Assert.Equal(3, names.Length) Dim model = compilation.GetSemanticModel(tree) CheckSymbolInfoOnly(model, DirectCast(names(0).Parent, ExpressionSyntax), "Sub C(Of X).Sub1(Of Y)(a As System.Int32)", "Sub C(Of X).Sub1(Of Y, Z)(a As System.Int32)") CheckSymbolInfoOnly(model, DirectCast(names(1).Parent, ExpressionSyntax), "Sub C(Of X).Sub1(Of A)(a As System.Int32)") CheckSymbolInfoOnly(model, DirectCast(names(2).Parent, ExpressionSyntax), "Sub C(Of X).Sub1(Of A, B)(a As System.Int32)") End Sub <Fact()> Public Sub GetSymbolInfo_NameSyntax_Event_Field_Property() Dim compilation = CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Public Class C(Of X) Public ReadOnly Property Prop1(a As Integer) As String Get Return Nothing End Get End Property Public Property Prop1 As String Public Event Ev1 As Action Public Dim Fld As String End Class ''' <see cref="C.Fld"/> ''' <see cref="C.Fld(Of Integer)"/> ''' <see cref="C.Ev1"/> ''' <see cref="C.Ev1(Of X)"/> ''' <see cref="C.Prop1"/> ''' <see cref="C.Prop1(Of A)"/> Public Class OtherClass End Class ]]> </file> </compilation>, <errors> <![CDATA[ BC42309: XML comment has a tag with a 'cref' attribute 'C.Fld(Of Integer)' that could not be resolved. ''' <see cref="C.Fld(Of Integer)"/> ~~~~~~~~~~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'C.Ev1(Of X)' that could not be resolved. ''' <see cref="C.Ev1(Of X)"/> ~~~~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'C.Prop1(Of A)' that could not be resolved. ''' <see cref="C.Prop1(Of A)"/> ~~~~~~~~~~~~~~~~~~~~ ]]> </errors>) Dim tree As SyntaxTree = compilation.SyntaxTrees(0) Dim names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "C") Assert.Equal(6, names.Length) Dim model = compilation.GetSemanticModel(tree) CheckSymbolInfoOnly(model, DirectCast(names(0).Parent, ExpressionSyntax), "C(Of X).Fld As System.String") CheckSymbolInfoOnly(model, DirectCast(names(1).Parent, ExpressionSyntax)) CheckSymbolInfoOnly(model, DirectCast(names(2).Parent, ExpressionSyntax), "Event C(Of X).Ev1 As System.Action") CheckSymbolInfoOnly(model, DirectCast(names(3).Parent, ExpressionSyntax)) CheckSymbolInfoOnly(model, DirectCast(names(4).Parent, ExpressionSyntax), "Property C(Of X).Prop1 As System.String", "ReadOnly Property C(Of X).Prop1(a As System.Int32) As System.String") CheckSymbolInfoOnly(model, DirectCast(names(5).Parent, ExpressionSyntax)) End Sub <Fact()> Public Sub SemanticInfo_InsideCref() Dim compilation = CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Public Class Clazz(Of T) ''' <see cref="X(Of T, T(Of T, X, InnerClazz(Of X)))"/> Public Class InnerClazz(Of X) End Class End Class ]]> </file> </compilation>, <errors> <![CDATA[ BC42309: XML comment has a tag with a 'cref' attribute 'X(Of T, T(Of T, X, InnerClazz(Of X)))' that could not be resolved. ''' <see cref="X(Of T, T(Of T, X, InnerClazz(Of X)))"/> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]> </errors>) Dim tree As SyntaxTree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "InnerClazz") Assert.Equal(1, names.Length) CheckSymbolInfoAndTypeInfo(model, DirectCast(names(0), ExpressionSyntax), "Clazz(Of T).InnerClazz(Of X)") names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "T") Assert.Equal(3, names.Length) CheckSymbolInfoAndTypeInfo(model, DirectCast(names(0), ExpressionSyntax), "T") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(1), ExpressionSyntax)) CheckSymbolInfoAndTypeInfo(model, DirectCast(names(2), ExpressionSyntax), "T") names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "X") Assert.Equal(3, names.Length) CheckSymbolInfoAndTypeInfo(model, DirectCast(names(0), ExpressionSyntax)) CheckSymbolInfoAndTypeInfo(model, DirectCast(names(1), ExpressionSyntax), "X") ' Did not bind in dev11. CheckSymbolInfoAndTypeInfo(model, DirectCast(names(2), ExpressionSyntax), "X") ' Did not bind in dev11. End Sub <Fact()> Public Sub SemanticInfo_InsideParam() Dim compilation = CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System ''' <summary><param name="a" nested="true">@OuterClass(Of X)</param></summary> ''' <param name="a">@OuterClass(Of X)</param> Public MustInherit Class OuterClass(Of X) ''' <summary><param name="a" nested="true">@F</param></summary> ''' <param name="a">@F</param> Public F As String ''' <summary><param name="a" nested="true">@S(Of T)</param></summary> ''' <param name="a">@S(Of T)</param> Public Shared Sub S(Of T)(a As Integer) End Sub ''' <summary><param name="a" nested="true">@FUN(Of T)</param></summary> ''' <param name="a">@FUN(Of T)</param> Public MustOverride Function FUN(Of T)(a As T) As String ''' <summary><param name="a" nested="true">@Operator +</param></summary> ''' <param name="a">@Operator +</param> Public Shared Operator +(a As OuterClass(Of X), b As Integer) As Integer Return Nothing End Operator ''' <summary><param name="a" nested="true">@Operator CType</param></summary> ''' <param name="a">@Operator CType</param> Public Shared Narrowing Operator CType(a As Integer) As OuterClass(Of X) Return Nothing End Operator ''' <summary><param name="obj" nested="true">@E</param></summary> ''' <param name="obj">@E</param> Public Event E As Action(Of Integer) ''' <summary><param name="a" nested="true">@E2</param></summary> ''' <param name="a">@E2</param> Public Event E2(a As Integer) ''' <summary><param name="a" nested="true">@P</param></summary> ''' <param name="a">@P</param> Property P As String ''' <summary><param name="a" nested="true">@P(a As String)</param></summary> ''' <param name="a">@P(a As String)</param> ReadOnly Property P(a As String) As String Get Return Nothing End Get End Property ''' <summary><param name="a" nested="true">@D(a As Integer)</param></summary> ''' <param name="a">@D(a As Integer)</param> Public Delegate Function D(a As Integer) As String ''' <summary><param name="a" nested="true">@SD(a As Integer)</param></summary> ''' <param name="a">@SD(a As Integer)</param> Public Delegate Sub SD(a As Integer) ''' <summary><param name="a" nested="true">@ENM</param></summary> ''' <param name="a">@ENM</param> Public Enum ENM ''' <summary><param name="a" nested="true">@DefaultValue</param></summary> ''' <param name="a">@DefaultValue</param> DefaultValue End Enum ''' <summary><param name="a" nested="true">@INT(Of INTT)</param></summary> ''' <param name="a">@INT(Of INTT)</param> Public Interface INT(Of INTT) ''' <summary><param name="a" nested="true">@INTS(a As Integer)</param></summary> ''' <param name="a">@INTS(a As Integer)</param> Sub INTS(a As Integer) End Interface End Class ''' <param name="a" nested="true">@M0</param> ''' <summary><param name="a">@M0</param></summary> Public Module M0 Public a As Integer End Module ]]> </file> </compilation>, <errors> <![CDATA[ BC42306: XML comment tag 'param' is not permitted on a 'class' language element. ''' <summary><param name="a" nested="true">@OuterClass(Of X)</param></summary> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'param' is not permitted on a 'class' language element. ''' <param name="a">@OuterClass(Of X)</param> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'param' is not permitted on a 'variable' language element. ''' <summary><param name="a" nested="true">@F</param></summary> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'param' is not permitted on a 'variable' language element. ''' <param name="a">@F</param> ~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42307: XML comment parameter 'a' does not match a parameter on the corresponding 'property' statement. ''' <summary><param name="a" nested="true">@P</param></summary> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42307: XML comment parameter 'a' does not match a parameter on the corresponding 'property' statement. ''' <param name="a">@P</param> ~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'param' is not permitted on a 'enum' language element. ''' <summary><param name="a" nested="true">@ENM</param></summary> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'param' is not permitted on a 'enum' language element. ''' <param name="a">@ENM</param> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'param' is not permitted on a 'variable' language element. ''' <summary><param name="a" nested="true">@DefaultValue</param></summary> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'param' is not permitted on a 'variable' language element. ''' <param name="a">@DefaultValue</param> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'param' is not permitted on a 'interface' language element. ''' <summary><param name="a" nested="true">@INT(Of INTT)</param></summary> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'param' is not permitted on a 'interface' language element. ''' <param name="a">@INT(Of INTT)</param> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'param' is not permitted on a 'module' language element. ''' <param name="a" nested="true">@M0</param> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'param' is not permitted on a 'module' language element. ''' <summary><param name="a">@M0</param></summary> ~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]> </errors>) Dim tree As SyntaxTree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "obj") Assert.Equal(2, names.Length) CheckSymbolInfoOnly(model, DirectCast(names(0), ExpressionSyntax), "obj As System.Int32") CheckSymbolInfoOnly(model, DirectCast(names(1), ExpressionSyntax), "obj As System.Int32") names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "a") Assert.Equal(32, names.Length) CheckSymbolInfoOnly(model, DirectCast(names(0), ExpressionSyntax)) CheckSymbolInfoOnly(model, DirectCast(names(1), ExpressionSyntax)) CheckSymbolInfoOnly(model, DirectCast(names(2), ExpressionSyntax)) CheckSymbolInfoOnly(model, DirectCast(names(3), ExpressionSyntax)) CheckSymbolInfoOnly(model, DirectCast(names(4), ExpressionSyntax), "a As System.Int32") CheckSymbolInfoOnly(model, DirectCast(names(5), ExpressionSyntax), "a As System.Int32") CheckSymbolInfoOnly(model, DirectCast(names(6), ExpressionSyntax), "a As T") CheckSymbolInfoOnly(model, DirectCast(names(7), ExpressionSyntax), "a As T") CheckSymbolInfoOnly(model, DirectCast(names(8), ExpressionSyntax), "a As OuterClass(Of X)") CheckSymbolInfoOnly(model, DirectCast(names(9), ExpressionSyntax), "a As OuterClass(Of X)") CheckSymbolInfoOnly(model, DirectCast(names(10), ExpressionSyntax), "a As System.Int32") CheckSymbolInfoOnly(model, DirectCast(names(11), ExpressionSyntax), "a As System.Int32") CheckSymbolInfoOnly(model, DirectCast(names(12), ExpressionSyntax), "a As System.Int32") CheckSymbolInfoOnly(model, DirectCast(names(13), ExpressionSyntax), "a As System.Int32") CheckSymbolInfoOnly(model, DirectCast(names(14), ExpressionSyntax)) CheckSymbolInfoOnly(model, DirectCast(names(15), ExpressionSyntax)) CheckSymbolInfoOnly(model, DirectCast(names(16), ExpressionSyntax), "a As System.String") CheckSymbolInfoOnly(model, DirectCast(names(17), ExpressionSyntax), "a As System.String") CheckSymbolInfoOnly(model, DirectCast(names(18), ExpressionSyntax), "a As System.Int32") CheckSymbolInfoOnly(model, DirectCast(names(19), ExpressionSyntax), "a As System.Int32") CheckSymbolInfoOnly(model, DirectCast(names(20), ExpressionSyntax), "a As System.Int32") CheckSymbolInfoOnly(model, DirectCast(names(21), ExpressionSyntax), "a As System.Int32") CheckSymbolInfoOnly(model, DirectCast(names(22), ExpressionSyntax)) CheckSymbolInfoOnly(model, DirectCast(names(23), ExpressionSyntax)) CheckSymbolInfoOnly(model, DirectCast(names(24), ExpressionSyntax)) CheckSymbolInfoOnly(model, DirectCast(names(25), ExpressionSyntax)) CheckSymbolInfoOnly(model, DirectCast(names(26), ExpressionSyntax)) CheckSymbolInfoOnly(model, DirectCast(names(27), ExpressionSyntax)) CheckSymbolInfoOnly(model, DirectCast(names(28), ExpressionSyntax), "a As System.Int32") CheckSymbolInfoOnly(model, DirectCast(names(29), ExpressionSyntax), "a As System.Int32") CheckSymbolInfoOnly(model, DirectCast(names(30), ExpressionSyntax)) CheckSymbolInfoOnly(model, DirectCast(names(31), ExpressionSyntax)) End Sub <Fact()> Public Sub SemanticInfo_InsideParamRef() Dim compilation = CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System ''' <summary><paramref name="a" nested="true">@OuterClass(Of X)</paramref></summary> ''' <paramref name="a">@OuterClass(Of X)</paramref> Public MustInherit Class OuterClass(Of X) ''' <summary><paramref name="a" nested="true">@F</paramref></summary> ''' <paramref name="a">@F</paramref> Public F As String ''' <summary><paramref name="a" nested="true">@S(Of T)</paramref></summary> ''' <paramref name="a">@S(Of T)</paramref> Public Shared Sub S(Of T)(a As Integer) End Sub ''' <summary><paramref name="a" nested="true">@FUN(Of T)</paramref></summary> ''' <paramref name="a">@FUN(Of T)</paramref> Public MustOverride Function FUN(Of T)(a As T) As String ''' <summary><paramref name="a" nested="true">@Operator +</paramref></summary> ''' <paramref name="a">@Operator +</paramref> Public Shared Operator +(a As OuterClass(Of X), b As Integer) As Integer Return Nothing End Operator ''' <summary><paramref name="a" nested="true">@Operator CType</paramref></summary> ''' <paramref name="a">@Operator CType</paramref> Public Shared Narrowing Operator CType(a As Integer) As OuterClass(Of X) Return Nothing End Operator ''' <summary><paramref name="obj" nested="true">@E</paramref></summary> ''' <paramref name="obj">@E</paramref> Public Event E As Action(Of Integer) ''' <summary><paramref name="a" nested="true">@E2</paramref></summary> ''' <paramref name="a">@E2</paramref> Public Event E2(a As Integer) ''' <summary><paramref name="a" nested="true">@P</paramref></summary> ''' <paramref name="a">@P</paramref> Property P As String ''' <summary><paramref name="a" nested="true">@P(a As String)</paramref></summary> ''' <paramref name="a">@P(a As String)</paramref> ReadOnly Property P(a As String) As String Get Return Nothing End Get End Property ''' <summary><paramref name="a" nested="true">@D(a As Integer)</paramref></summary> ''' <paramref name="a">@D(a As Integer)</paramref> Public Delegate Function D(a As Integer) As String ''' <summary><paramref name="a" nested="true">@SD(a As Integer)</paramref></summary> ''' <paramref name="a">@SD(a As Integer)</paramref> Public Delegate Sub SD(a As Integer) ''' <summary><paramref name="a" nested="true">@ENM</paramref></summary> ''' <paramref name="a">@ENM</paramref> Public Enum ENM ''' <summary><paramref name="a" nested="true">@DefaultValue</paramref></summary> ''' <paramref name="a">@DefaultValue</paramref> DefaultValue End Enum ''' <summary><paramref name="a" nested="true">@INT(Of INTT)</paramref></summary> ''' <paramref name="a">@INT(Of INTT)</paramref> Public Interface INT(Of INTT) ''' <summary><paramref name="a" nested="true">@INTS(a As Integer)</paramref></summary> ''' <paramref name="a">@INTS(a As Integer)</paramref> Sub INTS(a As Integer) End Interface End Class ''' <paramref name="a" nested="true">@M0</paramref> ''' <summary><paramref name="a">@M0</paramref></summary> Public Module M0 Public a As Integer End Module ]]> </file> </compilation>, <errors> <![CDATA[ BC42306: XML comment tag 'paramref' is not permitted on a 'class' language element. ''' <summary><paramref name="a" nested="true">@OuterClass(Of X)</paramref></summary> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'paramref' is not permitted on a 'class' language element. ''' <paramref name="a">@OuterClass(Of X)</paramref> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'paramref' is not permitted on a 'variable' language element. ''' <summary><paramref name="a" nested="true">@F</paramref></summary> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'paramref' is not permitted on a 'variable' language element. ''' <paramref name="a">@F</paramref> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42307: XML comment parameter 'a' does not match a parameter on the corresponding 'property' statement. ''' <summary><paramref name="a" nested="true">@P</paramref></summary> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42307: XML comment parameter 'a' does not match a parameter on the corresponding 'property' statement. ''' <paramref name="a">@P</paramref> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'paramref' is not permitted on a 'enum' language element. ''' <summary><paramref name="a" nested="true">@ENM</paramref></summary> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'paramref' is not permitted on a 'enum' language element. ''' <paramref name="a">@ENM</paramref> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'paramref' is not permitted on a 'variable' language element. ''' <summary><paramref name="a" nested="true">@DefaultValue</paramref></summary> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'paramref' is not permitted on a 'variable' language element. ''' <paramref name="a">@DefaultValue</paramref> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'paramref' is not permitted on a 'interface' language element. ''' <summary><paramref name="a" nested="true">@INT(Of INTT)</paramref></summary> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'paramref' is not permitted on a 'interface' language element. ''' <paramref name="a">@INT(Of INTT)</paramref> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'paramref' is not permitted on a 'module' language element. ''' <paramref name="a" nested="true">@M0</paramref> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'paramref' is not permitted on a 'module' language element. ''' <summary><paramref name="a">@M0</paramref></summary> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]> </errors>) Dim tree As SyntaxTree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "obj") Assert.Equal(2, names.Length) CheckSymbolInfoOnly(model, DirectCast(names(0), ExpressionSyntax), "obj As System.Int32") CheckSymbolInfoOnly(model, DirectCast(names(0), ExpressionSyntax), "obj As System.Int32") names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "a") Assert.Equal(32, names.Length) CheckSymbolInfoOnly(model, DirectCast(names(0), ExpressionSyntax)) CheckSymbolInfoOnly(model, DirectCast(names(1), ExpressionSyntax)) CheckSymbolInfoOnly(model, DirectCast(names(2), ExpressionSyntax)) CheckSymbolInfoOnly(model, DirectCast(names(3), ExpressionSyntax)) CheckSymbolInfoOnly(model, DirectCast(names(4), ExpressionSyntax), "a As System.Int32") CheckSymbolInfoOnly(model, DirectCast(names(5), ExpressionSyntax), "a As System.Int32") CheckSymbolInfoOnly(model, DirectCast(names(6), ExpressionSyntax), "a As T") CheckSymbolInfoOnly(model, DirectCast(names(7), ExpressionSyntax), "a As T") CheckSymbolInfoOnly(model, DirectCast(names(8), ExpressionSyntax), "a As OuterClass(Of X)") CheckSymbolInfoOnly(model, DirectCast(names(9), ExpressionSyntax), "a As OuterClass(Of X)") CheckSymbolInfoOnly(model, DirectCast(names(10), ExpressionSyntax), "a As System.Int32") CheckSymbolInfoOnly(model, DirectCast(names(11), ExpressionSyntax), "a As System.Int32") CheckSymbolInfoOnly(model, DirectCast(names(12), ExpressionSyntax), "a As System.Int32") CheckSymbolInfoOnly(model, DirectCast(names(13), ExpressionSyntax), "a As System.Int32") CheckSymbolInfoOnly(model, DirectCast(names(14), ExpressionSyntax)) CheckSymbolInfoOnly(model, DirectCast(names(15), ExpressionSyntax)) CheckSymbolInfoOnly(model, DirectCast(names(16), ExpressionSyntax), "a As System.String") CheckSymbolInfoOnly(model, DirectCast(names(17), ExpressionSyntax), "a As System.String") CheckSymbolInfoOnly(model, DirectCast(names(18), ExpressionSyntax), "a As System.Int32") CheckSymbolInfoOnly(model, DirectCast(names(19), ExpressionSyntax), "a As System.Int32") CheckSymbolInfoOnly(model, DirectCast(names(20), ExpressionSyntax), "a As System.Int32") CheckSymbolInfoOnly(model, DirectCast(names(21), ExpressionSyntax), "a As System.Int32") CheckSymbolInfoOnly(model, DirectCast(names(22), ExpressionSyntax)) CheckSymbolInfoOnly(model, DirectCast(names(23), ExpressionSyntax)) CheckSymbolInfoOnly(model, DirectCast(names(24), ExpressionSyntax)) CheckSymbolInfoOnly(model, DirectCast(names(25), ExpressionSyntax)) CheckSymbolInfoOnly(model, DirectCast(names(26), ExpressionSyntax)) CheckSymbolInfoOnly(model, DirectCast(names(27), ExpressionSyntax)) CheckSymbolInfoOnly(model, DirectCast(names(28), ExpressionSyntax), "a As System.Int32") CheckSymbolInfoOnly(model, DirectCast(names(29), ExpressionSyntax), "a As System.Int32") CheckSymbolInfoOnly(model, DirectCast(names(30), ExpressionSyntax)) CheckSymbolInfoOnly(model, DirectCast(names(31), ExpressionSyntax)) End Sub <Fact()> Public Sub SemanticInfo_InsideTypeParam() Dim compilation = CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System ''' <summary><typeparam name="x" nested="true">@OuterClass(Of X)</typeparam></summary> ''' <typeparam name="x">@OuterClass(Of X)</typeparam> Public MustInherit Class OuterClass(Of X) ''' <summary><typeparam name="x" nested="true">@F</typeparam></summary> ''' <typeparam name="x">@F</typeparam> Public F As String ''' <summary><typeparam name="t" nested="true">@S(Of T)</typeparam></summary> ''' <typeparam name="t">@S(Of T)</typeparam> Public Shared Sub S(Of T)(a As Integer) End Sub ''' <summary><typeparam name="tt" nested="true">@FUN(Of T)</typeparam></summary> ''' <typeparam name="tt">@FUN(Of T)</typeparam> Public MustOverride Function FUN(Of TT)(a As Integer) As String ''' <summary><typeparam name="x" nested="true">@Operator +</typeparam></summary> ''' <typeparam name="x">@Operator +</typeparam> Public Shared Operator +(a As OuterClass(Of X), b As Integer) As Integer Return Nothing End Operator ''' <summary><typeparam name="x" nested="true">@Operator CType</typeparam></summary> ''' <typeparam name="x">@Operator CType</typeparam> Public Shared Narrowing Operator CType(a As Integer) As OuterClass(Of X) Return Nothing End Operator ''' <summary><typeparam name="t" nested="true">@E</typeparam></summary> ''' <typeparam name="t">@E</typeparam> Public Event E As Action(Of Integer) ''' <summary><typeparam name="x" nested="true">@E2</typeparam></summary> ''' <typeparam name="x">@E2</typeparam> Public Event E2(a As Integer) ''' <summary><typeparam name="x" nested="true">@P</typeparam></summary> ''' <typeparam name="x">@P</typeparam> Property P As String ''' <summary><typeparam name="x" nested="true">@P(a As String)</typeparam></summary> ''' <typeparam name="x">@P(a As String)</typeparam> ReadOnly Property P(a As String) As String Get Return Nothing End Get End Property ''' <summary><typeparam name="tt" nested="true">@D(a As Integer)</typeparam></summary> ''' <typeparam name="tt">@D(a As Integer)</typeparam> Public Delegate Function D(Of TT)(a As Integer) As String ''' <summary><typeparam name="t" nested="true">@SD(a As Integer)</typeparam></summary> ''' <typeparam name="t">@SD(a As Integer)</typeparam> Public Delegate Sub SD(Of T)(a As Integer) ''' <summary><typeparam name="x" nested="true">@ENM</typeparam></summary> ''' <typeparam name="x">@ENM</typeparam> Public Enum ENM ''' <summary><typeparam name="x" nested="true">@DefaultValue</typeparam></summary> ''' <typeparam name="x">@DefaultValue</typeparam> DefaultValue End Enum ''' <summary><typeparam name="tt" nested="true">@INT(Of TT)</typeparam></summary> ''' <typeparam name="tt">@INT(Of TT)</typeparam> Public Interface INT(Of TT) ''' <summary><typeparam name="t" nested="true">@INTS(a As Integer)</typeparam></summary> ''' <typeparam name="t">@INTS(a As Integer)</typeparam> Sub INTS(Of T)(a As Integer) End Interface End Class ''' <typeparam name="x" nested="true">@M0</typeparam> ''' <summary><typeparam name="x">@M0</typeparam></summary> Public Module M0 Public a As Integer End Module ]]> </file> </compilation>, <errors> <![CDATA[ BC42306: XML comment tag 'typeparam' is not permitted on a 'variable' language element. ''' <summary><typeparam name="x" nested="true">@F</typeparam></summary> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'typeparam' is not permitted on a 'variable' language element. ''' <typeparam name="x">@F</typeparam> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'typeparam' is not permitted on a 'operator' language element. ''' <summary><typeparam name="x" nested="true">@Operator +</typeparam></summary> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'typeparam' is not permitted on a 'operator' language element. ''' <typeparam name="x">@Operator +</typeparam> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42317: XML comment type parameter 'x' does not match a type parameter on the corresponding 'operator' statement. ''' <summary><typeparam name="x" nested="true">@Operator CType</typeparam></summary> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42317: XML comment type parameter 'x' does not match a type parameter on the corresponding 'operator' statement. ''' <typeparam name="x">@Operator CType</typeparam> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'typeparam' is not permitted on a 'event' language element. ''' <summary><typeparam name="t" nested="true">@E</typeparam></summary> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'typeparam' is not permitted on a 'event' language element. ''' <typeparam name="t">@E</typeparam> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'typeparam' is not permitted on a 'event' language element. ''' <summary><typeparam name="x" nested="true">@E2</typeparam></summary> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'typeparam' is not permitted on a 'event' language element. ''' <typeparam name="x">@E2</typeparam> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'typeparam' is not permitted on a 'property' language element. ''' <summary><typeparam name="x" nested="true">@P</typeparam></summary> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'typeparam' is not permitted on a 'property' language element. ''' <typeparam name="x">@P</typeparam> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'typeparam' is not permitted on a 'property' language element. ''' <summary><typeparam name="x" nested="true">@P(a As String)</typeparam></summary> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'typeparam' is not permitted on a 'property' language element. ''' <typeparam name="x">@P(a As String)</typeparam> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'typeparam' is not permitted on a 'enum' language element. ''' <summary><typeparam name="x" nested="true">@ENM</typeparam></summary> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'typeparam' is not permitted on a 'enum' language element. ''' <typeparam name="x">@ENM</typeparam> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'typeparam' is not permitted on a 'variable' language element. ''' <summary><typeparam name="x" nested="true">@DefaultValue</typeparam></summary> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'typeparam' is not permitted on a 'variable' language element. ''' <typeparam name="x">@DefaultValue</typeparam> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'typeparam' is not permitted on a 'module' language element. ''' <typeparam name="x" nested="true">@M0</typeparam> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'typeparam' is not permitted on a 'module' language element. ''' <summary><typeparam name="x">@M0</typeparam></summary> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]> </errors>) Dim tree As SyntaxTree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "t") Assert.Equal(8, names.Length) CheckSymbolInfoAndTypeInfo(model, DirectCast(names(0), ExpressionSyntax), "T") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(1), ExpressionSyntax), "T") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(2), ExpressionSyntax)) CheckSymbolInfoAndTypeInfo(model, DirectCast(names(3), ExpressionSyntax)) CheckSymbolInfoAndTypeInfo(model, DirectCast(names(4), ExpressionSyntax), "T") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(5), ExpressionSyntax), "T") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(6), ExpressionSyntax), "T") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(7), ExpressionSyntax), "T") names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "tt") Assert.Equal(6, names.Length) CheckSymbolInfoAndTypeInfo(model, DirectCast(names(0), ExpressionSyntax), "TT") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(1), ExpressionSyntax), "TT") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(2), ExpressionSyntax), "TT") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(3), ExpressionSyntax), "TT") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(4), ExpressionSyntax), "TT") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(5), ExpressionSyntax), "TT") names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "x") Assert.Equal(20, names.Length) CheckSymbolInfoAndTypeInfo(model, DirectCast(names(0), ExpressionSyntax), "X") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(1), ExpressionSyntax), "X") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(2), ExpressionSyntax)) CheckSymbolInfoAndTypeInfo(model, DirectCast(names(3), ExpressionSyntax)) CheckSymbolInfoAndTypeInfo(model, DirectCast(names(4), ExpressionSyntax)) CheckSymbolInfoAndTypeInfo(model, DirectCast(names(5), ExpressionSyntax)) CheckSymbolInfoAndTypeInfo(model, DirectCast(names(6), ExpressionSyntax)) CheckSymbolInfoAndTypeInfo(model, DirectCast(names(7), ExpressionSyntax)) CheckSymbolInfoAndTypeInfo(model, DirectCast(names(8), ExpressionSyntax)) CheckSymbolInfoAndTypeInfo(model, DirectCast(names(9), ExpressionSyntax)) CheckSymbolInfoAndTypeInfo(model, DirectCast(names(10), ExpressionSyntax)) CheckSymbolInfoAndTypeInfo(model, DirectCast(names(11), ExpressionSyntax)) CheckSymbolInfoAndTypeInfo(model, DirectCast(names(12), ExpressionSyntax)) CheckSymbolInfoAndTypeInfo(model, DirectCast(names(13), ExpressionSyntax)) CheckSymbolInfoAndTypeInfo(model, DirectCast(names(14), ExpressionSyntax)) CheckSymbolInfoAndTypeInfo(model, DirectCast(names(15), ExpressionSyntax)) CheckSymbolInfoAndTypeInfo(model, DirectCast(names(16), ExpressionSyntax)) CheckSymbolInfoAndTypeInfo(model, DirectCast(names(17), ExpressionSyntax)) CheckSymbolInfoAndTypeInfo(model, DirectCast(names(18), ExpressionSyntax)) CheckSymbolInfoAndTypeInfo(model, DirectCast(names(19), ExpressionSyntax)) End Sub <Fact()> Public Sub SemanticInfo_InsideTypeParamRef() Dim compilation = CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System ''' <summary><typeparamref name="x" nested="true">@OuterClass(Of X)</typeparamref></summary> ''' <typeparamref name="x">@OuterClass(Of X)</typeparamref> Public MustInherit Class OuterClass(Of X) ''' <summary><typeparamref name="x" nested="true">@F</typeparamref></summary> ''' <typeparamref name="x">@F</typeparamref> Public F As String ''' <summary><typeparamref name="t" nested="true">@S(Of T)</typeparamref></summary> ''' <typeparamref name="t">@S(Of T)</typeparamref> Public Shared Sub S(Of T)(a As Integer) End Sub ''' <summary><typeparamref name="tt" nested="true">@FUN(Of T)</typeparamref></summary> ''' <typeparamref name="tt">@FUN(Of T)</typeparamref> Public MustOverride Function FUN(Of TT)(a As Integer) As String ''' <summary><typeparamref name="x" nested="true">@Operator +</typeparamref></summary> ''' <typeparamref name="x">@Operator +</typeparamref> Public Shared Operator +(a As OuterClass(Of X), b As Integer) As Integer Return Nothing End Operator ''' <summary><typeparamref name="x" nested="true">@Operator CType</typeparamref></summary> ''' <typeparamref name="x">@Operator CType</typeparamref> Public Shared Narrowing Operator CType(a As Integer) As OuterClass(Of X) Return Nothing End Operator ''' <summary><typeparamref name="t" nested="true">@E</typeparamref></summary> ''' <typeparamref name="t">@E</typeparamref> Public Event E As Action(Of Integer) ''' <summary><typeparamref name="x" nested="true">@E2</typeparamref></summary> ''' <typeparamref name="x">@E2</typeparamref> Public Event E2(a As Integer) ''' <summary><typeparamref name="x" nested="true">@P</typeparamref></summary> ''' <typeparamref name="x">@P</typeparamref> Property P As String ''' <summary><typeparamref name="x" nested="true">@P(a As String)</typeparamref></summary> ''' <typeparamref name="x">@P(a As String)</typeparamref> ReadOnly Property P(a As String) As String Get Return Nothing End Get End Property ''' <summary><typeparamref name="tt" nested="true">@D(a As Integer)</typeparamref></summary> ''' <typeparamref name="tt">@D(a As Integer)</typeparamref> Public Delegate Function D(Of TT)(a As Integer) As String ''' <summary><typeparamref name="t" nested="true">@SD(a As Integer)</typeparamref></summary> ''' <typeparamref name="t">@SD(a As Integer)</typeparamref> Public Delegate Sub SD(Of T)(a As Integer) ''' <summary><typeparamref name="x" nested="true">@ENM</typeparamref></summary> ''' <typeparamref name="x">@ENM</typeparamref> Public Enum ENM ''' <summary><typeparamref name="x" nested="true">@DefaultValue</typeparamref></summary> ''' <typeparamref name="x">@DefaultValue</typeparamref> DefaultValue End Enum ''' <summary><typeparamref name="tt" nested="true">@INT(Of TT)</typeparamref></summary> ''' <typeparamref name="tt">@INT(Of TT)</typeparamref> Public Interface INT(Of TT) ''' <summary><typeparamref name="t" nested="true">@INTS(a As Integer)</typeparamref></summary> ''' <typeparamref name="t">@INTS(a As Integer)</typeparamref> Sub INTS(Of T)(a As Integer) End Interface End Class ''' <typeparamref name="x" nested="true">@M0</typeparamref> ''' <summary><typeparamref name="x">@M0</typeparamref></summary> Public Module M0 ''' <typeparamref name="x" nested="true">@M0.a</typeparamref> ''' <summary><typeparamref name="x">@M0.a</typeparamref></summary> ''' <typeparamref>@M0.a -- no-name</typeparamref> Public a As Integer End Module ]]> </file> </compilation>, <errors> <![CDATA[ BC42317: XML comment type parameter 't' does not match a type parameter on the corresponding 'event' statement. ''' <summary><typeparamref name="t" nested="true">@E</typeparamref></summary> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42317: XML comment type parameter 't' does not match a type parameter on the corresponding 'event' statement. ''' <typeparamref name="t">@E</typeparamref> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'typeparamref' is not permitted on a 'module' language element. ''' <typeparamref name="x" nested="true">@M0</typeparamref> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'typeparamref' is not permitted on a 'module' language element. ''' <summary><typeparamref name="x">@M0</typeparamref></summary> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42317: XML comment type parameter 'x' does not match a type parameter on the corresponding 'variable' statement. ''' <typeparamref name="x" nested="true">@M0.a</typeparamref> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42317: XML comment type parameter 'x' does not match a type parameter on the corresponding 'variable' statement. ''' <summary><typeparamref name="x">@M0.a</typeparamref></summary> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]> </errors>) Dim tree As SyntaxTree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "t") Assert.Equal(8, names.Length) CheckSymbolInfoAndTypeInfo(model, DirectCast(names(0), ExpressionSyntax), "T") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(1), ExpressionSyntax), "T") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(2), ExpressionSyntax)) CheckSymbolInfoAndTypeInfo(model, DirectCast(names(3), ExpressionSyntax)) CheckSymbolInfoAndTypeInfo(model, DirectCast(names(4), ExpressionSyntax), "T") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(5), ExpressionSyntax), "T") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(6), ExpressionSyntax), "T") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(7), ExpressionSyntax), "T") names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "tt") Assert.Equal(6, names.Length) CheckSymbolInfoAndTypeInfo(model, DirectCast(names(0), ExpressionSyntax), "TT") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(1), ExpressionSyntax), "TT") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(2), ExpressionSyntax), "TT") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(3), ExpressionSyntax), "TT") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(4), ExpressionSyntax), "TT") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(5), ExpressionSyntax), "TT") names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "x") Assert.Equal(22, names.Length) CheckSymbolInfoAndTypeInfo(model, DirectCast(names(0), ExpressionSyntax), "X") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(1), ExpressionSyntax), "X") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(2), ExpressionSyntax), "X") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(3), ExpressionSyntax), "X") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(4), ExpressionSyntax), "X") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(5), ExpressionSyntax), "X") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(6), ExpressionSyntax), "X") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(7), ExpressionSyntax), "X") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(8), ExpressionSyntax), "X") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(9), ExpressionSyntax), "X") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(10), ExpressionSyntax), "X") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(11), ExpressionSyntax), "X") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(12), ExpressionSyntax), "X") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(13), ExpressionSyntax), "X") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(14), ExpressionSyntax), "X") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(15), ExpressionSyntax), "X") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(16), ExpressionSyntax), "X") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(17), ExpressionSyntax), "X") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(18), ExpressionSyntax)) CheckSymbolInfoAndTypeInfo(model, DirectCast(names(19), ExpressionSyntax)) CheckSymbolInfoAndTypeInfo(model, DirectCast(names(20), ExpressionSyntax)) CheckSymbolInfoAndTypeInfo(model, DirectCast(names(21), ExpressionSyntax)) End Sub <Fact()> Public Sub SemanticInfo_RightBinderAndSymbol() Dim compilation = CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System ''' <see cref="X">@OuterClass</see> ' Failed in dev11. ''' <see cref="S">@OuterClass</see> ' Failed in dev11. Public MustInherit Class OuterClass(Of X) ''' <see cref="X">@F</see> ''' <see cref="S">@F</see> ''' <see cref="T">@F</see> Public F As String ''' <see cref="X">@S</see> ''' <see cref="F">@S</see> ''' <see cref="a">@S</see> ''' <see cref="T">@S</see> Public Shared Sub S(Of T)(a As Integer) End Sub ''' <see cref="X">@FUN</see> ''' <see cref="F">@FUN</see> ''' <see cref="a">@FUN</see> ''' <see cref="T">@FUN</see> Public MustOverride Function FUN(Of T)(a As Integer) As String ''' <see cref="X">@InnerClass</see> ''' <see cref="F">@InnerClass</see> ''' <see cref="T">@InnerClass</see> ''' <see cref="Y">@InnerClass</see> ' Failed in dev11. Public Class InnerClass(Of Y) End Class ''' <see cref="X">@E</see> ''' <see cref="F">@E</see> ''' <see cref="T">@E</see> ''' <see cref="obj">@E</see> Public Event E As Action(Of Integer) ''' <see cref="X">@E2</see> ''' <see cref="F">@E2</see> ''' <see cref="a">@E2</see> ''' <see cref="T">@E2</see> Public Event E2(a As Integer) ''' <see cref="X">@P</see> ''' <see cref="F">@P</see> ''' <see cref="T">@P</see> Property P As String ''' <see cref="X">@P(a)</see> ''' <see cref="F">@P(a)</see> ''' <see cref="a">@P(a)</see> ''' <see cref="T">@P(a)</see> ReadOnly Property P(a As String) As String Get Return Nothing End Get End Property ''' <see cref="X">@D</see> ''' <see cref="F">@D</see> ''' <see cref="a">@D</see> ''' <see cref="T">@D</see> Public Delegate Function D(a As Integer) As String ''' <see cref="X">@SD</see> ''' <see cref="F">@SD</see> ''' <see cref="a">@SD</see> ''' <see cref="T">@SD</see> Public Delegate Sub SD(a As Integer) ''' <see cref="X">@ENM</see> ''' <see cref="F">@ENM</see> ''' <see cref="DefaultValue">@ENM</see> ' Failed in dev11. Public Enum ENM ''' <see cref="F">@DefaultValue</see> DefaultValue End Enum ''' <see cref="X">@INT</see> ''' <see cref="F">@INT</see> ''' <see cref="INTT">@INT</see> ' Failed in dev11. ''' <see cref="INTS">@INT</see> ' Failed in dev11. Public Interface INT(Of INTT) ''' <see cref="F">@INTS</see> Sub INTS(a As Integer) End Interface End Class ''' <see cref="Fun02">@M0</see> Public Module M0 ''' <see cref="Fun02">@Fun02</see> Public Function Fun02() As Integer Return Nothing End Function End Module ]]> </file> </compilation>, <errors> <![CDATA[ BC42375: XML comment has a tag with a 'cref' attribute 'X' that bound to a type parameter. Use the <typeparamref> tag instead. ''' <see cref="X">@OuterClass</see> ' Failed in dev11. ~~~~~~~~ BC42375: XML comment has a tag with a 'cref' attribute 'X' that bound to a type parameter. Use the <typeparamref> tag instead. ''' <see cref="X">@F</see> ~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'T' that could not be resolved. ''' <see cref="T">@F</see> ~~~~~~~~ BC42375: XML comment has a tag with a 'cref' attribute 'X' that bound to a type parameter. Use the <typeparamref> tag instead. ''' <see cref="X">@S</see> ~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'a' that could not be resolved. ''' <see cref="a">@S</see> ~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'T' that could not be resolved. ''' <see cref="T">@S</see> ~~~~~~~~ BC42375: XML comment has a tag with a 'cref' attribute 'X' that bound to a type parameter. Use the <typeparamref> tag instead. ''' <see cref="X">@FUN</see> ~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'a' that could not be resolved. ''' <see cref="a">@FUN</see> ~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'T' that could not be resolved. ''' <see cref="T">@FUN</see> ~~~~~~~~ BC42375: XML comment has a tag with a 'cref' attribute 'X' that bound to a type parameter. Use the <typeparamref> tag instead. ''' <see cref="X">@InnerClass</see> ~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'T' that could not be resolved. ''' <see cref="T">@InnerClass</see> ~~~~~~~~ BC42375: XML comment has a tag with a 'cref' attribute 'Y' that bound to a type parameter. Use the <typeparamref> tag instead. ''' <see cref="Y">@InnerClass</see> ' Failed in dev11. ~~~~~~~~ BC42375: XML comment has a tag with a 'cref' attribute 'X' that bound to a type parameter. Use the <typeparamref> tag instead. ''' <see cref="X">@E</see> ~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'T' that could not be resolved. ''' <see cref="T">@E</see> ~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'obj' that could not be resolved. ''' <see cref="obj">@E</see> ~~~~~~~~~~ BC42375: XML comment has a tag with a 'cref' attribute 'X' that bound to a type parameter. Use the <typeparamref> tag instead. ''' <see cref="X">@E2</see> ~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'a' that could not be resolved. ''' <see cref="a">@E2</see> ~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'T' that could not be resolved. ''' <see cref="T">@E2</see> ~~~~~~~~ BC42375: XML comment has a tag with a 'cref' attribute 'X' that bound to a type parameter. Use the <typeparamref> tag instead. ''' <see cref="X">@P</see> ~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'T' that could not be resolved. ''' <see cref="T">@P</see> ~~~~~~~~ BC42375: XML comment has a tag with a 'cref' attribute 'X' that bound to a type parameter. Use the <typeparamref> tag instead. ''' <see cref="X">@P(a)</see> ~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'a' that could not be resolved. ''' <see cref="a">@P(a)</see> ~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'T' that could not be resolved. ''' <see cref="T">@P(a)</see> ~~~~~~~~ BC42375: XML comment has a tag with a 'cref' attribute 'X' that bound to a type parameter. Use the <typeparamref> tag instead. ''' <see cref="X">@D</see> ~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'a' that could not be resolved. ''' <see cref="a">@D</see> ~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'T' that could not be resolved. ''' <see cref="T">@D</see> ~~~~~~~~ BC42375: XML comment has a tag with a 'cref' attribute 'X' that bound to a type parameter. Use the <typeparamref> tag instead. ''' <see cref="X">@SD</see> ~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'a' that could not be resolved. ''' <see cref="a">@SD</see> ~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'T' that could not be resolved. ''' <see cref="T">@SD</see> ~~~~~~~~ BC42375: XML comment has a tag with a 'cref' attribute 'X' that bound to a type parameter. Use the <typeparamref> tag instead. ''' <see cref="X">@ENM</see> ~~~~~~~~ BC42375: XML comment has a tag with a 'cref' attribute 'X' that bound to a type parameter. Use the <typeparamref> tag instead. ''' <see cref="X">@INT</see> ~~~~~~~~ BC42375: XML comment has a tag with a 'cref' attribute 'INTT' that bound to a type parameter. Use the <typeparamref> tag instead. ''' <see cref="INTT">@INT</see> ' Failed in dev11. ~~~~~~~~~~~ ]]> </errors>) Dim tree As SyntaxTree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "X") Assert.Equal(13, names.Length) CheckTypeParameterCrefSymbolInfoAndTypeInfo(model, names(0), "X") CheckTypeParameterCrefSymbolInfoAndTypeInfo(model, names(1), "X") CheckTypeParameterCrefSymbolInfoAndTypeInfo(model, names(2), "X") CheckTypeParameterCrefSymbolInfoAndTypeInfo(model, names(3), "X") CheckTypeParameterCrefSymbolInfoAndTypeInfo(model, names(4), "X") CheckTypeParameterCrefSymbolInfoAndTypeInfo(model, names(5), "X") CheckTypeParameterCrefSymbolInfoAndTypeInfo(model, names(6), "X") CheckTypeParameterCrefSymbolInfoAndTypeInfo(model, names(7), "X") CheckTypeParameterCrefSymbolInfoAndTypeInfo(model, names(8), "X") CheckTypeParameterCrefSymbolInfoAndTypeInfo(model, names(9), "X") CheckTypeParameterCrefSymbolInfoAndTypeInfo(model, names(10), "X") CheckTypeParameterCrefSymbolInfoAndTypeInfo(model, names(11), "X") CheckTypeParameterCrefSymbolInfoAndTypeInfo(model, names(12), "X") names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "S") Assert.Equal(2, names.Length) CheckSymbolInfoOnly(model, names(0), "Sub OuterClass(Of X).S(Of T)(a As System.Int32)") CheckSymbolInfoOnly(model, names(1), "Sub OuterClass(Of X).S(Of T)(a As System.Int32)") names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "T") Assert.Equal(10, names.Length) CheckSymbolInfoOnly(model, names(0)) CheckSymbolInfoOnly(model, names(1)) CheckSymbolInfoOnly(model, names(2)) CheckSymbolInfoOnly(model, names(3)) CheckSymbolInfoOnly(model, names(4)) CheckSymbolInfoOnly(model, names(5)) CheckSymbolInfoOnly(model, names(6)) CheckSymbolInfoOnly(model, names(7)) CheckSymbolInfoOnly(model, names(8)) CheckSymbolInfoOnly(model, names(9)) names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "F") Assert.Equal(13, names.Length) CheckSymbolInfoOnly(model, names(0), "OuterClass(Of X).F As System.String") CheckSymbolInfoOnly(model, names(1), "OuterClass(Of X).F As System.String") CheckSymbolInfoOnly(model, names(2), "OuterClass(Of X).F As System.String") CheckSymbolInfoOnly(model, names(3), "OuterClass(Of X).F As System.String") CheckSymbolInfoOnly(model, names(4), "OuterClass(Of X).F As System.String") CheckSymbolInfoOnly(model, names(5), "OuterClass(Of X).F As System.String") CheckSymbolInfoOnly(model, names(6), "OuterClass(Of X).F As System.String") CheckSymbolInfoOnly(model, names(7), "OuterClass(Of X).F As System.String") CheckSymbolInfoOnly(model, names(8), "OuterClass(Of X).F As System.String") CheckSymbolInfoOnly(model, names(9), "OuterClass(Of X).F As System.String") CheckSymbolInfoOnly(model, names(10), "OuterClass(Of X).F As System.String") CheckSymbolInfoOnly(model, names(11), "OuterClass(Of X).F As System.String") CheckSymbolInfoOnly(model, names(12), "OuterClass(Of X).F As System.String") names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "a") Assert.Equal(6, names.Length) CheckSymbolInfoOnly(model, names(0)) CheckSymbolInfoOnly(model, names(1)) CheckSymbolInfoOnly(model, names(2)) CheckSymbolInfoOnly(model, names(3)) CheckSymbolInfoOnly(model, names(4)) CheckSymbolInfoOnly(model, names(5)) names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "obj") Assert.Equal(1, names.Length) CheckSymbolInfoOnly(model, names(0)) names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "DefaultValue") Assert.Equal(1, names.Length) CheckSymbolInfoOnly(model, names(0), "OuterClass(Of X).ENM.DefaultValue") ' Did not bind in dev11. names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "Fun02") Assert.Equal(2, names.Length) CheckSymbolInfoOnly(model, names(0), "Function M0.Fun02() As System.Int32") CheckSymbolInfoOnly(model, names(0), "Function M0.Fun02() As System.Int32") names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "INTT") Assert.Equal(1, names.Length) CheckTypeParameterCrefSymbolInfoAndTypeInfo(model, names(0), "INTT") names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "INTS") Assert.Equal(1, names.Length) CheckSymbolInfoOnly(model, names(0), "Sub OuterClass(Of X).INT(Of INTT).INTS(a As System.Int32)") End Sub <Fact()> Public Sub SemanticInfo_SquareBrackets() Dim compilation = CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System ''' <typeparam name="X"></typeparam> ''' <typeparam name="[X]"></typeparam> ''' <typeparamref name="X"></typeparamref> ''' <typeparamref name="[X]"></typeparamref> Public MustInherit Class OuterClass(Of X) ''' <typeparamref name="X"></typeparamref> ''' <typeparamref name="[X]"></typeparamref> ''' <typeparam name="t"></typeparam> ''' <typeparam name="[t]"></typeparam> ''' <typeparamref name="t"></typeparamref> ''' <typeparamref name="[t]"></typeparamref> ''' <param name="a"></param> ''' <param name="[a]"></param> ''' <paramref name="A"></paramref> ''' <paramref name="[A]"></paramref> Public Shared Sub S(Of T)(a As Integer) End Sub End Class ]]> </file> </compilation>, <errors></errors>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:OuterClass`1"> <typeparam name="X"></typeparam> <typeparam name="[X]"></typeparam> <typeparamref name="X"></typeparamref> <typeparamref name="[X]"></typeparamref> </member> <member name="M:OuterClass`1.S``1(System.Int32)"> <typeparamref name="X"></typeparamref> <typeparamref name="[X]"></typeparamref> <typeparam name="t"></typeparam> <typeparam name="[t]"></typeparam> <typeparamref name="t"></typeparamref> <typeparamref name="[t]"></typeparamref> <param name="a"></param> <param name="[a]"></param> <paramref name="A"></paramref> <paramref name="[A]"></paramref> </member> </members> </doc> ]]> </xml>) Dim tree As SyntaxTree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "X") Assert.Equal(6, names.Length) CheckSymbolInfoAndTypeInfo(model, DirectCast(names(0), ExpressionSyntax), "X") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(1), ExpressionSyntax), "X") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(2), ExpressionSyntax), "X") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(3), ExpressionSyntax), "X") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(4), ExpressionSyntax), "X") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(5), ExpressionSyntax), "X") names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "t") Assert.Equal(4, names.Length) CheckSymbolInfoAndTypeInfo(model, DirectCast(names(0), ExpressionSyntax), "T") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(1), ExpressionSyntax), "T") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(2), ExpressionSyntax), "T") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(3), ExpressionSyntax), "T") names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "a") Assert.Equal(2, names.Length) CheckSymbolInfoOnly(model, DirectCast(names(0), ExpressionSyntax), "a As System.Int32") CheckSymbolInfoOnly(model, DirectCast(names(1), ExpressionSyntax), "a As System.Int32") names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "A") Assert.Equal(2, names.Length) CheckSymbolInfoOnly(model, DirectCast(names(0), ExpressionSyntax), "a As System.Int32") CheckSymbolInfoOnly(model, DirectCast(names(1), ExpressionSyntax), "a As System.Int32") End Sub <Fact()> Public Sub SemanticModel_Accessibility() Dim compilation = CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Public Class OuterClass ''' <see cref="Other.S" /> ''' <see cref="c.n1.n2.t.C.c" /> Public Shared Sub Su(Of T)(a As Integer) End Sub End Class Public Class Other(Of OT) Private Shared Sub S(a As Integer) End Sub End Class Public Class C(Of T) Private Class N1 Private Class N2 Public Class T Public Class C ''' <see cref="t" /> Private C As T ''' <typeparamref name="t"/> Public Shared Sub XYZ(Of T)(a As Integer) End Sub End Class End Class End Class End Class End Class ]]> </file> </compilation>, Nothing) Dim tree As SyntaxTree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim text = tree.ToString() ' Other.S Dim names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "Other") Assert.Equal(1, names.Length) Dim symbols = CheckSymbolInfoAndTypeInfo(model, DirectCast(names(0), ExpressionSyntax), "Other(Of OT)") ' BREAK: dev11 includes "Sub Other(Of OT).S(a As System.Int32)" AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(text.IndexOf("Other.S""", StringComparison.Ordinal) + 5, container:=DirectCast(symbols(0), NamedTypeSymbol)), SymbolKind.Method), "Function System.Object.Equals(obj As System.Object) As System.Boolean", "Function System.Object.Equals(objA As System.Object, objB As System.Object) As System.Boolean", "Function System.Object.GetHashCode() As System.Int32", "Function System.Object.GetType() As System.Type", "Function System.Object.MemberwiseClone() As System.Object", "Function System.Object.ReferenceEquals(objA As System.Object, objB As System.Object) As System.Boolean", "Function System.Object.ToString() As System.String", "Sub System.Object.Finalize()") AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(text.IndexOf("Other.S""", StringComparison.Ordinal) + 5, container:=DirectCast(symbols(0), NamedTypeSymbol), name:="S"), SymbolKind.Method)) AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(text.IndexOf("Other.S""", StringComparison.Ordinal) + 5, container:=DirectCast(symbols(0), NamedTypeSymbol), name:="GetHashCode"), SymbolKind.Method), "Function System.Object.GetHashCode() As System.Int32") ' c.n1.n2.t.C names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "C") Assert.Equal(1, names.Length) ' BREAK: works in dev11. symbols = CheckSymbolInfoAndTypeInfo(model, DirectCast(names(0), ExpressionSyntax), "C(Of T).N1.N2.T.C") Assert.Equal(1, symbols.Length) ' "t" names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "t") Assert.Equal(3, names.Length) ' cref="t" symbols = CheckSymbolInfoAndTypeInfo(model, DirectCast(names(1), ExpressionSyntax), "C(Of T).N1.N2.T") Dim firstIndex = text.IndexOf("""t""", StringComparison.Ordinal) + 1 AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(firstIndex, name:="T"), SymbolKind.NamedType, SymbolKind.TypeParameter), "C(Of T).N1.N2.T") AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(firstIndex, name:="T", container:=symbols(0).ContainingType), SymbolKind.NamedType, SymbolKind.TypeParameter), "C(Of T).N1.N2.T") AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(firstIndex, name:="T", container:=symbols(0).ContainingType.ContainingType), SymbolKind.NamedType, SymbolKind.TypeParameter)) ' name="t" Dim secondSymbols = CheckSymbolInfoAndTypeInfo(model, DirectCast(names(2), ExpressionSyntax), "T") Dim secondIndex = text.IndexOf("""t""", firstIndex + 5, StringComparison.Ordinal) + 1 AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(secondIndex, name:="T"), SymbolKind.NamedType, SymbolKind.TypeParameter), "T") AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(secondIndex, name:="T", container:=symbols(0).ContainingType), SymbolKind.NamedType, SymbolKind.TypeParameter), "C(Of T).N1.N2.T") AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(secondIndex, name:="T", container:=secondSymbols(0).ContainingType), SymbolKind.NamedType, SymbolKind.TypeParameter)) End Sub <Fact> <WorkItem(4719, "https://github.com/dotnet/roslyn/issues/4719")> Public Sub CrefLookup() Dim source = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ ''' <summary> ''' See <see cref="C(Of U)" /> ''' </summary> Class C(Of T) Sub M() End Sub End Class Class Outer Private Class Inner End Class End Class ]]> </file> </compilation> Dim comp = CompileCheckDiagnosticsAndXmlDocument(source, <errors/>) Dim syntaxTree = comp.SyntaxTrees(0) Dim model = comp.GetSemanticModel(syntaxTree) Dim outer = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("Outer") Dim inner = outer.GetMember(Of NamedTypeSymbol)("Inner") Dim position = syntaxTree.ToString().IndexOf("(Of U)", StringComparison.Ordinal) Const bug4719IsFixed = False If bug4719IsFixed Then Assert.Equal(inner, model.LookupSymbols(position, outer, inner.Name).Single()) Else Assert.False(model.LookupSymbols(position, outer, inner.Name).Any()) End If End Sub <Fact()> Public Sub SemanticInfo_ErrorsInXmlGenerating_NoneInSemanticMode() Dim compilation = CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System ''' <summary> ''' <a>sss ''' </summary> Public Class TestClass Dim x As TestClass End Class ]]> </file> </compilation>, <errors> <![CDATA[ BC42304: XML documentation parse error: Element is missing an end tag. XML comment will be ignored. ''' <a>sss ~~~ BC42304: XML documentation parse error: '>' expected. XML comment will be ignored. ''' </summary> ~ BC42304: XML documentation parse error: Expected beginning '<' for an XML tag. XML comment will be ignored. ''' </summary> ~ BC42304: XML documentation parse error: XML name expected. XML comment will be ignored. ''' </summary> ~ ]]> </errors>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> </members> </doc> ]]> </xml>) Dim tree As SyntaxTree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "TestClass") Assert.Equal(1, names.Length) Dim symbols = CheckSymbolInfoAndTypeInfo(model, DirectCast(names(0), ExpressionSyntax), "TestClass") Assert.Equal(1, symbols.Length) Dim type = symbols(0) Assert.Equal(SymbolKind.NamedType, type.Kind) Dim docComment = type.GetDocumentationCommentXml() Assert.False(String.IsNullOrWhiteSpace(docComment)) Assert.Equal( <![CDATA[ <member name="T:TestClass"> <summary> <a>sss </summary> </member> ]]>.Value.Trim().Replace(vbLf, "").Replace(vbCr, ""), docComment.Trim().Replace(vbLf, "").Replace(vbCr, "")) End Sub <Fact()> Public Sub SemanticInfo_ErrorsInXmlGenerating_NoneInSemanticMode_PartialMethod() Dim compilation = CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Partial Public Class TestClass ''' <summary> Declaration </summary> Partial Private Sub PS() End Sub End Class Partial Public Class TestClass ''' <summary> Implementation Private Sub PS() PS() End Sub End Class ]]> </file> </compilation>, <errors> <![CDATA[ BC42304: XML documentation parse error: Element is missing an end tag. XML comment will be ignored. ''' <summary> Implementation ~~~~~~~~~ BC42304: XML documentation parse error: '>' expected. XML comment will be ignored. ''' <summary> Implementation ~ BC42304: XML documentation parse error: Expected beginning '<' for an XML tag. XML comment will be ignored. ''' <summary> Implementation ~ ]]> </errors>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="M:TestClass.PS"> <summary> Declaration </summary> </member> </members> </doc> ]]> </xml>) Dim tree As SyntaxTree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "PS") Assert.Equal(1, names.Length) Dim symbols = CheckSymbolInfoOnly(model, DirectCast(names(0), ExpressionSyntax), "Sub TestClass.PS()") Assert.Equal(1, symbols.Length) Dim method = symbols(0) Assert.Equal(SymbolKind.Method, method.Kind) Dim docComment = method.GetDocumentationCommentXml() Assert.False(String.IsNullOrWhiteSpace(docComment)) Assert.Equal("<member name=""M:TestClass.PS""> <summary> Implementation</member>".Trim(), docComment.Trim().Replace(vbLf, "").Replace(vbCr, "")) End Sub <Fact()> Public Sub Lookup_InsideParam() Dim compilation = CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Public Class OuterClass ''' <param name="a."/> ''' <param name="a"/> ''' <param name="[a]"/> ''' <typeparam name="[b]"/> ''' <see name="b"/> ''' <see cref="c"/> Public Shared Sub S(Of T)(a As Integer) End Sub End Class ]]> </file> </compilation>, Nothing) Dim tree As SyntaxTree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim text = tree.ToString() AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(text.IndexOf("""a.""", StringComparison.Ordinal) + 2), SymbolKind.Parameter), "a As System.Int32") AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(text.IndexOf("""a""", StringComparison.Ordinal) + 1), SymbolKind.Parameter), "a As System.Int32") AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(text.IndexOf("""[a]""", StringComparison.Ordinal) + 1), SymbolKind.Parameter), "a As System.Int32") AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(text.IndexOf("""[a]""", StringComparison.Ordinal) + 1), SymbolKind.TypeParameter)) AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(text.IndexOf("""[b]""", StringComparison.Ordinal) + 1), SymbolKind.Parameter)) AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(text.IndexOf("""b""", StringComparison.Ordinal) + 1), SymbolKind.Parameter)) AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(text.IndexOf("""c""", StringComparison.Ordinal) + 1), SymbolKind.Parameter)) End Sub <Fact()> Public Sub Lookup_InsideParamRef() Dim compilation = CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Public Class OuterClass ''' <paramref name="a."></paramref> ''' <paramref name="a"></paramref> ''' <paramref name="[a]"></paramref> ''' <typeparam name="[b]"/> ''' <see name="b"/> ''' <see cref="c"/> Public Shared Sub S(Of T)(a As Integer) End Sub End Class ]]> </file> </compilation>, Nothing) Dim tree As SyntaxTree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim text = tree.ToString() AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(text.IndexOf("""a.""", StringComparison.Ordinal) + 2), SymbolKind.Parameter), "a As System.Int32") AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(text.IndexOf("""a""", StringComparison.Ordinal) + 1), SymbolKind.Parameter), "a As System.Int32") AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(text.IndexOf("""[a]""", StringComparison.Ordinal) + 1), SymbolKind.Parameter), "a As System.Int32") AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(text.IndexOf("""[a]""", StringComparison.Ordinal) + 1), SymbolKind.TypeParameter)) AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(text.IndexOf("""[b]""", StringComparison.Ordinal) + 1), SymbolKind.Parameter)) AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(text.IndexOf("""b""", StringComparison.Ordinal) + 1), SymbolKind.Parameter)) AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(text.IndexOf("""c""", StringComparison.Ordinal) + 1), SymbolKind.Parameter)) End Sub <Fact()> Public Sub Lookup_InsideTypeParam() Dim compilation = CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Public Class OuterClass(Of X) ''' <typeparam name="a."></typeparam> ''' <typeparam name="a"></typeparam> ''' <typeparam name="[a]"></typeparam> ''' <param name="[b]"/> ''' <see name="b"/> ''' <see cref="c"/> Public Shared Sub S(Of T)(a As Integer) End Sub End Class ]]> </file> </compilation>, Nothing) Dim tree As SyntaxTree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim text = tree.ToString() AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(text.IndexOf("""a.""", StringComparison.Ordinal) + 2), SymbolKind.TypeParameter), "T", "X") AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(text.IndexOf("""a""", StringComparison.Ordinal) + 1), SymbolKind.TypeParameter), "T", "X") AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(text.IndexOf("""[a]""", StringComparison.Ordinal) + 1), SymbolKind.TypeParameter), "T", "X") AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(text.IndexOf("""[a]""", StringComparison.Ordinal) + 1), SymbolKind.Parameter)) AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(text.IndexOf("""[b]""", StringComparison.Ordinal) + 1), SymbolKind.TypeParameter), "X") AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(text.IndexOf("""b""", StringComparison.Ordinal) + 1), SymbolKind.TypeParameter), "X") AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(text.IndexOf("""b""", StringComparison.Ordinal) + 1), SymbolKind.TypeParameter), "X") End Sub <Fact()> Public Sub Lookup_InsideTypeParamRef() Dim compilation = CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Public Class OuterClass(Of X) ''' <typeparamref name="a."/> ''' <typeparamref name="a"/> ''' <typeparamref name="[a]"/> ''' <param name="[b]"/> ''' <see name="b"/> ''' <see cref="c"/> Public Shared Sub S(Of T)(a As Integer) End Sub End Class ]]> </file> </compilation>, Nothing) Dim tree As SyntaxTree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim text = tree.ToString() AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(text.IndexOf("""a.""", StringComparison.Ordinal) + 2), SymbolKind.TypeParameter), "T", "X") AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(text.IndexOf("""a""", StringComparison.Ordinal) + 1), SymbolKind.TypeParameter), "T", "X") AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(text.IndexOf("""[a]""", StringComparison.Ordinal) + 1), SymbolKind.TypeParameter), "T", "X") AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(text.IndexOf("""[a]""", StringComparison.Ordinal) + 1), SymbolKind.Parameter)) AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(text.IndexOf("""[b]""", StringComparison.Ordinal) + 1), SymbolKind.TypeParameter), "X") AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(text.IndexOf("""b""", StringComparison.Ordinal) + 1), SymbolKind.TypeParameter), "X") AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(text.IndexOf("""b""", StringComparison.Ordinal) + 1), SymbolKind.TypeParameter), "X") End Sub <Fact()> Public Sub Lookup_Cref() Dim compilation = CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System ''' <see cref="d"/> ''' <see cref="d."/> Public Class OuterClass(Of X) ''' <param name="[b]"/> ''' <see name="b"/> ''' <see cref="c"/> ''' <see cref="c."/> Public Shared Sub S(Of T)(a As Integer) End Sub End Class ]]> </file> </compilation>, Nothing) Dim tree As SyntaxTree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim text = tree.ToString() AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(text.IndexOf("""d.""", StringComparison.Ordinal) + 2), SymbolKind.TypeParameter, SymbolKind.Parameter), "X") AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(text.IndexOf("""d""", StringComparison.Ordinal) + 1), SymbolKind.TypeParameter, SymbolKind.Parameter), "X") AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(text.IndexOf("""[b]""", StringComparison.Ordinal) + 1), SymbolKind.TypeParameter, SymbolKind.Parameter), "a As System.Int32", "X") AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(text.IndexOf("""b""", StringComparison.Ordinal) + 1), SymbolKind.TypeParameter, SymbolKind.Parameter), "X") AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(text.IndexOf("""c""", StringComparison.Ordinal) + 1), SymbolKind.TypeParameter, SymbolKind.Parameter), "X") AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(text.IndexOf("""c.""", StringComparison.Ordinal) + 1), SymbolKind.TypeParameter, SymbolKind.Parameter), "X") End Sub <Fact()> Public Sub Lookup_ParameterAndFieldConflict() Dim compilation = CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Public Class OuterClass Public X As String ''' <param name="X" cref="X"></param> Public Sub SSS(x As Integer) End Sub End Class ]]> </file> </compilation>, Nothing) Dim tree As SyntaxTree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim text = tree.ToString() ' X Dim names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "X") Assert.Equal(2, names.Length) CheckSymbolInfoOnly(model, DirectCast(names(0), ExpressionSyntax), "x As System.Int32") CheckSymbolInfoOnly(model, DirectCast(names(1), ExpressionSyntax), "OuterClass.X As System.String") AssertLookupResult( FilterOfSymbolKindOnly( model.LookupSymbols( text.IndexOf("name=""X""", StringComparison.Ordinal) + 6), SymbolKind.Field, SymbolKind.Parameter), "x As System.Int32") AssertLookupResult( FilterOfSymbolKindOnly( model.LookupSymbols( text.IndexOf("cref=""X""", StringComparison.Ordinal) + 6), SymbolKind.Field, SymbolKind.Parameter), "OuterClass.X As System.String") End Sub <Fact()> Public Sub Lookup_TypeParameterAndFieldConflict() Dim compilation = CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Public Class OuterClass Public X As String ''' <typeparamref name="X" cref="X"/> Public Sub SSS(Of X)() End Sub End Class ]]> </file> </compilation>, Nothing) Dim tree As SyntaxTree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim text = tree.ToString() ' X Dim names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "X") Assert.Equal(2, names.Length) CheckSymbolInfoAndTypeInfo(model, DirectCast(names(0), ExpressionSyntax), "X") CheckSymbolInfoOnly(model, DirectCast(names(1), ExpressionSyntax), "OuterClass.X As System.String") AssertLookupResult( FilterOfSymbolKindOnly( model.LookupSymbols( text.IndexOf("name=""X""", StringComparison.Ordinal) + 6), SymbolKind.Field, SymbolKind.TypeParameter), "X") AssertLookupResult( FilterOfSymbolKindOnly( model.LookupSymbols( text.IndexOf("cref=""X""", StringComparison.Ordinal) + 6), SymbolKind.Field, SymbolKind.TypeParameter), "OuterClass.X As System.String") End Sub <Fact()> Public Sub Lookup_DoesNotDependOnContext() ' This test just proves that lookup result does not depend on ' context and returns, for example, fields in places where only ' type is expected Dim compilation = CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Public Class OuterClass(Of W) Public X As String Public Sub SSS() Dim a As OuterClass(Of Integer) = Nothing End Sub End Class ]]> </file> </compilation>, Nothing) Dim tree As SyntaxTree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim text = tree.ToString() AssertLookupResult( FilterOfSymbolKindOnly( model.LookupSymbols( text.IndexOf("Of Integer", StringComparison.Ordinal) + 3), SymbolKind.Field), "OuterClass(Of W).X As System.String") Dim symInteger = FilterOfSymbolKindOnly( model.LookupSymbols( text.IndexOf("Of Integer", StringComparison.Ordinal) + 3, name:="Int32"), SymbolKind.NamedType) AssertLookupResult(symInteger, "System.Int32") AssertLookupResult( FilterOfSymbolKindOnly( model.LookupSymbols( text.IndexOf("Of Integer", StringComparison.Ordinal) + 3, name:="Parse", container:=DirectCast(symInteger(0), NamedTypeSymbol)), SymbolKind.Method), "Function System.Int32.Parse(s As System.String) As System.Int32", "Function System.Int32.Parse(s As System.String, provider As System.IFormatProvider) As System.Int32", "Function System.Int32.Parse(s As System.String, style As System.Globalization.NumberStyles) As System.Int32", "Function System.Int32.Parse(s As System.String, style As System.Globalization.NumberStyles, provider As System.IFormatProvider) As System.Int32") End Sub <Fact(Skip:="https://github.com/dotnet/roslyn/issues/8807")> Public Sub Include_XPathNotFound_WRN_XMLDocInvalidXMLFragment() Dim xmlText = <root/> Dim xmlFile = Temp.CreateFile(extension:=".xml").WriteAllText(xmlText.ToString) Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Imports System.Collections.Generic ''' <summary> ''' <include file='{0}' path='//target' /> ''' </summary> Class C End Class ]]> </file> </compilation> CompileCheckDiagnosticsAndXmlDocument(FormatSourceXml(xmlSource, xmlFile), <error></error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:C"> <summary> <!--warning BC42320: Unable to include XML fragment '//target' of file '**FILE**'.--> </summary> </member> </members> </doc> ]]> </xml>, stringMapper:=Function(o) StringReplace(o, AsXmlCommentText(xmlFile), "**FILE**"), ensureEnglishUICulture:=True) End Sub <WorkItem(684184, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/684184")> <Fact(Skip:="https://github.com/dotnet/roslyn/issues/8807")> Public Sub Bug684184() Dim xmlText = <docs> <doc for="DataRepeaterLayoutStyles"> <summary></summary> </doc> </docs> Dim xmlFile = Temp.CreateFile(extension:=".xml").WriteAllText(xmlText.ToString) Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System ''' <include file='{0}' path='docs2/doc[@for="DataRepeater"]/*' /> Public Class Clazz End Class ]]> </file> </compilation> CompileCheckDiagnosticsAndXmlDocument(FormatSourceXml(xmlSource, xmlFile), <error></error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:Clazz"> <!--warning BC42320: Unable to include XML fragment 'docs2/doc[@for="DataRepeater"]/*' of file '**FILE**'.--> </member> </members> </doc> ]]> </xml>, stringMapper:=Function(o) StringReplace(o, AsXmlCommentText(xmlFile), "**FILE**"), ensureEnglishUICulture:=True) End Sub <Fact(Skip:="https://github.com/dotnet/roslyn/issues/8807")> Public Sub Include_FileNotFound_WRN_XMLDocBadFormedXML() Dim xmlText = <root/> Dim xmlFile = Temp.CreateFile(extension:=".xml").WriteAllText(xmlText.ToString) Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Imports System.Collections.Generic ''' <summary> ''' <include file='{0}5' path='//target' /> ''' </summary> Class C End Class ]]> </file> </compilation> CompileCheckDiagnosticsAndXmlDocument(FormatSourceXml(xmlSource, xmlFile), <error></error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:C"> <summary> <!--warning BC42321: Unable to include XML fragment '//target' of file '**FILE**5'. File not found.--> </summary> </member> </members> </doc> ]]> </xml>, stringMapper:=Function(o) StringReplace(o, AsXmlCommentText(xmlFile), "**FILE**"), ensureEnglishUICulture:=True) End Sub <Fact(Skip:="https://github.com/dotnet/roslyn/issues/8807")> Public Sub Include_IOError_WRN_XMLDocBadFormedXML() Dim xmlText = <root> <target>Included</target> </root> Dim xmlFile = Temp.CreateFile(extension:=".xml").WriteAllText(xmlText.ToString) Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Imports System.Collections.Generic ''' <summary> ''' <include file='{0}' path='//target' /> ''' </summary> Class C End Class ]]> </file> </compilation> Using _stream = New FileStream(xmlFile.Path, FileMode.Open, FileAccess.ReadWrite) CompileCheckDiagnosticsAndXmlDocument(FormatSourceXml(xmlSource, xmlFile), <error></error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:C"> <summary> <!--warning BC42321: Unable to include XML fragment '//target' of file '**FILE**'. The process cannot access the file '**FILE**' because it is being used by another process.--> </summary> </member> </members> </doc> ]]> </xml>, stringMapper:=Function(o) StringReplace(o, AsXmlCommentText(xmlFile), "**FILE**"), ensureEnglishUICulture:=True) End Using End Sub <Fact(Skip:="https://github.com/dotnet/roslyn/issues/8807")> Public Sub Include_XmlError_WRN_XMLDocBadFormedXML() Dim xmlText = <![CDATA[ <root> <target>Included<target> </root> ]]> Dim xmlFile = Temp.CreateFile(extension:=".xml").WriteAllText(xmlText.Value.ToString) Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Imports System.Collections.Generic ''' <summary> ''' <include file='{0}' path='//target' /> ''' </summary> Class C End Class ]]> </file> </compilation> CompileCheckDiagnosticsAndXmlDocument(FormatSourceXml(xmlSource, xmlFile), <error></error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:C"> <summary> <!--warning BC42320: Unable to include XML fragment '//target' of file '**FILE**'.--> </summary> </member> </members> </doc> ]]> </xml>, stringMapper:=Function(o) StringReplace(o, AsXmlCommentText(xmlFile), "**FILE**"), ensureEnglishUICulture:=True) End Sub <Fact(Skip:="https://github.com/dotnet/roslyn/issues/8807")> Public Sub Include_XDocument_WRN_XMLDocInvalidXMLFragment() Dim xmlText = <![CDATA[ <root> <target>Included</target> </root> ]]> Dim xmlFile = Temp.CreateFile(extension:=".xml").WriteAllText(xmlText.Value.ToString) Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Imports System.Collections.Generic ''' <summary> ''' <include file='{0}' path='//target/../..' /> ''' </summary> Class C End Class ]]> </file> </compilation> CompileCheckDiagnosticsAndXmlDocument(FormatSourceXml(xmlSource, xmlFile), <error></error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:C"> <summary> <!--warning BC42320: Unable to include XML fragment '//target/../..' of file '**FILE**'.--> </summary> </member> </members> </doc> ]]> </xml>, stringMapper:=Function(o) StringReplace(o, AsXmlCommentText(xmlFile), "**FILE**"), ensureEnglishUICulture:=True) End Sub <Fact> Public Sub Include_Cycle_WRN_XMLDocInvalidXMLFragment() Dim xmlText = <root> <target> <nested> <include file='{0}' path='//target'/> </nested> </target> </root> Dim xmlFile = Temp.CreateFile(extension:=".xml") xmlFile.WriteAllText(String.Format(xmlText.ToString, xmlFile.ToString)) Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Imports System.Collections.Generic ''' <summary> ''' <include file='{0}' path='//target' /> ''' </summary> Class C End Class ]]> </file> </compilation> CompileCheckDiagnosticsAndXmlDocument(FormatSourceXml(xmlSource, xmlFile), <error><%= $"BC42320: Unable to include XML fragment '{xmlFile.ToString()}' of file '//target'." %></error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:C"> <summary> <target> <nested> <target> <nested> <!--warning BC42320: Unable to include XML fragment '**FILE**' of file '//target'.--> </nested> </target> </nested> </target> </summary> </member> </members> </doc> ]]> </xml>, stringMapper:=Function(o) StringReplace(o, AsXmlCommentText(xmlFile), "**FILE**"), ensureEnglishUICulture:=True) End Sub <Fact(Skip:="https://github.com/dotnet/roslyn/issues/8807")> Public Sub Include_XPathError_WRN_XMLDocBadFormedXML() Dim xmlText = <![CDATA[ <root> <target>Included</target> </root> ]]> Dim xmlFile = Temp.CreateFile(extension:=".xml").WriteAllText(xmlText.Value.ToString) Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Imports System.Collections.Generic ''' <summary> ''' <include file='{0}' path='//target/%^' /> ''' </summary> Class C End Class ]]> </file> </compilation> CompileCheckDiagnosticsAndXmlDocument(FormatSourceXml(xmlSource, xmlFile), <error></error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:C"> <summary> <!--warning BC42320: Unable to include XML fragment '//target/%^' of file '**FILE**'.--> </summary> </member> </members> </doc> ]]> </xml>, stringMapper:=Function(o) StringReplace(o, AsXmlCommentText(xmlFile), "**FILE**"), ensureEnglishUICulture:=True) End Sub <Fact> Public Sub Include_CrefHandling() Dim xmlText = <![CDATA[ <root> <target> Included section <summary> See <see cref="Module0"/>. See <see cref="Module0."/>. See <see cref="Module0. "/>. See <see cref="Module0 "/>. </summary> <remarks></remarks> </target> <target> Included section <summary> See <see cref="T:A.B.C"/>. See <see cref="Module1"/>. See <see cref="Module0.' "/>. See <see cref="Module0. _ "/>. </summary> <remarks></remarks> </target> </root> ]]> Dim xmlFile = Temp.CreateFile(extension:=".xml").WriteAllText(xmlText.Value.ToString) Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Imports System.Collections.Generic ''' <summary> ''' <include file='{0}' path='//target' /> ''' </summary> Class Module0 End Class ]]> </file> </compilation> CompileCheckDiagnosticsAndXmlDocument(FormatSourceXml(xmlSource, xmlFile), <error> <![CDATA[ BC42309: XML comment has a tag with a 'cref' attribute 'Module0. _' that could not be resolved. BC42309: XML comment has a tag with a 'cref' attribute 'Module0.' that could not be resolved. BC42309: XML comment has a tag with a 'cref' attribute 'Module0.' that could not be resolved. BC42309: XML comment has a tag with a 'cref' attribute 'Module0.'' that could not be resolved. BC42309: XML comment has a tag with a 'cref' attribute 'Module1' that could not be resolved. ]]> </error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:Module0"> <summary> <target> Included section <summary> See <see cref="T:Module0" />. See <see cref="?:Module0." />. See <see cref="?:Module0. " />. See <see cref="T:Module0" />. </summary> <remarks /> </target><target> Included section <summary> See <see cref="T:A.B.C" />. See <see cref="?:Module1" />. See <see cref="?:Module0.' " />. See <see cref="?:Module0. _ " />. </summary> <remarks /> </target> </summary> </member> </members> </doc> ]]> </xml>) End Sub <Fact> Public Sub Include_ParamAndParamRefHandling() Dim xmlText = <![CDATA[ <root> <target> Included section <summary> See <param/>. See <param name="PARAMA"/>. See <param name="PARAMb"/>. See <param name="b"/>. See <param name="B' comment "/>. See <param name="Parama "/>. </summary> <remarks></remarks> </target> <target> Included section <summary> See <paramref/>. See <paramref name="PARAMA"/>. See <paramref name="PARAMb"/>. See <paramref name="b"/>. See <paramref name="B' comment "/>. See <paramref name="Parama "/>. </summary> <remarks></remarks> </target> </root> ]]> Dim xmlFile = Temp.CreateFile(extension:=".xml").WriteAllText(xmlText.Value.ToString) Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Imports System.Collections.Generic Class Module0 ''' <summary> ''' <include file='{0}' path='//target' /> ''' </summary> Sub S(paramA As String, B As Integer) End Sub End Class ]]> </file> </compilation> CompileCheckDiagnosticsAndXmlDocument(FormatSourceXml(xmlSource, xmlFile), <error> <![CDATA[ BC42307: XML comment parameter 'B' comment' does not match a parameter on the corresponding 'sub' statement. BC42307: XML comment parameter 'B' comment' does not match a parameter on the corresponding 'sub' statement. BC42307: XML comment parameter 'PARAMb' does not match a parameter on the corresponding 'sub' statement. BC42307: XML comment parameter 'PARAMb' does not match a parameter on the corresponding 'sub' statement. BC42308: XML comment parameter must have a 'name' attribute. BC42308: XML comment parameter must have a 'name' attribute. ]]> </error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="M:Module0.S(System.String,System.Int32)"> <summary> <target> Included section <summary> See <!--warning BC42308: XML comment parameter must have a 'name' attribute.--><param />. See <param name="PARAMA" />. See <!--warning BC42307: XML comment parameter 'PARAMb' does not match a parameter on the corresponding 'sub' statement.--><param name="PARAMb" />. See <param name="b" />. See <!--warning BC42307: XML comment parameter 'B' comment' does not match a parameter on the corresponding 'sub' statement.--><param name="B' comment " />. See <param name="Parama " />. </summary> <remarks /> </target><target> Included section <summary> See <!--warning BC42308: XML comment parameter must have a 'name' attribute.--><paramref />. See <paramref name="PARAMA" />. See <!--warning BC42307: XML comment parameter 'PARAMb' does not match a parameter on the corresponding 'sub' statement.--><paramref name="PARAMb" />. See <paramref name="b" />. See <!--warning BC42307: XML comment parameter 'B' comment' does not match a parameter on the corresponding 'sub' statement.--><paramref name="B' comment " />. See <paramref name="Parama " />. </summary> <remarks /> </target> </summary> </member> </members> </doc> ]]> </xml>, ensureEnglishUICulture:=True) End Sub <Fact> Public Sub Include_TypeParamAndTypeParamRefHandling() Dim xmlText = <![CDATA[ <root> <target> Included section <summary> See <typeparam/>. See <typeparam name="X"/>. See <typeparam name="Y"/>. See <typeparam name="XY"/>. See <typeparam name="Y' comment "/>. See <typeparam name="Y "/>. </summary> <remarks></remarks> </target> <target> Included section <summary> See <typeparamref/>. See <typeparamref name="X"/>. See <typeparamref name="Y"/>. See <typeparamref name="XY"/>. See <typeparamref name="Y' comment "/>. See <typeparamref name="Y "/>. </summary> <remarks></remarks> </target> </root> ]]> Dim xmlFile = Temp.CreateFile(extension:=".xml").WriteAllText(xmlText.Value.ToString) Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Imports System.Collections.Generic Class OuterClass(Of X) ''' <summary> ''' <include file='{0}' path='//target' /> ''' </summary> Class InnerClass(Of Y) End Class End Class ]]> </file> </compilation> CompileCheckDiagnosticsAndXmlDocument(FormatSourceXml(xmlSource, xmlFile), <error> <![CDATA[ BC42317: XML comment type parameter 'X' does not match a type parameter on the corresponding 'class' statement. BC42317: XML comment type parameter 'XY' does not match a type parameter on the corresponding 'class' statement. BC42317: XML comment type parameter 'XY' does not match a type parameter on the corresponding 'class' statement. BC42317: XML comment type parameter 'Y' comment' does not match a type parameter on the corresponding 'class' statement. BC42317: XML comment type parameter 'Y' comment' does not match a type parameter on the corresponding 'class' statement. BC42318: XML comment type parameter must have a 'name' attribute. BC42318: XML comment type parameter must have a 'name' attribute. ]]> </error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:OuterClass`1.InnerClass`1"> <summary> <target> Included section <summary> See <!--warning BC42318: XML comment type parameter must have a 'name' attribute.--><typeparam />. See <!--warning BC42317: XML comment type parameter 'X' does not match a type parameter on the corresponding 'class' statement.--><typeparam name="X" />. See <typeparam name="Y" />. See <!--warning BC42317: XML comment type parameter 'XY' does not match a type parameter on the corresponding 'class' statement.--><typeparam name="XY" />. See <!--warning BC42317: XML comment type parameter 'Y' comment' does not match a type parameter on the corresponding 'class' statement.--><typeparam name="Y' comment " />. See <typeparam name="Y " />. </summary> <remarks /> </target><target> Included section <summary> See <!--warning BC42318: XML comment type parameter must have a 'name' attribute.--><typeparamref />. See <typeparamref name="X" />. See <typeparamref name="Y" />. See <!--warning BC42317: XML comment type parameter 'XY' does not match a type parameter on the corresponding 'class' statement.--><typeparamref name="XY" />. See <!--warning BC42317: XML comment type parameter 'Y' comment' does not match a type parameter on the corresponding 'class' statement.--><typeparamref name="Y' comment " />. See <typeparamref name="Y " />. </summary> <remarks /> </target> </summary> </member> </members> </doc> ]]> </xml>, ensureEnglishUICulture:=True) End Sub <Fact> Public Sub Include_Exception() Dim xmlText = <![CDATA[ <root> <target> <exception cref="Exception"/> <exception cref=""/> <exception/> </target> <targeterror> <exception cref="Exception"/> </targeterror> </root> ]]> Dim xmlFile = Temp.CreateFile(extension:=".xml").WriteAllText(xmlText.Value.ToString) Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Imports System.Collections.Generic ''' <include file='{0}' path='//targeterror' /> Public Module Module0 End Module ''' <include file='{0}' path='//targeterror' /> Public Class Clazz(Of X) ''' <include file='{0}' path='//target' /> Public Sub X1() End Sub ''' <include file='{0}' path='//target' /> Public Event E As Action ''' <include file='{0}' path='//targeterror' /> Public F As Integer ''' <include file='{0}' path='//target' /> Public Property P As Integer ''' <include file='{0}' path='//targeterror' /> Public Delegate Function FDelegate(a As Integer) As String ''' <include file='{0}' path='//targeterror' /> Public Enum En : A : End Enum ''' <include file='{0}' path='//targeterror' /> Public Structure STR : End Structure ''' <include file='{0}' path='//target' /> Public ReadOnly Property A(x As String) As String Get Return x End Get End Property End Class ]]> </file> </compilation> CompileCheckDiagnosticsAndXmlDocument(FormatSourceXml(xmlSource, xmlFile), <error> <![CDATA[ BC42306: XML comment tag 'exception' is not permitted on a 'class' language element. BC42306: XML comment tag 'exception' is not permitted on a 'delegate' language element. BC42306: XML comment tag 'exception' is not permitted on a 'enum' language element. BC42306: XML comment tag 'exception' is not permitted on a 'module' language element. BC42306: XML comment tag 'exception' is not permitted on a 'structure' language element. BC42306: XML comment tag 'exception' is not permitted on a 'variable' language element. BC42309: XML comment has a tag with a 'cref' attribute '' that could not be resolved. BC42309: XML comment has a tag with a 'cref' attribute '' that could not be resolved. BC42309: XML comment has a tag with a 'cref' attribute '' that could not be resolved. BC42309: XML comment has a tag with a 'cref' attribute '' that could not be resolved. BC42319: XML comment exception must have a 'cref' attribute. BC42319: XML comment exception must have a 'cref' attribute. BC42319: XML comment exception must have a 'cref' attribute. BC42319: XML comment exception must have a 'cref' attribute. ]]> </error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:Module0"> <targeterror> <!--warning BC42306: XML comment tag 'exception' is not permitted on a 'module' language element.--><exception cref="Exception" /> </targeterror> </member> <member name="T:Clazz`1"> <targeterror> <!--warning BC42306: XML comment tag 'exception' is not permitted on a 'class' language element.--><exception cref="Exception" /> </targeterror> </member> <member name="M:Clazz`1.X1"> <target> <exception cref="T:System.Exception" /> <exception cref="?:" /> <!--warning BC42319: XML comment exception must have a 'cref' attribute.--><exception /> </target> </member> <member name="E:Clazz`1.E"> <target> <exception cref="T:System.Exception" /> <exception cref="?:" /> <!--warning BC42319: XML comment exception must have a 'cref' attribute.--><exception /> </target> </member> <member name="F:Clazz`1.F"> <targeterror> <!--warning BC42306: XML comment tag 'exception' is not permitted on a 'variable' language element.--><exception cref="Exception" /> </targeterror> </member> <member name="P:Clazz`1.P"> <target> <exception cref="T:System.Exception" /> <exception cref="?:" /> <!--warning BC42319: XML comment exception must have a 'cref' attribute.--><exception /> </target> </member> <member name="T:Clazz`1.FDelegate"> <targeterror> <!--warning BC42306: XML comment tag 'exception' is not permitted on a 'delegate' language element.--><exception cref="Exception" /> </targeterror> </member> <member name="T:Clazz`1.En"> <targeterror> <!--warning BC42306: XML comment tag 'exception' is not permitted on a 'enum' language element.--><exception cref="Exception" /> </targeterror> </member> <member name="T:Clazz`1.STR"> <targeterror> <!--warning BC42306: XML comment tag 'exception' is not permitted on a 'structure' language element.--><exception cref="Exception" /> </targeterror> </member> <member name="P:Clazz`1.A(System.String)"> <target> <exception cref="T:System.Exception" /> <exception cref="?:" /> <!--warning BC42319: XML comment exception must have a 'cref' attribute.--><exception /> </target> </member> </members> </doc> ]]> </xml>, ensureEnglishUICulture:=True) End Sub <Fact> Public Sub Include_Returns() Dim xmlText = <![CDATA[ <root> <target> <returns/> </target> </root> ]]> Dim xmlFile = Temp.CreateFile(extension:=".xml").WriteAllText(xmlText.Value.ToString) Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Imports System.Collections.Generic ''' <include file='{0}' path='//target' /> Public Class TestClass ''' <include file='{0}' path='//target' /> Public Enum EN : A : End Enum ''' <include file='{0}' path='//target' /> Public Delegate Sub DelSub(a As Integer) ''' <include file='{0}' path='//target' /> Public Delegate Function DelFunc(a As Integer) As Integer ''' <include file='{0}' path='//target' /> Public Shared Sub MSub(p3 As Integer, p4 As String) End Sub ''' <include file='{0}' path='//target' /> Public Shared Function MFunc(p3 As Integer, p4 As String) As Integer Return Nothing End Function ''' <include file='{0}' path='//target' /> Public Field As Integer ''' <include file='{0}' path='//target' /> WithEvents FieldWE As TestClass ''' <include file='{0}' path='//target' /> Public Declare Function DeclareFtn Lib "bar" () As Integer ''' <include file='{0}' path='//target' /> Public Declare Sub DeclareSub Lib "bar" () ''' <include file='{0}' path='//target' /> Public ReadOnly Property PReadOnly As Integer Get Return Nothing End Get End Property ''' <include file='{0}' path='//target' /> Public Property PReadWrite As Integer Get Return Nothing End Get Set(value As Integer) End Set End Property ''' <include file='{0}' path='//target' /> Public WriteOnly Property PWriteOnly As Integer Set(value As Integer) End Set End Property ''' <include file='{0}' path='//target' /> Public Event EE(p11 As String) End Class ]]> </file> </compilation> CompileCheckDiagnosticsAndXmlDocument(FormatSourceXml(xmlSource, xmlFile), <error> <![CDATA[ BC42306: XML comment tag 'returns' is not permitted on a 'class' language element. BC42306: XML comment tag 'returns' is not permitted on a 'delegate sub' language element. BC42306: XML comment tag 'returns' is not permitted on a 'enum' language element. BC42306: XML comment tag 'returns' is not permitted on a 'event' language element. BC42306: XML comment tag 'returns' is not permitted on a 'sub' language element. BC42306: XML comment tag 'returns' is not permitted on a 'variable' language element. BC42306: XML comment tag 'returns' is not permitted on a 'WithEvents variable' language element. BC42313: XML comment tag 'returns' is not permitted on a 'WriteOnly' Property. BC42315: XML comment tag 'returns' is not permitted on a 'declare sub' language element. ]]> </error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:TestClass"> <target> <!--warning BC42306: XML comment tag 'returns' is not permitted on a 'class' language element.--><returns /> </target> </member> <member name="T:TestClass.EN"> <target> <!--warning BC42306: XML comment tag 'returns' is not permitted on a 'enum' language element.--><returns /> </target> </member> <member name="T:TestClass.DelSub"> <target> <!--warning BC42306: XML comment tag 'returns' is not permitted on a 'delegate sub' language element.--><returns /> </target> </member> <member name="T:TestClass.DelFunc"> <target> <returns /> </target> </member> <member name="M:TestClass.MSub(System.Int32,System.String)"> <target> <!--warning BC42306: XML comment tag 'returns' is not permitted on a 'sub' language element.--><returns /> </target> </member> <member name="M:TestClass.MFunc(System.Int32,System.String)"> <target> <returns /> </target> </member> <member name="F:TestClass.Field"> <target> <!--warning BC42306: XML comment tag 'returns' is not permitted on a 'variable' language element.--><returns /> </target> </member> <member name="F:TestClass._FieldWE"> <target> <!--warning BC42306: XML comment tag 'returns' is not permitted on a 'WithEvents variable' language element.--><returns /> </target> </member> <member name="M:TestClass.DeclareFtn"> <target> <returns /> </target> </member> <member name="M:TestClass.DeclareSub"> <target> <!--warning BC42315: XML comment tag 'returns' is not permitted on a 'declare sub' language element.--><returns /> </target> </member> <member name="P:TestClass.PReadOnly"> <target> <returns /> </target> </member> <member name="P:TestClass.PReadWrite"> <target> <returns /> </target> </member> <member name="P:TestClass.PWriteOnly"> <target> <!--warning BC42313: XML comment tag 'returns' is not permitted on a 'WriteOnly' Property.--><returns /> </target> </member> <member name="E:TestClass.EE"> <target> <!--warning BC42306: XML comment tag 'returns' is not permitted on a 'event' language element.--><returns /> </target> </member> </members> </doc> ]]> </xml>, ensureEnglishUICulture:=True) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:="https://github.com/dotnet/roslyn/issues/29531")> Public Sub Include_Value() Dim xmlText = <![CDATA[ <root> <target> <value/> </target> </root> ]]> Dim xmlFile = Temp.CreateFile(extension:=".xml").WriteAllText(xmlText.Value.ToString) Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Imports System.Collections.Generic ''' <include file='{0}' path='//target' /> Public Class TestClass ''' <include file='{0}' path='//target' /> Public Enum EN : A : End Enum ''' <include file='{0}' path='//target' /> Public Structure STR : End Structure ''' <include file='{0}' path='//target' /> Public Interface INTERF : End Interface ''' <include file='{0}' path='//target' /> Public Delegate Sub DelSub(a As Integer) ''' <include file='{0}' path='//target' /> Public Delegate Function DelFunc(a As Integer) As Integer ''' <include file='{0}' path='//target' /> Public Shared Sub MSub(p3 As Integer, p4 As String) End Sub ''' <include file='{0}' path='//target' /> Public Shared Function MFunc(p3 As Integer, p4 As String) As Integer Return Nothing End Function ''' <include file='{0}' path='//target' /> Public Declare Function DeclareFtn Lib "bar" (p3 As Integer) As Integer ''' <include file='{0}' path='//target' /> Public Field As Integer ''' <include file='{0}' path='//target' /> Public WriteOnly Property PWriteOnly(p As Integer) As Integer Set(value As Integer) End Set End Property ''' <include file='{0}' path='//target' /> Public Property PReadWrite As Integer ''' <include file='{0}' path='//target' /> Public Event EVE(ppp As Integer) End Class ]]> </file> </compilation> CompileCheckDiagnosticsAndXmlDocument(FormatSourceXml(xmlSource, xmlFile), <error> <![CDATA[ BC42306: XML comment tag 'value' is not permitted on a 'class' language element. BC42306: XML comment tag 'value' is not permitted on a 'declare' language element. BC42306: XML comment tag 'value' is not permitted on a 'delegate' language element. BC42306: XML comment tag 'value' is not permitted on a 'delegate sub' language element. BC42306: XML comment tag 'value' is not permitted on a 'enum' language element. BC42306: XML comment tag 'value' is not permitted on a 'event' language element. BC42306: XML comment tag 'value' is not permitted on a 'function' language element. BC42306: XML comment tag 'value' is not permitted on a 'interface' language element. BC42306: XML comment tag 'value' is not permitted on a 'structure' language element. BC42306: XML comment tag 'value' is not permitted on a 'sub' language element. BC42306: XML comment tag 'value' is not permitted on a 'variable' language element. ]]> </error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:TestClass"> <target> <!--warning BC42306: XML comment tag 'value' is not permitted on a 'class' language element.--><value /> </target> </member> <member name="T:TestClass.EN"> <target> <!--warning BC42306: XML comment tag 'value' is not permitted on a 'enum' language element.--><value /> </target> </member> <member name="T:TestClass.STR"> <target> <!--warning BC42306: XML comment tag 'value' is not permitted on a 'structure' language element.--><value /> </target> </member> <member name="T:TestClass.INTERF"> <target> <!--warning BC42306: XML comment tag 'value' is not permitted on a 'interface' language element.--><value /> </target> </member> <member name="T:TestClass.DelSub"> <target> <!--warning BC42306: XML comment tag 'value' is not permitted on a 'delegate sub' language element.--><value /> </target> </member> <member name="T:TestClass.DelFunc"> <target> <!--warning BC42306: XML comment tag 'value' is not permitted on a 'delegate' language element.--><value /> </target> </member> <member name="M:TestClass.MSub(System.Int32,System.String)"> <target> <!--warning BC42306: XML comment tag 'value' is not permitted on a 'sub' language element.--><value /> </target> </member> <member name="M:TestClass.MFunc(System.Int32,System.String)"> <target> <!--warning BC42306: XML comment tag 'value' is not permitted on a 'function' language element.--><value /> </target> </member> <member name="M:TestClass.DeclareFtn(System.Int32)"> <target> <!--warning BC42306: XML comment tag 'value' is not permitted on a 'declare' language element.--><value /> </target> </member> <member name="F:TestClass.Field"> <target> <!--warning BC42306: XML comment tag 'value' is not permitted on a 'variable' language element.--><value /> </target> </member> <member name="P:TestClass.PWriteOnly(System.Int32)"> <target> <value /> </target> </member> <member name="P:TestClass.PReadWrite"> <target> <value /> </target> </member> <member name="E:TestClass.EVE"> <target> <!--warning BC42306: XML comment tag 'value' is not permitted on a 'event' language element.--><value /> </target> </member> </members> </doc> ]]> </xml>, ensureEnglishUICulture:=True) End Sub <Fact> Public Sub Include_ParamAndParamRef() Dim xmlText = <![CDATA[ <root> <target> <param name="P9"/> <paramref name="P9"/> </target> </root> ]]> Dim xmlFile = Temp.CreateFile(extension:=".xml").WriteAllText(xmlText.Value.ToString) Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Imports System.Collections.Generic ''' <include file='{0}' path='//target' /> Public Class TestClass ''' <include file='{0}' path='//target' /> Public Shared Sub M(P9 As Integer, p4 As String) Dim a As TestClass = Nothing End Sub ''' <include file='{0}' path='//target' /> Public F As Integer ''' <include file='{0}' path='//target' /> Public Property P As Integer ''' <include file='{0}' path='//target' /> Public ReadOnly Property P(P9 As String) As Integer Get Return Nothing End Get End Property ''' <include file='{0}' path='//target' /> Public Event EE(P9 As String) End Class ]]> </file> </compilation> CompileCheckDiagnosticsAndXmlDocument(FormatSourceXml(xmlSource, xmlFile), <error> <![CDATA[ BC42306: XML comment tag 'param' is not permitted on a 'class' language element. BC42306: XML comment tag 'param' is not permitted on a 'variable' language element. BC42306: XML comment tag 'paramref' is not permitted on a 'class' language element. BC42306: XML comment tag 'paramref' is not permitted on a 'variable' language element. BC42307: XML comment parameter 'P9' does not match a parameter on the corresponding 'property' statement. BC42307: XML comment parameter 'P9' does not match a parameter on the corresponding 'property' statement. ]]> </error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:TestClass"> <target> <!--warning BC42306: XML comment tag 'param' is not permitted on a 'class' language element.--><param name="P9" /> <!--warning BC42306: XML comment tag 'paramref' is not permitted on a 'class' language element.--><paramref name="P9" /> </target> </member> <member name="M:TestClass.M(System.Int32,System.String)"> <target> <param name="P9" /> <paramref name="P9" /> </target> </member> <member name="F:TestClass.F"> <target> <!--warning BC42306: XML comment tag 'param' is not permitted on a 'variable' language element.--><param name="P9" /> <!--warning BC42306: XML comment tag 'paramref' is not permitted on a 'variable' language element.--><paramref name="P9" /> </target> </member> <member name="P:TestClass.P"> <target> <!--warning BC42307: XML comment parameter 'P9' does not match a parameter on the corresponding 'property' statement.--><param name="P9" /> <!--warning BC42307: XML comment parameter 'P9' does not match a parameter on the corresponding 'property' statement.--><paramref name="P9" /> </target> </member> <member name="P:TestClass.P(System.String)"> <target> <param name="P9" /> <paramref name="P9" /> </target> </member> <member name="E:TestClass.EE"> <target> <param name="P9" /> <paramref name="P9" /> </target> </member> </members> </doc> ]]> </xml>, ensureEnglishUICulture:=True) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:="https://github.com/dotnet/roslyn/issues/29531")> Public Sub Include_TypeParamAndTypeParamRef() Dim xmlText = <![CDATA[ <root> <target> <typeparam name="P9"/> <typeparamref name="P9"/> </target> </root> ]]> Dim xmlFile = Temp.CreateFile(extension:=".xml").WriteAllText(xmlText.Value.ToString) Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Imports System.Collections.Generic ''' <include file='{0}' path='//target' /> Public Module Module0 ''' <include file='{0}' path='//target' /> Public Declare Function DeclareFtn Lib "bar" (p3 As Integer) As Integer End Module ''' <include file='{0}' path='//target' /> Public Class TestClass(Of P9) ''' <include file='{0}' path='//target' /> Public Enum EN : A : End Enum ''' <include file='{0}' path='//target' /> Public Structure STR(Of X) : End Structure ''' <include file='{0}' path='//target' /> Public Interface INTERF(Of X, Y) : End Interface ''' <include file='{0}' path='//target' /> Public Delegate Sub DelSub(Of W)(a As Integer) ''' <include file='{0}' path='//target' /> Public Delegate Function DelFunc(Of W)(a As Integer) As Integer ''' <include file='{0}' path='//target' /> Public Shared Sub MSub(Of TT)(p3 As Integer, p4 As String) End Sub ''' <include file='{0}' path='//target' /> Public Shared Function MFunc(p3 As Integer, p4 As String) As Integer Return Nothing End Function ''' <include file='{0}' path='//target' /> Public Field As Integer ''' <include file='{0}' path='//target' /> Public WriteOnly Property PWriteOnly(p As Integer) As Integer Set(value As Integer) End Set End Property ''' <include file='{0}' path='//target' /> Public Property PReadWrite As Integer ''' <include file='{0}' path='//target' /> Public Event EVE(ppp As Integer) End Class ]]> </file> </compilation> CompileCheckDiagnosticsAndXmlDocument(FormatSourceXml(xmlSource, xmlFile), <error> <![CDATA[ BC42306: XML comment tag 'typeparam' is not permitted on a 'declare' language element. BC42306: XML comment tag 'typeparam' is not permitted on a 'enum' language element. BC42306: XML comment tag 'typeparam' is not permitted on a 'event' language element. BC42306: XML comment tag 'typeparam' is not permitted on a 'module' language element. BC42306: XML comment tag 'typeparam' is not permitted on a 'property' language element. BC42306: XML comment tag 'typeparam' is not permitted on a 'property' language element. BC42306: XML comment tag 'typeparam' is not permitted on a 'variable' language element. BC42306: XML comment tag 'typeparamref' is not permitted on a 'module' language element. BC42317: XML comment type parameter 'P9' does not match a type parameter on the corresponding 'declare' statement. BC42317: XML comment type parameter 'P9' does not match a type parameter on the corresponding 'delegate' statement. BC42317: XML comment type parameter 'P9' does not match a type parameter on the corresponding 'delegate sub' statement. BC42317: XML comment type parameter 'P9' does not match a type parameter on the corresponding 'function' statement. BC42317: XML comment type parameter 'P9' does not match a type parameter on the corresponding 'interface' statement. BC42317: XML comment type parameter 'P9' does not match a type parameter on the corresponding 'structure' statement. BC42317: XML comment type parameter 'P9' does not match a type parameter on the corresponding 'sub' statement. ]]> </error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:Module0"> <target> <!--warning BC42306: XML comment tag 'typeparam' is not permitted on a 'module' language element.--><typeparam name="P9" /> <!--warning BC42306: XML comment tag 'typeparamref' is not permitted on a 'module' language element.--><typeparamref name="P9" /> </target> </member> <member name="M:Module0.DeclareFtn(System.Int32)"> <target> <!--warning BC42306: XML comment tag 'typeparam' is not permitted on a 'declare' language element.--><typeparam name="P9" /> <!--warning BC42317: XML comment type parameter 'P9' does not match a type parameter on the corresponding 'declare' statement.--><typeparamref name="P9" /> </target> </member> <member name="T:TestClass`1"> <target> <typeparam name="P9" /> <typeparamref name="P9" /> </target> </member> <member name="T:TestClass`1.EN"> <target> <!--warning BC42306: XML comment tag 'typeparam' is not permitted on a 'enum' language element.--><typeparam name="P9" /> <typeparamref name="P9" /> </target> </member> <member name="T:TestClass`1.STR`1"> <target> <!--warning BC42317: XML comment type parameter 'P9' does not match a type parameter on the corresponding 'structure' statement.--><typeparam name="P9" /> <typeparamref name="P9" /> </target> </member> <member name="T:TestClass`1.INTERF`2"> <target> <!--warning BC42317: XML comment type parameter 'P9' does not match a type parameter on the corresponding 'interface' statement.--><typeparam name="P9" /> <typeparamref name="P9" /> </target> </member> <member name="T:TestClass`1.DelSub`1"> <target> <!--warning BC42317: XML comment type parameter 'P9' does not match a type parameter on the corresponding 'delegate sub' statement.--><typeparam name="P9" /> <typeparamref name="P9" /> </target> </member> <member name="T:TestClass`1.DelFunc`1"> <target> <!--warning BC42317: XML comment type parameter 'P9' does not match a type parameter on the corresponding 'delegate' statement.--><typeparam name="P9" /> <typeparamref name="P9" /> </target> </member> <member name="M:TestClass`1.MSub``1(System.Int32,System.String)"> <target> <!--warning BC42317: XML comment type parameter 'P9' does not match a type parameter on the corresponding 'sub' statement.--><typeparam name="P9" /> <typeparamref name="P9" /> </target> </member> <member name="M:TestClass`1.MFunc(System.Int32,System.String)"> <target> <!--warning BC42317: XML comment type parameter 'P9' does not match a type parameter on the corresponding 'function' statement.--><typeparam name="P9" /> <typeparamref name="P9" /> </target> </member> <member name="F:TestClass`1.Field"> <target> <!--warning BC42306: XML comment tag 'typeparam' is not permitted on a 'variable' language element.--><typeparam name="P9" /> <typeparamref name="P9" /> </target> </member> <member name="P:TestClass`1.PWriteOnly(System.Int32)"> <target> <!--warning BC42306: XML comment tag 'typeparam' is not permitted on a 'property' language element.--><typeparam name="P9" /> <typeparamref name="P9" /> </target> </member> <member name="P:TestClass`1.PReadWrite"> <target> <!--warning BC42306: XML comment tag 'typeparam' is not permitted on a 'property' language element.--><typeparam name="P9" /> <typeparamref name="P9" /> </target> </member> <member name="E:TestClass`1.EVE"> <target> <!--warning BC42306: XML comment tag 'typeparam' is not permitted on a 'event' language element.--><typeparam name="P9" /> <typeparamref name="P9" /> </target> </member> </members> </doc> ]]> </xml>, ensureEnglishUICulture:=True) End Sub <Fact> Public Sub Include_TypeParameterCref() Dim xmlText = <![CDATA[ <root> <target> <see cref="P9"/> </target> </root> ]]> Dim xmlFile = Temp.CreateFile(extension:=".xml").WriteAllText(xmlText.Value.ToString) Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Imports System.Collections.Generic ''' <include file='{0}' path='//target' /> Public Module Module0 ''' <include file='{0}' path='//target' /> Public Declare Function DeclareFtn Lib "bar" (p3 As Integer) As Integer End Module ''' <include file='{0}' path='//target' /> Public Class TestClass(Of P9) ''' <include file='{0}' path='//target' /> Public Enum EN : A : End Enum ''' <include file='{0}' path='//target' /> Public Structure STR(Of X) : End Structure ''' <include file='{0}' path='//target' /> Public Interface INTERF(Of X, Y) : End Interface ''' <include file='{0}' path='//target' /> Public Delegate Sub DelSub(Of W)(a As Integer) ''' <include file='{0}' path='//target' /> Public Delegate Function DelFunc(Of W)(a As Integer) As Integer ''' <include file='{0}' path='//target' /> Public Shared Sub MSub(Of TT)(p3 As Integer, p4 As String) End Sub ''' <include file='{0}' path='//target' /> Public Shared Function MFunc(p3 As Integer, p4 As String) As Integer Return Nothing End Function ''' <include file='{0}' path='//target' /> Public Field As Integer ''' <include file='{0}' path='//target' /> Public WriteOnly Property PWriteOnly(p As Integer) As Integer Set(value As Integer) End Set End Property ''' <include file='{0}' path='//target' /> Public Property PReadWrite As Integer ''' <include file='{0}' path='//target' /> Public Event EVE(ppp As Integer) End Class ]]> </file> </compilation> CompileCheckDiagnosticsAndXmlDocument(FormatSourceXml(xmlSource, xmlFile), <error> <![CDATA[ BC42309: XML comment has a tag with a 'cref' attribute 'P9' that could not be resolved. BC42309: XML comment has a tag with a 'cref' attribute 'P9' that could not be resolved. BC42375: XML comment has a tag with a 'cref' attribute 'P9' that bound to a type parameter. Use the <typeparamref> tag instead. BC42375: XML comment has a tag with a 'cref' attribute 'P9' that bound to a type parameter. Use the <typeparamref> tag instead. BC42375: XML comment has a tag with a 'cref' attribute 'P9' that bound to a type parameter. Use the <typeparamref> tag instead. BC42375: XML comment has a tag with a 'cref' attribute 'P9' that bound to a type parameter. Use the <typeparamref> tag instead. BC42375: XML comment has a tag with a 'cref' attribute 'P9' that bound to a type parameter. Use the <typeparamref> tag instead. BC42375: XML comment has a tag with a 'cref' attribute 'P9' that bound to a type parameter. Use the <typeparamref> tag instead. BC42375: XML comment has a tag with a 'cref' attribute 'P9' that bound to a type parameter. Use the <typeparamref> tag instead. BC42375: XML comment has a tag with a 'cref' attribute 'P9' that bound to a type parameter. Use the <typeparamref> tag instead. BC42375: XML comment has a tag with a 'cref' attribute 'P9' that bound to a type parameter. Use the <typeparamref> tag instead. BC42375: XML comment has a tag with a 'cref' attribute 'P9' that bound to a type parameter. Use the <typeparamref> tag instead. BC42375: XML comment has a tag with a 'cref' attribute 'P9' that bound to a type parameter. Use the <typeparamref> tag instead. BC42375: XML comment has a tag with a 'cref' attribute 'P9' that bound to a type parameter. Use the <typeparamref> tag instead. ]]> </error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:Module0"> <target> <see cref="?:P9" /> </target> </member> <member name="M:Module0.DeclareFtn(System.Int32)"> <target> <see cref="?:P9" /> </target> </member> <member name="T:TestClass`1"> <target> <see cref="?:P9" /> </target> </member> <member name="T:TestClass`1.EN"> <target> <see cref="?:P9" /> </target> </member> <member name="T:TestClass`1.STR`1"> <target> <see cref="?:P9" /> </target> </member> <member name="T:TestClass`1.INTERF`2"> <target> <see cref="?:P9" /> </target> </member> <member name="T:TestClass`1.DelSub`1"> <target> <see cref="?:P9" /> </target> </member> <member name="T:TestClass`1.DelFunc`1"> <target> <see cref="?:P9" /> </target> </member> <member name="M:TestClass`1.MSub``1(System.Int32,System.String)"> <target> <see cref="?:P9" /> </target> </member> <member name="M:TestClass`1.MFunc(System.Int32,System.String)"> <target> <see cref="?:P9" /> </target> </member> <member name="F:TestClass`1.Field"> <target> <see cref="?:P9" /> </target> </member> <member name="P:TestClass`1.PWriteOnly(System.Int32)"> <target> <see cref="?:P9" /> </target> </member> <member name="P:TestClass`1.PReadWrite"> <target> <see cref="?:P9" /> </target> </member> <member name="E:TestClass`1.EVE"> <target> <see cref="?:P9" /> </target> </member> </members> </doc> ]]> </xml>) End Sub <Fact> Private Sub ExtendedCref_IdentifierInName_IdentifierAndGenericInSignature() Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Imports System.Collections.Generic Public Structure TestStruct ''' <see cref="T(List(Of Int32), TestStruct)"/> Public Shared field As Integer Sub T(p As List(Of Int32), i as TestStruct) End Sub End Structure ]]> </file> </compilation> Dim xmlDoc = <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="F:TestStruct.field"> <see cref="M:TestStruct.T(System.Collections.Generic.List{System.Int32},TestStruct)"/> </member> </members> </doc> ]]> </xml> Dim compilation = CompileCheckDiagnosticsAndXmlDocument(xmlSource, <errors></errors>, xmlDoc) Dim model = compilation.GetSemanticModel(compilation.SyntaxTrees(0)) Dim crefNodes = CrefFinder.FindAllCrefs(compilation.SyntaxTrees(0)) Assert.Equal(1, crefNodes.Count) Dim info = model.GetSymbolInfo(crefNodes(0)) Assert.NotNull(info.Symbol) Assert.Equal("Sub TestStruct.T(p As System.Collections.Generic.List(Of System.Int32), i As TestStruct)", info.Symbol.ToTestDisplayString()) CheckAllNames(model, crefNodes(0), New NameSyntaxInfo("T", {"Sub TestStruct.T(p As System.Collections.Generic.List(Of System.Int32), i As TestStruct)"}, {}), New NameSyntaxInfo("List(Of Int32)", {"System.Collections.Generic.List(Of System.Int32)"}, {"System.Collections.Generic.List(Of System.Int32)"}), New NameSyntaxInfo("Int32", {"System.Int32"}, {"System.Int32"}), New NameSyntaxInfo("TestStruct", {"TestStruct"}, {"TestStruct"})) End Sub <WorkItem(703587, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/703587")> <Fact()> Private Sub ObjectMemberViaInterfaceA() Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System ''' Comment Public Class C Implements IEquatable(Of C) ''' Implements <see cref="IEquatable(Of T).Equals"/>. ''' Implements <see cref="IEquatable(Of T).GetHashCode"/>. ''' Implements <see cref="IEquatable(Of T).Equals(T)"/>. ''' Implements <see cref="IEquatable(Of T).GetHashCode()"/>. Public Function IEquals(c As C) As Boolean Implements IEquatable(Of C).Equals Return False End Function End Class ]]> </file> </compilation> Dim xmlDoc = <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:C"> Comment </member> <member name="M:C.IEquals(C)"> Implements <see cref="M:System.IEquatable`1.Equals(`0)"/>. Implements <see cref="!:IEquatable(Of T).GetHashCode"/>. Implements <see cref="M:System.IEquatable`1.Equals(`0)"/>. Implements <see cref="!:IEquatable(Of T).GetHashCode()"/>. </member> </members> </doc> ]]> </xml> CompileCheckDiagnosticsAndXmlDocument(xmlSource, <errors> <![CDATA[ BC42309: XML comment has a tag with a 'cref' attribute 'IEquatable(Of T).GetHashCode' that could not be resolved. ''' Implements <see cref="IEquatable(Of T).GetHashCode"/>. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'IEquatable(Of T).GetHashCode()' that could not be resolved. ''' Implements <see cref="IEquatable(Of T).GetHashCode()"/>. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]> </errors>, xmlDoc) End Sub <WorkItem(703587, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/703587")> <Fact()> Private Sub ObjectMemberViaInterfaceB() Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System ''' Comment Public Interface INT Inherits IEquatable(Of Integer) ''' Implements <see cref="Equals"/>. ''' Implements <see cref="IEquals(Integer)"/>. ''' Implements <see cref="Equals(Object)"/>. ''' Implements <see cref="Equals(Integer)"/>. ''' Implements <see cref="GetHashCode"/>. ''' Implements <see cref="GetHashCode()"/>. Function IEquals(c As Integer) As Boolean End Interface ]]> </file> </compilation> Dim xmlDoc = <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:INT"> Comment </member> <member name="M:INT.IEquals(System.Int32)"> Implements <see cref="M:System.IEquatable`1.Equals(`0)"/>. Implements <see cref="M:INT.IEquals(System.Int32)"/>. Implements <see cref="!:Equals(Object)"/>. Implements <see cref="M:System.IEquatable`1.Equals(`0)"/>. Implements <see cref="!:GetHashCode"/>. Implements <see cref="!:GetHashCode()"/>. </member> </members> </doc> ]]> </xml> CompileCheckDiagnosticsAndXmlDocument(xmlSource, <errors> <![CDATA[ BC42309: XML comment has a tag with a 'cref' attribute 'Equals(Object)' that could not be resolved. ''' Implements <see cref="Equals(Object)"/>. ~~~~~~~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'GetHashCode' that could not be resolved. ''' Implements <see cref="GetHashCode"/>. ~~~~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'GetHashCode()' that could not be resolved. ''' Implements <see cref="GetHashCode()"/>. ~~~~~~~~~~~~~~~~~~~~ ]]> </errors>, xmlDoc) End Sub <Fact> Private Sub ExtendedCref_GenericInName_IdentifierInSignature() Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Public Structure TestStruct ''' <see cref="T(Of T)(T, TestStruct)"/> Public Shared field As Integer Sub T(Of T)(p As T, i as TestStruct) End Sub End Structure ]]> </file> </compilation> Dim xmlDoc = <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="F:TestStruct.field"> <see cref="M:TestStruct.T``1(``0,TestStruct)"/> </member> </members> </doc> ]]> </xml> Dim compilation = CompileCheckDiagnosticsAndXmlDocument(xmlSource, <errors></errors>, xmlDoc) Dim model = compilation.GetSemanticModel(compilation.SyntaxTrees(0)) Dim crefNodes = CrefFinder.FindAllCrefs(compilation.SyntaxTrees(0)) Assert.Equal(1, crefNodes.Count) Dim info = model.GetSymbolInfo(crefNodes(0)) Assert.NotNull(info.Symbol) Assert.Equal("Sub TestStruct.T(Of T)(p As T, i As TestStruct)", info.Symbol.ToTestDisplayString()) CheckAllNames(model, crefNodes(0), New NameSyntaxInfo("T(Of T)", {"Sub TestStruct.T(Of T)(p As T, i As TestStruct)"}, {}), New NameSyntaxInfo("T", {"T"}, {"T"}), New NameSyntaxInfo("T", {"T"}, {"T"}), New NameSyntaxInfo("TestStruct", {"TestStruct"}, {"TestStruct"})) End Sub <Fact> Private Sub ExtendedCref_GenericInName_GlobalInSignature() Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Public Structure TestStruct ''' <see cref="T(Of T)(T, Global.TestStruct)"/> Public Shared field As Integer Sub T(Of T)(p As T, i as TestStruct) End Sub End Structure ]]> </file> </compilation> Dim xmlDoc = <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="F:TestStruct.field"> <see cref="M:TestStruct.T``1(``0,TestStruct)"/> </member> </members> </doc> ]]> </xml> Dim compilation = CompileCheckDiagnosticsAndXmlDocument(xmlSource, <errors></errors>, xmlDoc) Dim model = compilation.GetSemanticModel(compilation.SyntaxTrees(0)) Dim crefNodes = CrefFinder.FindAllCrefs(compilation.SyntaxTrees(0)) Assert.Equal(1, crefNodes.Count) Dim info = model.GetSymbolInfo(crefNodes(0)) Assert.NotNull(info.Symbol) Assert.Equal("Sub TestStruct.T(Of T)(p As T, i As TestStruct)", info.Symbol.ToTestDisplayString()) CheckAllNames(model, crefNodes(0), New NameSyntaxInfo("T(Of T)", {"Sub TestStruct.T(Of T)(p As T, i As TestStruct)"}, {}), New NameSyntaxInfo("T", {"T"}, {"T"}), New NameSyntaxInfo("T", {"T"}, {"T"}), New NameSyntaxInfo("Global.TestStruct", {"TestStruct"}, {"TestStruct"}), New NameSyntaxInfo("Global", {"Global"}, {}), New NameSyntaxInfo("TestStruct", {"TestStruct"}, {"TestStruct"})) End Sub <Fact> Private Sub ExtendedCref_GlobalAndQualifiedInName_TypeParamInSignature() Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Public Structure TestStruct ''' <see cref="Global.TestStruct.T(Of T)(T, TestStruct)"/> Public Shared field As Integer Sub T(Of T)(p As T, i as TestStruct) End Sub End Structure ]]> </file> </compilation> Dim xmlDoc = <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="F:TestStruct.field"> <see cref="M:TestStruct.T``1(``0,TestStruct)"/> </member> </members> </doc> ]]> </xml> Dim compilation = CompileCheckDiagnosticsAndXmlDocument(xmlSource, <errors></errors>, xmlDoc) Dim model = compilation.GetSemanticModel(compilation.SyntaxTrees(0)) Dim crefNodes = CrefFinder.FindAllCrefs(compilation.SyntaxTrees(0)) Assert.Equal(1, crefNodes.Count) Dim info = model.GetSymbolInfo(crefNodes(0)) Assert.NotNull(info.Symbol) Assert.Equal("Sub TestStruct.T(Of T)(p As T, i As TestStruct)", info.Symbol.ToTestDisplayString()) CheckAllNames(model, crefNodes(0), New NameSyntaxInfo("Global.TestStruct.T(Of T)", {"Sub TestStruct.T(Of T)(p As T, i As TestStruct)"}, {}), New NameSyntaxInfo("Global.TestStruct", {"TestStruct"}, {"TestStruct"}), New NameSyntaxInfo("Global", {"Global"}, {}), New NameSyntaxInfo("TestStruct", {"TestStruct"}, {"TestStruct"}), New NameSyntaxInfo("T(Of T)", {"Sub TestStruct.T(Of T)(p As T, i As TestStruct)"}, {}), New NameSyntaxInfo("T", {"T"}, {"T"}), New NameSyntaxInfo("T", {"T"}, {"T"}), New NameSyntaxInfo("TestStruct", {"TestStruct"}, {"TestStruct"})) End Sub <Fact> Private Sub ExtendedCref_QualifiedOperatorReference() Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Public Structure TestStruct(Of X) ''' <see cref="Global.TestStruct(Of ZZZ). operator+(integer, TestStruct(Of zzz))"/> Public Shared field As Integer Public Shared Operator +(a As Integer, b As TestStruct(Of X)) As String Return Nothing End Operator End Structure]]> </file> </compilation> Dim xmlDoc = <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="F:TestStruct`1.field"> <see cref="M:TestStruct`1.op_Addition(System.Int32,TestStruct{`0})"/> </member> </members> </doc> ]]> </xml> Dim compilation = CompileCheckDiagnosticsAndXmlDocument(xmlSource, <errors></errors>, xmlDoc) Dim model = compilation.GetSemanticModel(compilation.SyntaxTrees(0)) Dim crefNodes = CrefFinder.FindAllCrefs(compilation.SyntaxTrees(0)) Assert.Equal(1, crefNodes.Count) Dim info = model.GetSymbolInfo(crefNodes(0)) Assert.NotNull(info.Symbol) Assert.Equal("Function TestStruct(Of ZZZ).op_Addition(a As System.Int32, b As TestStruct(Of ZZZ)) As System.String", info.Symbol.ToTestDisplayString()) CheckAllNames(model, crefNodes(0), New NameSyntaxInfo("Global.TestStruct(Of ZZZ). operator+", {"Function TestStruct(Of ZZZ).op_Addition(a As System.Int32, b As TestStruct(Of ZZZ)) As System.String"}, {}), New NameSyntaxInfo("Global.TestStruct(Of ZZZ)", {"TestStruct(Of ZZZ)"}, {"TestStruct(Of ZZZ)"}), New NameSyntaxInfo("Global", {"Global"}, {}), New NameSyntaxInfo("TestStruct(Of ZZZ)", {"TestStruct(Of ZZZ)"}, {"TestStruct(Of ZZZ)"}), New NameSyntaxInfo("ZZZ", {"ZZZ"}, {"ZZZ"}), New NameSyntaxInfo("operator+", {"Function TestStruct(Of ZZZ).op_Addition(a As System.Int32, b As TestStruct(Of ZZZ)) As System.String"}, {}), New NameSyntaxInfo("TestStruct(Of zzz)", {"TestStruct(Of ZZZ)"}, {"TestStruct(Of ZZZ)"}), New NameSyntaxInfo("zzz", {"ZZZ"}, {"ZZZ"})) End Sub <Fact> Private Sub ExtendedCref_OperatorReference() Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Public Class Clazz Public Structure TestStruct ''' <see cref="operator+(integer, Global.Clazz.TestStruct)"/> Public Shared field As Integer Public Shared Operator +(a As Integer, b As TestStruct) As String Return Nothing End Operator End Structure End Class ]]> </file> </compilation> Dim xmlDoc = <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="F:Clazz.TestStruct.field"> <see cref="M:Clazz.TestStruct.op_Addition(System.Int32,Clazz.TestStruct)"/> </member> </members> </doc> ]]> </xml> Dim compilation = CompileCheckDiagnosticsAndXmlDocument(xmlSource, <errors></errors>, xmlDoc) Dim model = compilation.GetSemanticModel(compilation.SyntaxTrees(0)) Dim crefNodes = CrefFinder.FindAllCrefs(compilation.SyntaxTrees(0)) Assert.Equal(1, crefNodes.Count) Dim info = model.GetSymbolInfo(crefNodes(0)) Assert.NotNull(info.Symbol) Assert.Equal("Function Clazz.TestStruct.op_Addition(a As System.Int32, b As Clazz.TestStruct) As System.String", info.Symbol.ToTestDisplayString()) CheckAllNames(model, crefNodes(0), New NameSyntaxInfo("operator+", {"Function Clazz.TestStruct.op_Addition(a As System.Int32, b As Clazz.TestStruct) As System.String"}, {}), New NameSyntaxInfo("Global.Clazz.TestStruct", {"Clazz.TestStruct"}, {"Clazz.TestStruct"}), New NameSyntaxInfo("Global.Clazz", {"Clazz"}, {"Clazz"}), New NameSyntaxInfo("Global", {"Global"}, {}), New NameSyntaxInfo("Clazz", {"Clazz"}, {"Clazz"}), New NameSyntaxInfo("TestStruct", {"Clazz.TestStruct"}, {"Clazz.TestStruct"})) End Sub <Fact> Private Sub ExtendedCref_ReturnType() Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Public Class GenericClazz(Of T) End Class Public Class Clazz(Of X) Public Structure TestStruct ''' <see cref="operator ctype(Integer)"/> ''' <see cref="operator ctype(Integer) As TestStruct"/> ''' <see cref="Global.Clazz(Of A) . TestStruct. operator ctype(Clazz(Of A).TestStruct) As A"/> ''' <see cref="Global.Clazz(Of B) . TestStruct. operator ctype(B)"/> ''' <see cref="operator ctype(TestStruct) As Global.Clazz(Of Integer)"/> ''' <see cref="Clazz(Of C).TestStruct.operator ctype(Clazz(Of C). TestStruct) As GenericClazz(Of C)"/> Public Shared field As Integer Public Shared Narrowing Operator CType(a As Integer) As TestStruct Return Nothing End Operator Public Shared Narrowing Operator CType(a As TestStruct) As X Return Nothing End Operator Public Shared Narrowing Operator CType(a As TestStruct) As GenericClazz(Of X) Return Nothing End Operator Public Shared Narrowing Operator CType(a As X) As TestStruct Return Nothing End Operator Public Shared Narrowing Operator CType(a As TestStruct) As Global.Clazz(Of Integer) Return Nothing End Operator End Structure End Class ]]> </file> </compilation> Dim xmlDoc = <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="F:Clazz`1.TestStruct.field"> <see cref="M:Clazz`1.TestStruct.op_Explicit(System.Int32)~Clazz{`0}.TestStruct"/> <see cref="M:Clazz`1.TestStruct.op_Explicit(System.Int32)~Clazz{`0}.TestStruct"/> <see cref="M:Clazz`1.TestStruct.op_Explicit(Clazz{`0}.TestStruct)~`0"/> <see cref="M:Clazz`1.TestStruct.op_Explicit(`0)~Clazz{`0}.TestStruct"/> <see cref="M:Clazz`1.TestStruct.op_Explicit(Clazz{`0}.TestStruct)~Clazz{System.Int32}"/> <see cref="M:Clazz`1.TestStruct.op_Explicit(Clazz{`0}.TestStruct)~GenericClazz{`0}"/> </member> </members> </doc> ]]> </xml> Dim compilation = CompileCheckDiagnosticsAndXmlDocument(xmlSource, <errors></errors>, xmlDoc) Dim model = compilation.GetSemanticModel(compilation.SyntaxTrees(0)) Dim crefNodes = CrefFinder.FindAllCrefs(compilation.SyntaxTrees(0)) Assert.Equal(6, crefNodes.Count) Dim index As Integer = 0 For Each name In {"Function Clazz(Of X).TestStruct.op_Explicit(a As System.Int32) As Clazz(Of X).TestStruct", "Function Clazz(Of X).TestStruct.op_Explicit(a As System.Int32) As Clazz(Of X).TestStruct", "Function Clazz(Of A).TestStruct.op_Explicit(a As Clazz(Of A).TestStruct) As A", "Function Clazz(Of B).TestStruct.op_Explicit(a As B) As Clazz(Of B).TestStruct", "Function Clazz(Of X).TestStruct.op_Explicit(a As Clazz(Of X).TestStruct) As Clazz(Of System.Int32)", "Function Clazz(Of C).TestStruct.op_Explicit(a As Clazz(Of C).TestStruct) As GenericClazz(Of C)"} Dim info = model.GetSymbolInfo(crefNodes(index)) If name Is Nothing Then Assert.True(info.IsEmpty) Else Assert.NotNull(info.Symbol) Assert.Equal(name, info.Symbol.ToTestDisplayString()) End If index += 1 Next CheckAllNames(model, crefNodes(0), New NameSyntaxInfo("operator ctype", {"Function Clazz(Of X).TestStruct.op_Explicit(a As Clazz(Of X).TestStruct) As Clazz(Of System.Int32)", "Function Clazz(Of X).TestStruct.op_Explicit(a As Clazz(Of X).TestStruct) As GenericClazz(Of X)", "Function Clazz(Of X).TestStruct.op_Explicit(a As Clazz(Of X).TestStruct) As X", "Function Clazz(Of X).TestStruct.op_Explicit(a As System.Int32) As Clazz(Of X).TestStruct", "Function Clazz(Of X).TestStruct.op_Explicit(a As X) As Clazz(Of X).TestStruct"}, {})) CheckAllNames(model, crefNodes(1), New NameSyntaxInfo("operator ctype", {"Function Clazz(Of X).TestStruct.op_Explicit(a As Clazz(Of X).TestStruct) As Clazz(Of System.Int32)", "Function Clazz(Of X).TestStruct.op_Explicit(a As Clazz(Of X).TestStruct) As GenericClazz(Of X)", "Function Clazz(Of X).TestStruct.op_Explicit(a As Clazz(Of X).TestStruct) As X", "Function Clazz(Of X).TestStruct.op_Explicit(a As System.Int32) As Clazz(Of X).TestStruct", "Function Clazz(Of X).TestStruct.op_Explicit(a As X) As Clazz(Of X).TestStruct"}, {}), New NameSyntaxInfo("TestStruct", {"Clazz(Of X).TestStruct"}, {"Clazz(Of X).TestStruct"})) CheckAllNames(model, crefNodes(2), New NameSyntaxInfo("Global.Clazz(Of A) . TestStruct. operator ctype", {"Function Clazz(Of A).TestStruct.op_Explicit(a As Clazz(Of A).TestStruct) As Clazz(Of System.Int32)", "Function Clazz(Of A).TestStruct.op_Explicit(a As Clazz(Of A).TestStruct) As GenericClazz(Of A)", "Function Clazz(Of A).TestStruct.op_Explicit(a As Clazz(Of A).TestStruct) As A", "Function Clazz(Of A).TestStruct.op_Explicit(a As System.Int32) As Clazz(Of A).TestStruct", "Function Clazz(Of A).TestStruct.op_Explicit(a As A) As Clazz(Of A).TestStruct"}, {}), New NameSyntaxInfo("Global.Clazz(Of A) . TestStruct", {"Clazz(Of A).TestStruct"}, {"Clazz(Of A).TestStruct"}), New NameSyntaxInfo("Global.Clazz(Of A)", {"Clazz(Of A)"}, {"Clazz(Of A)"}), New NameSyntaxInfo("Global", {"Global"}, {}), New NameSyntaxInfo("Clazz(Of A)", {"Clazz(Of A)"}, {"Clazz(Of A)"}), New NameSyntaxInfo("A", {"A"}, {"A"}), New NameSyntaxInfo("TestStruct", {"Clazz(Of A).TestStruct"}, {"Clazz(Of A).TestStruct"}), New NameSyntaxInfo("operator ctype", {"Function Clazz(Of A).TestStruct.op_Explicit(a As Clazz(Of A).TestStruct) As Clazz(Of System.Int32)", "Function Clazz(Of A).TestStruct.op_Explicit(a As Clazz(Of A).TestStruct) As GenericClazz(Of A)", "Function Clazz(Of A).TestStruct.op_Explicit(a As Clazz(Of A).TestStruct) As A", "Function Clazz(Of A).TestStruct.op_Explicit(a As System.Int32) As Clazz(Of A).TestStruct", "Function Clazz(Of A).TestStruct.op_Explicit(a As A) As Clazz(Of A).TestStruct"}, {}), New NameSyntaxInfo("Clazz(Of A).TestStruct", {"Clazz(Of A).TestStruct"}, {"Clazz(Of A).TestStruct"}), New NameSyntaxInfo("Clazz(Of A)", {"Clazz(Of A)"}, {"Clazz(Of A)"}), New NameSyntaxInfo("A", {"A"}, {"A"}), New NameSyntaxInfo("TestStruct", {"Clazz(Of A).TestStruct"}, {"Clazz(Of A).TestStruct"}), New NameSyntaxInfo("A", {"A"}, {"A"})) CheckAllNames(model, crefNodes(3), New NameSyntaxInfo("Global.Clazz(Of B) . TestStruct. operator ctype", {"Function Clazz(Of B).TestStruct.op_Explicit(a As Clazz(Of B).TestStruct) As Clazz(Of System.Int32)", "Function Clazz(Of B).TestStruct.op_Explicit(a As Clazz(Of B).TestStruct) As GenericClazz(Of B)", "Function Clazz(Of B).TestStruct.op_Explicit(a As Clazz(Of B).TestStruct) As B", "Function Clazz(Of B).TestStruct.op_Explicit(a As System.Int32) As Clazz(Of B).TestStruct", "Function Clazz(Of B).TestStruct.op_Explicit(a As B) As Clazz(Of B).TestStruct"}, {}), New NameSyntaxInfo("Global.Clazz(Of B) . TestStruct", {"Clazz(Of B).TestStruct"}, {"Clazz(Of B).TestStruct"}), New NameSyntaxInfo("Global.Clazz(Of B)", {"Clazz(Of B)"}, {"Clazz(Of B)"}), New NameSyntaxInfo("Global", {"Global"}, {}), New NameSyntaxInfo("Clazz(Of B)", {"Clazz(Of B)"}, {"Clazz(Of B)"}), New NameSyntaxInfo("B", {"B"}, {"B"}), New NameSyntaxInfo("TestStruct", {"Clazz(Of B).TestStruct"}, {"Clazz(Of B).TestStruct"}), New NameSyntaxInfo("operator ctype", {"Function Clazz(Of B).TestStruct.op_Explicit(a As Clazz(Of B).TestStruct) As Clazz(Of System.Int32)", "Function Clazz(Of B).TestStruct.op_Explicit(a As Clazz(Of B).TestStruct) As GenericClazz(Of B)", "Function Clazz(Of B).TestStruct.op_Explicit(a As Clazz(Of B).TestStruct) As B", "Function Clazz(Of B).TestStruct.op_Explicit(a As System.Int32) As Clazz(Of B).TestStruct", "Function Clazz(Of B).TestStruct.op_Explicit(a As B) As Clazz(Of B).TestStruct"}, {}), New NameSyntaxInfo("B", {"B"}, {"B"})) CheckAllNames(model, crefNodes(4), New NameSyntaxInfo("operator ctype", {"Function Clazz(Of X).TestStruct.op_Explicit(a As Clazz(Of X).TestStruct) As Clazz(Of System.Int32)", "Function Clazz(Of X).TestStruct.op_Explicit(a As Clazz(Of X).TestStruct) As GenericClazz(Of X)", "Function Clazz(Of X).TestStruct.op_Explicit(a As Clazz(Of X).TestStruct) As X", "Function Clazz(Of X).TestStruct.op_Explicit(a As System.Int32) As Clazz(Of X).TestStruct", "Function Clazz(Of X).TestStruct.op_Explicit(a As X) As Clazz(Of X).TestStruct"}, {}), New NameSyntaxInfo("TestStruct", {"Clazz(Of X).TestStruct"}, {"Clazz(Of X).TestStruct"}), New NameSyntaxInfo("Global.Clazz(Of Integer)", {"Clazz(Of System.Int32)"}, {"Clazz(Of System.Int32)"}), New NameSyntaxInfo("Global", {"Global"}, {}), New NameSyntaxInfo("Clazz(Of Integer)", {"Clazz(Of System.Int32)"}, {"Clazz(Of System.Int32)"})) CheckAllNames(model, crefNodes(5), New NameSyntaxInfo("Clazz(Of C).TestStruct.operator ctype", {"Function Clazz(Of C).TestStruct.op_Explicit(a As Clazz(Of C).TestStruct) As Clazz(Of System.Int32)", "Function Clazz(Of C).TestStruct.op_Explicit(a As Clazz(Of C).TestStruct) As GenericClazz(Of C)", "Function Clazz(Of C).TestStruct.op_Explicit(a As Clazz(Of C).TestStruct) As C", "Function Clazz(Of C).TestStruct.op_Explicit(a As System.Int32) As Clazz(Of C).TestStruct", "Function Clazz(Of C).TestStruct.op_Explicit(a As C) As Clazz(Of C).TestStruct"}, {}), New NameSyntaxInfo("Clazz(Of C).TestStruct", {"Clazz(Of C).TestStruct"}, {"Clazz(Of C).TestStruct"}), New NameSyntaxInfo("Clazz(Of C)", {"Clazz(Of C)"}, {"Clazz(Of C)"}), New NameSyntaxInfo("C", {"C"}, {"C"}), New NameSyntaxInfo("TestStruct", {"Clazz(Of C).TestStruct"}, {"Clazz(Of C).TestStruct"}), New NameSyntaxInfo("operator ctype", {"Function Clazz(Of C).TestStruct.op_Explicit(a As Clazz(Of C).TestStruct) As Clazz(Of System.Int32)", "Function Clazz(Of C).TestStruct.op_Explicit(a As Clazz(Of C).TestStruct) As GenericClazz(Of C)", "Function Clazz(Of C).TestStruct.op_Explicit(a As Clazz(Of C).TestStruct) As C", "Function Clazz(Of C).TestStruct.op_Explicit(a As System.Int32) As Clazz(Of C).TestStruct", "Function Clazz(Of C).TestStruct.op_Explicit(a As C) As Clazz(Of C).TestStruct"}, {}), New NameSyntaxInfo("Clazz(Of C). TestStruct", {"Clazz(Of C).TestStruct"}, {"Clazz(Of C).TestStruct"}), New NameSyntaxInfo("Clazz(Of C)", {"Clazz(Of C)"}, {"Clazz(Of C)"}), New NameSyntaxInfo("C", {"C"}, {"C"}), New NameSyntaxInfo("TestStruct", {"Clazz(Of C).TestStruct"}, {"Clazz(Of C).TestStruct"}), New NameSyntaxInfo("GenericClazz(Of C)", {"GenericClazz(Of C)"}, {"GenericClazz(Of C)"}), New NameSyntaxInfo("C", {"C"}, {"C"})) End Sub <Fact> Private Sub ExtendedCref_ColorColor() Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Public Class SomeClass Public Sub SB() End Sub End Class Public Class Clazz Public someClass As SomeClass Public Structure TestStruct ''' <see cref="someclass.sb()"/> ''' <see cref="operator ctype(SomeClass) As TestStruct"/> ''' <see cref="operator ctype(TestStruct) As SomeClass"/> Public Shared field As Integer Public Shared Narrowing Operator CType(a As TestStruct) As SomeClass Return Nothing End Operator Public Shared Narrowing Operator CType(a As SomeClass) As TestStruct Return Nothing End Operator End Structure End Class ]]> </file> </compilation> Dim xmlDoc = <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="F:Clazz.TestStruct.field"> <see cref="M:SomeClass.SB"/> <see cref="M:Clazz.TestStruct.op_Explicit(SomeClass)~Clazz.TestStruct"/> <see cref="M:Clazz.TestStruct.op_Explicit(Clazz.TestStruct)~SomeClass"/> </member> </members> </doc> ]]> </xml> Dim compilation = CompileCheckDiagnosticsAndXmlDocument(xmlSource, <errors></errors>, xmlDoc) Dim model = compilation.GetSemanticModel(compilation.SyntaxTrees(0)) Dim crefNodes = CrefFinder.FindAllCrefs(compilation.SyntaxTrees(0)) Assert.Equal(3, crefNodes.Count) Dim index As Integer = 0 For Each name In {"Sub SomeClass.SB()", "Function Clazz.TestStruct.op_Explicit(a As SomeClass) As Clazz.TestStruct", "Function Clazz.TestStruct.op_Explicit(a As Clazz.TestStruct) As SomeClass"} Dim info = model.GetSymbolInfo(crefNodes(index)) If name Is Nothing Then Assert.True(info.IsEmpty) Else Assert.NotNull(info.Symbol) Assert.Equal(name, info.Symbol.ToTestDisplayString()) End If index += 1 Next CheckAllNames(model, crefNodes(0), New NameSyntaxInfo("someclass.sb", {"Sub SomeClass.SB()"}, {}), New NameSyntaxInfo("someclass", {"SomeClass"}, {"SomeClass"}), New NameSyntaxInfo("sb", {"Sub SomeClass.SB()"}, {})) CheckAllNames(model, crefNodes(1), New NameSyntaxInfo("operator ctype", {"Function Clazz.TestStruct.op_Explicit(a As SomeClass) As Clazz.TestStruct", "Function Clazz.TestStruct.op_Explicit(a As Clazz.TestStruct) As SomeClass"}, {}), New NameSyntaxInfo("SomeClass", {"SomeClass"}, {"SomeClass"}), New NameSyntaxInfo("TestStruct", {"Clazz.TestStruct"}, {"Clazz.TestStruct"})) CheckAllNames(model, crefNodes(2), New NameSyntaxInfo("operator ctype", {"Function Clazz.TestStruct.op_Explicit(a As SomeClass) As Clazz.TestStruct", "Function Clazz.TestStruct.op_Explicit(a As Clazz.TestStruct) As SomeClass"}, {}), New NameSyntaxInfo("TestStruct", {"Clazz.TestStruct"}, {"Clazz.TestStruct"}), New NameSyntaxInfo("SomeClass", {"SomeClass"}, {"SomeClass"})) End Sub <Fact> Private Sub ExtendedCref_ReferencingConversionByMethodName() Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Public Class SomeClass End Class Public Structure TestStruct ''' <see cref="op_Implicit(SomeClass)"/> ''' <see cref="op_Explicit(TestStruct)"/> Public Shared field As Integer Public Shared Narrowing Operator CType(a As TestStruct) As SomeClass Return Nothing End Operator Public Shared Widening Operator CType(a As SomeClass) As TestStruct Return Nothing End Operator End Structure ]]> </file> </compilation> Dim xmlDoc = <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="F:TestStruct.field"> <see cref="M:TestStruct.op_Implicit(SomeClass)~TestStruct"/> <see cref="M:TestStruct.op_Explicit(TestStruct)~SomeClass"/> </member> </members> </doc> ]]> </xml> Dim compilation = CompileCheckDiagnosticsAndXmlDocument(xmlSource, <errors></errors>, xmlDoc) Dim model = compilation.GetSemanticModel(compilation.SyntaxTrees(0)) Dim crefNodes = CrefFinder.FindAllCrefs(compilation.SyntaxTrees(0)) Assert.Equal(2, crefNodes.Count) Dim index As Integer = 0 For Each name In {"Function TestStruct.op_Implicit(a As SomeClass) As TestStruct", "Function TestStruct.op_Explicit(a As TestStruct) As SomeClass"} Dim info = model.GetSymbolInfo(crefNodes(index)) If name Is Nothing Then Assert.True(info.IsEmpty) Else Assert.NotNull(info.Symbol) Assert.Equal(name, info.Symbol.ToTestDisplayString()) End If index += 1 Next End Sub <Fact> Private Sub ExtendedCref_ReferencingConversionByMethodName_ReturnTypeOverloading() Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Public Class SomeClass End Class Public Structure TestStruct ''' <see cref="op_Implicit(TestStruct) As SomeClass"/> ''' <see cref="op_Implicit(TestStruct) As String"/> Public Shared field As Integer Public Shared Widening Operator CType(a As TestStruct) As SomeClass Return Nothing End Operator Public Shared Widening Operator CType(a As TestStruct) As String Return Nothing End Operator End Structure ]]> </file> </compilation> Dim xmlDoc = <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="F:TestStruct.field"> <see cref="M:TestStruct.op_Implicit(TestStruct)~SomeClass"/> <see cref="M:TestStruct.op_Implicit(TestStruct)~System.String"/> </member> </members> </doc> ]]> </xml> Dim compilation = CompileCheckDiagnosticsAndXmlDocument(xmlSource, <errors></errors>, xmlDoc) Dim model = compilation.GetSemanticModel(compilation.SyntaxTrees(0)) Dim crefNodes = CrefFinder.FindAllCrefs(compilation.SyntaxTrees(0)) Assert.Equal(2, crefNodes.Count) Dim index As Integer = 0 For Each name In {"Function TestStruct.op_Implicit(a As TestStruct) As SomeClass", "Function TestStruct.op_Implicit(a As TestStruct) As System.String"} Dim info = model.GetSymbolInfo(crefNodes(index)) If name Is Nothing Then Assert.True(info.IsEmpty) Else Assert.NotNull(info.Symbol) Assert.Equal(name, info.Symbol.ToTestDisplayString()) End If index += 1 Next End Sub <Fact> Private Sub ExtendedCref_MemberAndTypeParamConflict() Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Public Structure T(Of X) Class T(Of Y) Sub T(Of T)(p As T, i as TestStruct) End Sub End Class End Structure Public Structure TestStruct ''' <see cref="Global.T(Of T).T(Of T).T(Of T)(T, TestStruct)"/> Public Shared field As Integer End Structure ]]> </file> </compilation> Dim xmlDoc = <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="F:TestStruct.field"> <see cref="M:T`1.T`1.T``1(``0,TestStruct)"/> </member> </members> </doc> ]]> </xml> Dim compilation = CompileCheckDiagnosticsAndXmlDocument(xmlSource, <errors></errors>, xmlDoc) Dim model = compilation.GetSemanticModel(compilation.SyntaxTrees(0)) Dim crefNodes = CrefFinder.FindAllCrefs(compilation.SyntaxTrees(0)) Assert.Equal(1, crefNodes.Count) Dim info = model.GetSymbolInfo(crefNodes(0)) Assert.NotNull(info.Symbol) Assert.Equal("Sub T(Of T).T(Of T).T(Of T)(p As T, i As TestStruct)", info.Symbol.ToTestDisplayString()) CheckAllNames(model, crefNodes(0), New NameSyntaxInfo("Global.T(Of T).T(Of T).T(Of T)", {"Sub T(Of T).T(Of T).T(Of T)(p As T, i As TestStruct)"}, {}), New NameSyntaxInfo("Global.T(Of T).T(Of T)", {"T(Of T).T(Of T)"}, {"T(Of T).T(Of T)"}), New NameSyntaxInfo("Global.T(Of T)", {"T(Of T)"}, {"T(Of T)"}), New NameSyntaxInfo("Global", {"Global"}, {}), New NameSyntaxInfo("T(Of T)", {"T(Of T)"}, {"T(Of T)"}), New NameSyntaxInfo("T", {"T"}, {"T"}), New NameSyntaxInfo("T(Of T)", {"T(Of T).T(Of T)"}, {"T(Of T).T(Of T)"}), New NameSyntaxInfo("T", {"T"}, {"T"}), New NameSyntaxInfo("T(Of T)", {"Sub T(Of T).T(Of T).T(Of T)(p As T, i As TestStruct)"}, {}), New NameSyntaxInfo("T", {"T"}, {"T"}), New NameSyntaxInfo("T", {"T"}, {"T"}), New NameSyntaxInfo("TestStruct", {"TestStruct"}, {"TestStruct"})) End Sub Private Structure NameSyntaxInfo Public ReadOnly Syntax As String Public ReadOnly Symbols As String() Public ReadOnly Types As String() Public Sub New(syntax As String, symbols As String(), types As String()) Me.Syntax = syntax Me.Symbols = symbols Me.Types = types End Sub End Structure Private Sub CheckAllNames(model As SemanticModel, cref As CrefReferenceSyntax, ParamArray expected As NameSyntaxInfo()) Dim names = NameSyntaxFinder.FindNames(cref) Assert.Equal(expected.Length, names.Count) For i = 0 To names.Count - 1 Dim e = expected(i) Dim sym = names(i) Assert.Equal(e.Syntax, sym.ToString().Trim()) Dim actual = model.GetSymbolInfo(sym) If e.Symbols.Length = 0 Then Assert.True(actual.IsEmpty) ElseIf e.Symbols.Length = 1 Then Assert.NotNull(actual.Symbol) Assert.Equal(e.Symbols(0), actual.Symbol.ToTestDisplayString) Else Assert.Equal(CandidateReason.Ambiguous, actual.CandidateReason) AssertStringArraysEqual(e.Symbols, (From s In actual.CandidateSymbols Select s.ToTestDisplayString()).ToArray) End If Dim typeInfo = model.GetTypeInfo(sym) If e.Types.Length = 0 Then Assert.Null(typeInfo.Type) ElseIf e.Types.Length = 1 Then Assert.NotNull(typeInfo.Type) Assert.Equal(e.Types(0), typeInfo.Type.ToTestDisplayString()) Else Assert.Null(typeInfo.Type) End If Next End Sub <Fact> Private Sub ExtendedCref_UnaryOperatorsAndConversion() Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Public Class Clazz Public Shared Operator Like(a As Clazz, b As Integer) As Clazz Return Nothing End Operator Public Shared Operator And(a As Clazz, b As Integer) As Clazz Return Nothing End Operator Public Shared Operator Or(a As Clazz, b As Integer) As Clazz Return Nothing End Operator Public Shared Operator Xor(a As Clazz, b As Integer) As Clazz Return Nothing End Operator Public Shared Operator Mod(a As Clazz, b As Integer) As Clazz Return Nothing End Operator Public Shared Operator Not(a As Clazz) As Boolean Return Nothing End Operator Public Shared Operator IsTrue(a As Clazz) As Boolean Return Nothing End Operator Public Shared Operator IsFalse(a As Clazz) As Boolean Return Nothing End Operator Public Shared Narrowing Operator CType(a As Clazz) As String Return Nothing End Operator Public Shared Widening Operator CType(a As Clazz) As Integer? Return Nothing End Operator Public Shared Widening Operator CType(a As Integer?) As Clazz Return Nothing End Operator Public Shared Narrowing Operator CType(a As Integer) As Clazz Return Nothing End Operator ''' <see cref="operator Like (Clazz, Int32)"/> ''' <see cref="Clazz. operator And (Clazz, Int32)"/> ''' <see cref="operator Or (Clazz, Int32)"/> ''' <see cref=" Clazz. operator Xor (Clazz, Int32)"/> ''' <see cref="operator Mod (Clazz, Int32)"/> ''' <see cref="Global . Clazz. operator Not (Clazz)"/> ''' <see cref=" operator istrue (Clazz)"/> ''' <see cref=" Clazz. operator isfalse (Clazz)"/> ''' <see cref=" operator ctype (Clazz) as string"/> ''' <see cref=" Clazz. operator ctype (Clazz) as integer?"/> ''' <see cref=" operator ctype (integer?) as clazz"/> ''' <see cref=" operator ctype (integer) as clazz"/> ''' <see cref=" Global . Clazz. operator ctype (integer) as clazz"/> Public Shared field As Integer End Class ]]> </file> </compilation> Dim xmlDoc = <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="F:Clazz.field"> <see cref="M:Clazz.op_Like(Clazz,System.Int32)"/> <see cref="M:Clazz.op_BitwiseAnd(Clazz,System.Int32)"/> <see cref="M:Clazz.op_BitwiseOr(Clazz,System.Int32)"/> <see cref="M:Clazz.op_ExclusiveOr(Clazz,System.Int32)"/> <see cref="M:Clazz.op_Modulus(Clazz,System.Int32)"/> <see cref="M:Clazz.op_OnesComplement(Clazz)"/> <see cref="M:Clazz.op_True(Clazz)"/> <see cref="M:Clazz.op_False(Clazz)"/> <see cref="M:Clazz.op_Explicit(Clazz)~System.String"/> <see cref="M:Clazz.op_Implicit(Clazz)~System.Nullable{System.Int32}"/> <see cref="M:Clazz.op_Implicit(System.Nullable{System.Int32})~Clazz"/> <see cref="M:Clazz.op_Explicit(System.Int32)~Clazz"/> <see cref="M:Clazz.op_Explicit(System.Int32)~Clazz"/> </member> </members> </doc> ]]> </xml> Dim compilation = CompileCheckDiagnosticsAndXmlDocument(xmlSource, <errors></errors>, xmlDoc) Dim model = compilation.GetSemanticModel(compilation.SyntaxTrees(0)) Dim crefNodes = CrefFinder.FindAllCrefs(compilation.SyntaxTrees(0)) Assert.Equal(13, crefNodes.Count) Dim index As Integer = 0 For Each name In {"Function Clazz.op_Like(a As Clazz, b As System.Int32) As Clazz", "Function Clazz.op_BitwiseAnd(a As Clazz, b As System.Int32) As Clazz", "Function Clazz.op_BitwiseOr(a As Clazz, b As System.Int32) As Clazz", "Function Clazz.op_ExclusiveOr(a As Clazz, b As System.Int32) As Clazz", "Function Clazz.op_Modulus(a As Clazz, b As System.Int32) As Clazz", "Function Clazz.op_OnesComplement(a As Clazz) As System.Boolean", "Function Clazz.op_True(a As Clazz) As System.Boolean", "Function Clazz.op_False(a As Clazz) As System.Boolean", "Function Clazz.op_Explicit(a As Clazz) As System.String", "Function Clazz.op_Implicit(a As Clazz) As System.Nullable(Of System.Int32)", "Function Clazz.op_Implicit(a As System.Nullable(Of System.Int32)) As Clazz", "Function Clazz.op_Explicit(a As System.Int32) As Clazz", "Function Clazz.op_Explicit(a As System.Int32) As Clazz"} Dim info = model.GetSymbolInfo(crefNodes(index)) Assert.NotNull(info.Symbol) Assert.Equal(name, info.Symbol.ToTestDisplayString()) index += 1 Next End Sub <Fact> Private Sub ExtendedCref_StandaloneSimpleName() Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Public Class Clazz Public Structure STR End Structure Public Sub New() End Sub Public Sub New(s As Integer) End Sub Public Sub New(s As Clazz) End Sub Public Sub [New](Of T)(s As Integer) End Sub Public Sub [New](Of T)(s As Clazz) End Sub Public Sub [New](Of T)(s As T) End Sub Public Sub S0(s As Integer) End Sub Public Sub S0(s As String) End Sub Public Sub S0(s As STR) End Sub ''' <see cref="New(Clazz)"/> ''' <see cref="New(Int32)"/> ''' <see cref="New()"/> ''' <see cref="New(STR)"/> ''' <see cref="[New](Clazz)"/> ''' <see cref="[New](Of T)(Clazz)"/> ''' <see cref="[New](Of T)(T)"/> ''' <see cref="[New](Of T, W)(T)"/> ''' <see cref="S0(Of T)(T)"/> ''' <see cref="S0(STR)"/> Public Shared field As Integer End Class ]]> </file> </compilation> Dim xmlDoc = <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="F:Clazz.field"> <see cref="M:Clazz.#ctor(Clazz)"/> <see cref="M:Clazz.#ctor(System.Int32)"/> <see cref="M:Clazz.#ctor"/> <see cref="!:New(STR)"/> <see cref="!:[New](Clazz)"/> <see cref="M:Clazz.New``1(Clazz)"/> <see cref="M:Clazz.New``1(``0)"/> <see cref="!:[New](Of T, W)(T)"/> <see cref="!:S0(Of T)(T)"/> <see cref="M:Clazz.S0(Clazz.STR)"/> </member> </members> </doc> ]]> </xml> Dim compilation = CompileCheckDiagnosticsAndXmlDocument(xmlSource, <errors> <![CDATA[ BC42309: XML comment has a tag with a 'cref' attribute 'New(STR)' that could not be resolved. ''' <see cref="New(STR)"/> ~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute '[New](Clazz)' that could not be resolved. ''' <see cref="[New](Clazz)"/> ~~~~~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute '[New](Of T, W)(T)' that could not be resolved. ''' <see cref="[New](Of T, W)(T)"/> ~~~~~~~~~~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'S0(Of T)(T)' that could not be resolved. ''' <see cref="S0(Of T)(T)"/> ~~~~~~~~~~~~~~~~~~ ]]> </errors>, xmlDoc) Dim model = compilation.GetSemanticModel(compilation.SyntaxTrees(0)) Dim crefNodes = CrefFinder.FindAllCrefs(compilation.SyntaxTrees(0)) Assert.Equal(10, crefNodes.Count) Dim index As Integer = 0 For Each name In {"Sub Clazz..ctor(s As Clazz)", "Sub Clazz..ctor(s As System.Int32)", "Sub Clazz..ctor()", Nothing, Nothing, "Sub Clazz.[New](Of T)(s As Clazz)", "Sub Clazz.[New](Of T)(s As T)", Nothing, Nothing, "Sub Clazz.S0(s As Clazz.STR)"} Dim info = model.GetSymbolInfo(crefNodes(index)) If name Is Nothing Then Assert.True(info.IsEmpty) Else Assert.NotNull(info.Symbol) Assert.Equal(name, info.Symbol.ToTestDisplayString()) End If index += 1 Next End Sub <Fact> Private Sub ExtendedCref_QualifiedName_A() Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Public Class Clazz Public Structure STR End Structure Public Sub New() End Sub Public Sub New(s As Integer) End Sub Public Sub New(s As Clazz) End Sub Public Sub [New](Of T)(s As Integer) End Sub Public Sub [New](Of T)(s As Clazz) End Sub Public Sub [New](Of T)(s As T) End Sub Public Sub S0(s As Integer) End Sub Public Sub S0(s As String) End Sub Public Sub S0(s As STR) End Sub End Class Public Structure TestStruct ''' <see cref="Clazz.New(Clazz)"/> ''' <see cref="Global.Clazz.New(Int32)"/> ''' <see cref="Clazz.New()"/> ''' <see cref="Clazz.New(Clazz.STR)"/> ''' <see cref="Clazz.[New](Clazz)"/> ''' <see cref="Clazz.[New](Of T)(Clazz)"/> ''' <see cref="Global.Clazz.[New](Of T)(T)"/> ''' <see cref="Clazz.[New](Of T, W)(T)"/> ''' <see cref="Clazz.S0(Of T)(T)"/> ''' <see cref="Global.Clazz.S0(Clazz.STR)"/> Public Shared field As Integer End Structure ]]> </file> </compilation> Dim xmlDoc = <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="F:TestStruct.field"> <see cref="M:Clazz.#ctor(Clazz)"/> <see cref="M:Clazz.#ctor(System.Int32)"/> <see cref="M:Clazz.#ctor"/> <see cref="!:Clazz.New(Clazz.STR)"/> <see cref="!:Clazz.[New](Clazz)"/> <see cref="M:Clazz.New``1(Clazz)"/> <see cref="M:Clazz.New``1(``0)"/> <see cref="!:Clazz.[New](Of T, W)(T)"/> <see cref="!:Clazz.S0(Of T)(T)"/> <see cref="M:Clazz.S0(Clazz.STR)"/> </member> </members> </doc> ]]> </xml> Dim compilation = CompileCheckDiagnosticsAndXmlDocument(xmlSource, <errors> <![CDATA[ BC42309: XML comment has a tag with a 'cref' attribute 'Clazz.New(Clazz.STR)' that could not be resolved. ''' <see cref="Clazz.New(Clazz.STR)"/> ~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'Clazz.[New](Clazz)' that could not be resolved. ''' <see cref="Clazz.[New](Clazz)"/> ~~~~~~~~~~~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'Clazz.[New](Of T, W)(T)' that could not be resolved. ''' <see cref="Clazz.[New](Of T, W)(T)"/> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'Clazz.S0(Of T)(T)' that could not be resolved. ''' <see cref="Clazz.S0(Of T)(T)"/> ~~~~~~~~~~~~~~~~~~~~~~~~ ]]> </errors>, xmlDoc) Dim model = compilation.GetSemanticModel(compilation.SyntaxTrees(0)) Dim crefNodes = CrefFinder.FindAllCrefs(compilation.SyntaxTrees(0)) Assert.Equal(10, crefNodes.Count) Dim index As Integer = 0 For Each name In {"Sub Clazz..ctor(s As Clazz)", "Sub Clazz..ctor(s As System.Int32)", "Sub Clazz..ctor()", Nothing, Nothing, "Sub Clazz.[New](Of T)(s As Clazz)", "Sub Clazz.[New](Of T)(s As T)", Nothing, Nothing, "Sub Clazz.S0(s As Clazz.STR)"} Dim info = model.GetSymbolInfo(crefNodes(index)) If name Is Nothing Then Assert.True(info.IsEmpty) Else Assert.NotNull(info.Symbol) Assert.Equal(name, info.Symbol.ToTestDisplayString()) End If index += 1 Next End Sub <Fact> Private Sub ExtendedCref_QualifiedName_B() Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Public Structure Struct End Structure Public Class Clazz(Of A, B) Public Sub New() End Sub Public Sub New(s As Integer) End Sub Public Sub New(s As Clazz(Of Integer, Struct)) End Sub Public Sub New(s As Clazz(Of A, B)) End Sub Public Sub [New](Of T)(s As Integer) End Sub Public Sub [New](Of T)(s As Clazz(Of T, T)) End Sub Public Sub [New](Of T)(s As Clazz(Of T, B)) End Sub Public Sub [New](Of T)(s As T) End Sub Public Sub S0(s As Integer) End Sub Public Sub S0(s As String) End Sub Public Sub S0(Of X, Y)(a As A, b As B, c As X, d As Y) End Sub End Class Public Structure TestStruct ''' <see cref="Clazz.New(Integer)"/> ''' <see cref="Global.Clazz(Of X, Y).New(Int32)"/> ''' <see cref="Global.Clazz(Of X, Y).New(Clazz(Of X, Y))"/> ''' <see cref="Global.Clazz(Of X, Y).New(Clazz(Of Int32, Y))"/> ''' <see cref="Global.Clazz(Of X, Y).New(Clazz(Of Int32, Struct))"/> ''' <see cref="Clazz(Of X, Y).New()"/> ''' <see cref="Clazz(Of [Integer], Y).New([Integer])"/> ''' <see cref="Clazz(Of X, Y).[New](Clazz)"/> ''' <see cref="Clazz(Of X(Of D), Y).[New](Of T)(Int32)"/> ''' <see cref="Clazz(Of X, Y).[New](Of X)(X)"/> ''' <see cref="Clazz(Of X, Y).[New](Of X)(Y)"/> ''' <see cref="Clazz(Of X, Y).[New](Of T)(T)"/> ''' <see cref="Clazz(Of X, Y).[New](Of X)(Clazz(Of X, X))"/> ''' <see cref="Clazz(Of X, Y).[New](Of X)(Clazz(Of X, Y))"/> ''' <see cref="Clazz(Of X, Y).S0(Of T, U)(X, Y, T, U)"/> ''' <see cref="Global.Clazz(Of X, Y).S0(Of X, Y)(X, Y, X, Y)"/> Public Shared field As Integer End Structure ]]> </file> </compilation> Dim xmlDoc = <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="F:TestStruct.field"> <see cref="!:Clazz.New(Integer)"/> <see cref="M:Clazz`2.#ctor(System.Int32)"/> <see cref="M:Clazz`2.#ctor(Clazz{`0,`1})"/> <see cref="!:Global.Clazz(Of X, Y).New(Clazz(Of Int32, Y))"/> <see cref="M:Clazz`2.#ctor(Clazz{System.Int32,Struct})"/> <see cref="M:Clazz`2.#ctor"/> <see cref="!:Clazz(Of [Integer], Y).New([Integer])"/> <see cref="!:Clazz(Of X, Y).[New](Clazz)"/> <see cref="!:Clazz(Of X(Of D), Y).[New](Of T)(Int32)"/> <see cref="M:Clazz`2.New``1(``0)"/> <see cref="!:Clazz(Of X, Y).[New](Of X)(Y)"/> <see cref="M:Clazz`2.New``1(``0)"/> <see cref="M:Clazz`2.New``1(Clazz{``0,``0})"/> <see cref="M:Clazz`2.New``1(Clazz{``0,`1})"/> <see cref="M:Clazz`2.S0``2(`0,`1,``0,``1)"/> <see cref="!:Global.Clazz(Of X, Y).S0(Of X, Y)(X, Y, X, Y)"/> </member> </members> </doc> ]]> </xml> Dim compilation = CompileCheckDiagnosticsAndXmlDocument(xmlSource, <errors> <![CDATA[ BC42309: XML comment has a tag with a 'cref' attribute 'Clazz.New(Integer)' that could not be resolved. ''' <see cref="Clazz.New(Integer)"/> ~~~~~~~~~~~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'Global.Clazz(Of X, Y).New(Clazz(Of Int32, Y))' that could not be resolved. ''' <see cref="Global.Clazz(Of X, Y).New(Clazz(Of Int32, Y))"/> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'Clazz(Of [Integer], Y).New([Integer])' that could not be resolved. ''' <see cref="Clazz(Of [Integer], Y).New([Integer])"/> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'Clazz(Of X, Y).[New](Clazz)' that could not be resolved. ''' <see cref="Clazz(Of X, Y).[New](Clazz)"/> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'Clazz(Of X(Of D), Y).[New](Of T)(Int32)' that could not be resolved. ''' <see cref="Clazz(Of X(Of D), Y).[New](Of T)(Int32)"/> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'Clazz(Of X, Y).[New](Of X)(Y)' that could not be resolved. ''' <see cref="Clazz(Of X, Y).[New](Of X)(Y)"/> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'Global.Clazz(Of X, Y).S0(Of X, Y)(X, Y, X, Y)' that could not be resolved. ''' <see cref="Global.Clazz(Of X, Y).S0(Of X, Y)(X, Y, X, Y)"/> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]> </errors>, xmlDoc) Dim model = compilation.GetSemanticModel(compilation.SyntaxTrees(0)) Dim crefNodes = CrefFinder.FindAllCrefs(compilation.SyntaxTrees(0)) Assert.Equal(16, crefNodes.Count) Dim index As Integer = 0 For Each name In {Nothing, "Sub Clazz(Of X, Y)..ctor(s As System.Int32)", "Sub Clazz(Of X, Y)..ctor(s As Clazz(Of X, Y))", Nothing, "Sub Clazz(Of X, Y)..ctor(s As Clazz(Of System.Int32, Struct))", "Sub Clazz(Of X, Y)..ctor()", Nothing, Nothing, Nothing, "Sub Clazz(Of X, Y).[New](Of X)(s As X)", Nothing, "Sub Clazz(Of X, Y).[New](Of T)(s As T)", "Sub Clazz(Of X, Y).[New](Of X)(s As Clazz(Of X, X))", "Sub Clazz(Of X, Y).[New](Of X)(s As Clazz(Of X, Y))", "Sub Clazz(Of X, Y).S0(Of T, U)(a As X, b As Y, c As T, d As U)", Nothing} Dim info = model.GetSymbolInfo(crefNodes(index)) If name Is Nothing Then Assert.True(info.IsEmpty) Else Assert.NotNull(info.Symbol) Assert.Equal(name, info.Symbol.ToTestDisplayString()) End If index += 1 Next End Sub <Fact> Public Sub Include_AttrMissing_XMLMissingFileOrPathAttribute1() Dim xmlText = <root><target>Included</target></root> Dim xmlFile = Temp.CreateFile(extension:=".xml").WriteAllText(xmlText.Value.ToString) Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Imports System.Collections.Generic ''' <summary> ''' <include file='**FILE**' /> ''' <include path='//target' /> ''' <include/> ''' </summary> Class C End Class ]]> </file> </compilation> CompileCheckDiagnosticsAndXmlDocument(FormatSourceXml(xmlSource, xmlFile), <error> <![CDATA[ BC42310: XML comment tag 'include' must have a 'path' attribute. XML comment will be ignored. ''' <include file='**FILE**' /> ~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42310: XML comment tag 'include' must have a 'file' attribute. XML comment will be ignored. ''' <include path='//target' /> ~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42310: XML comment tag 'include' must have a 'file' attribute. XML comment will be ignored. ''' <include/> ~~~~~~~~~~ BC42310: XML comment tag 'include' must have a 'path' attribute. XML comment will be ignored. ''' <include/> ~~~~~~~~~~ ]]> </error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:C"> <summary> <!--warning BC42310: XML comment tag 'include' must have a 'path' attribute. XML comment will be ignored.--> <!--warning BC42310: XML comment tag 'include' must have a 'file' attribute. XML comment will be ignored.--> <!--warning BC42310: XML comment tag 'include' must have a 'file' attribute. XML comment will be ignored. warning BC42310: XML comment tag 'include' must have a 'path' attribute. XML comment will be ignored.--> </summary> </member> </members> </doc> ]]> </xml>, ensureEnglishUICulture:=True) End Sub <Fact> Public Sub ExtendedCref_BinaryOperator() ExtendedCref_BinaryOperatorCore(" &", "op_Concatenate", <errors></errors>) ExtendedCref_BinaryOperatorCore("+", "op_Addition", <errors> <![CDATA[ BC42309: XML comment has a tag with a 'cref' attribute 'Operator+(Clazz, String)' that could not be resolved. ''' <see cref="Operator+(Clazz, String)"/> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'Operator+(Clazz)' that could not be resolved. ''' <see cref="Operator+(Clazz)"/> ~~~~~~~~~~~~~~~~~~~~~~~ ]]> </errors>) ExtendedCref_BinaryOperatorCore("-", "op_Subtraction", <errors> <![CDATA[ BC42309: XML comment has a tag with a 'cref' attribute 'Operator-(Clazz, String)' that could not be resolved. ''' <see cref="Operator-(Clazz, String)"/> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'Operator-(Clazz)' that could not be resolved. ''' <see cref="Operator-(Clazz)"/> ~~~~~~~~~~~~~~~~~~~~~~~ ]]> </errors>) ExtendedCref_BinaryOperatorCore("*", "op_Multiply", <errors> <![CDATA[ BC42309: XML comment has a tag with a 'cref' attribute 'Operator*(Clazz, String)' that could not be resolved. ''' <see cref="Operator*(Clazz, String)"/> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'Operator*(Clazz)' that could not be resolved. ''' <see cref="Operator*(Clazz)"/> ~~~~~~~~~~~~~~~~~~~~~~~ ]]> </errors>) ExtendedCref_BinaryOperatorCore("/", "op_Division", <errors> <![CDATA[ BC42309: XML comment has a tag with a 'cref' attribute 'Operator/(Clazz, String)' that could not be resolved. ''' <see cref="Operator/(Clazz, String)"/> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'Operator/(Clazz)' that could not be resolved. ''' <see cref="Operator/(Clazz)"/> ~~~~~~~~~~~~~~~~~~~~~~~ ]]> </errors>) ExtendedCref_BinaryOperatorCore("\", "op_IntegerDivision", <errors> <![CDATA[ BC42309: XML comment has a tag with a 'cref' attribute 'Operator\(Clazz, String)' that could not be resolved. ''' <see cref="Operator\(Clazz, String)"/> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'Operator\(Clazz)' that could not be resolved. ''' <see cref="Operator\(Clazz)"/> ~~~~~~~~~~~~~~~~~~~~~~~ ]]> </errors>) ExtendedCref_BinaryOperatorCore("^", "op_Exponent", <errors> <![CDATA[ BC42309: XML comment has a tag with a 'cref' attribute 'Operator^(Clazz, String)' that could not be resolved. ''' <see cref="Operator^(Clazz, String)"/> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'Operator^(Clazz)' that could not be resolved. ''' <see cref="Operator^(Clazz)"/> ~~~~~~~~~~~~~~~~~~~~~~~ ]]> </errors>) ExtendedCref_BinaryOperatorCore("<<", "op_LeftShift", <errors></errors>) ExtendedCref_BinaryOperatorCore(">>", "op_RightShift", <errors></errors>) ExtendedCref_BinaryOperatorCore("=", "op_Equality", <errors> <![CDATA[ BC33033: Matching '<>' operator is required for 'Public Shared Operator =(a As Clazz, b As Integer) As Clazz'. Public Shared Operator =(a As Clazz, b As Integer) As Clazz ~ BC33033: Matching '<>' operator is required for 'Public Shared Operator =(a As Clazz, b As Integer?) As Clazz'. Public Shared Operator =(a As Clazz, b As Integer?) As Clazz ~ BC42309: XML comment has a tag with a 'cref' attribute 'Operator=(Clazz, String)' that could not be resolved. ''' <see cref="Operator=(Clazz, String)"/> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'Operator=(Clazz)' that could not be resolved. ''' <see cref="Operator=(Clazz)"/> ~~~~~~~~~~~~~~~~~~~~~~~ ]]> </errors>) ExtendedCref_BinaryOperatorCore("<>", "op_Inequality", <errors> <![CDATA[ BC33033: Matching '=' operator is required for 'Public Shared Operator <>(a As Clazz, b As Integer) As Clazz'. Public Shared Operator <>(a As Clazz, b As Integer) As Clazz ~~ BC33033: Matching '=' operator is required for 'Public Shared Operator <>(a As Clazz, b As Integer?) As Clazz'. Public Shared Operator <>(a As Clazz, b As Integer?) As Clazz ~~ ]]> </errors>) ExtendedCref_BinaryOperatorCore("<", "op_LessThan", <errors> <![CDATA[ BC33033: Matching '>' operator is required for 'Public Shared Operator <(a As Clazz, b As Integer) As Clazz'. Public Shared Operator <(a As Clazz, b As Integer) As Clazz ~ BC33033: Matching '>' operator is required for 'Public Shared Operator <(a As Clazz, b As Integer?) As Clazz'. Public Shared Operator <(a As Clazz, b As Integer?) As Clazz ~ ]]> </errors>) ExtendedCref_BinaryOperatorCore(">", "op_GreaterThan", <errors> <![CDATA[ BC33033: Matching '<' operator is required for 'Public Shared Operator >(a As Clazz, b As Integer) As Clazz'. Public Shared Operator >(a As Clazz, b As Integer) As Clazz ~ BC33033: Matching '<' operator is required for 'Public Shared Operator >(a As Clazz, b As Integer?) As Clazz'. Public Shared Operator >(a As Clazz, b As Integer?) As Clazz ~ ]]> </errors>) ExtendedCref_BinaryOperatorCore("<=", "op_LessThanOrEqual", <errors> <![CDATA[ BC33033: Matching '>=' operator is required for 'Public Shared Operator <=(a As Clazz, b As Integer) As Clazz'. Public Shared Operator <=(a As Clazz, b As Integer) As Clazz ~~ BC33033: Matching '>=' operator is required for 'Public Shared Operator <=(a As Clazz, b As Integer?) As Clazz'. Public Shared Operator <=(a As Clazz, b As Integer?) As Clazz ~~ ]]> </errors>) ExtendedCref_BinaryOperatorCore(">=", "op_GreaterThanOrEqual", <errors> <![CDATA[ BC33033: Matching '<=' operator is required for 'Public Shared Operator >=(a As Clazz, b As Integer) As Clazz'. Public Shared Operator >=(a As Clazz, b As Integer) As Clazz ~~ BC33033: Matching '<=' operator is required for 'Public Shared Operator >=(a As Clazz, b As Integer?) As Clazz'. Public Shared Operator >=(a As Clazz, b As Integer?) As Clazz ~~ ]]> </errors>) End Sub Private Sub ExtendedCref_BinaryOperatorCore(op As String, opName As String, errors As XElement) Dim invalidChars = op.Contains("<") OrElse op.Contains(">") OrElse op.Contains("&") Dim xmlSource = If(Not invalidChars, <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Public Class Clazz Public Shared Operator {0}(a As Clazz, b As Integer) As Clazz Return Nothing End Operator Public Shared Operator {0}(a As Clazz, b As Integer?) As Clazz Return Nothing End Operator ''' <see cref="{1}(Clazz, Integer) As Clazz"/> ''' <see cref="Operator{0}(Clazz, Integer)"/> ''' <see cref="Operator{0}(Clazz, String)"/> ''' <see cref="Operator{0}(Clazz, Int32?)"/> ''' <see cref="Operator{0}(Clazz)"/> ''' <see cref="Clazz.Operator{0}(Clazz, Integer)"/> ''' <see cref="Global.Clazz.Operator{0}(Clazz, Integer?)"/> Public Shared field As Integer End Class ]]> </file> </compilation>, <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Public Class Clazz Public Shared Operator {0}(a As Clazz, b As Integer) As Clazz Return Nothing End Operator Public Shared Operator {0}(a As Clazz, b As Integer?) As Clazz Return Nothing End Operator ''' <see cref="{1}(Clazz, Integer) As Clazz"/> ''' <see cref="Operator{0}(Clazz, Integer)"/> ''' <see cref="Operator{0}(Clazz, Int32?)"/> ''' <see cref="Clazz.Operator{0}(Clazz, Integer)"/> ''' <see cref="Global.Clazz.Operator{0}(Clazz, Integer?)"/> Public Shared field As Integer End Class ]]> </file> </compilation>) Dim xmlDoc = If(Not invalidChars, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="F:Clazz.field"> <see cref="M:Clazz.{0}(Clazz,System.Int32)"/> <see cref="M:Clazz.{0}(Clazz,System.Int32)"/> <see cref="!:Operator{1}(Clazz, String)"/> <see cref="M:Clazz.{0}(Clazz,System.Nullable{{System.Int32}})"/> <see cref="!:Operator{1}(Clazz)"/> <see cref="M:Clazz.{0}(Clazz,System.Int32)"/> <see cref="M:Clazz.{0}(Clazz,System.Nullable{{System.Int32}})"/> </member> </members> </doc> ]]> </xml>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="F:Clazz.field"> <see cref="M:Clazz.{0}(Clazz,System.Int32)"/> <see cref="M:Clazz.{0}(Clazz,System.Int32)"/> <see cref="M:Clazz.{0}(Clazz,System.Nullable{{System.Int32}})"/> <see cref="M:Clazz.{0}(Clazz,System.Int32)"/> <see cref="M:Clazz.{0}(Clazz,System.Nullable{{System.Int32}})"/> </member> </members> </doc> ]]> </xml>) Dim compilation = CompileCheckDiagnosticsAndXmlDocument( FormatSourceXml(xmlSource, op, opName), FormatXmlSimple(errors, op, If(op.Length = 1, "~", "~~")), FormatXmlSimple(xmlDoc, opName, op)) Dim crefNode = CrefFinder.FindCref(compilation.SyntaxTrees(0)) Dim model = compilation.GetSemanticModel(compilation.SyntaxTrees(0)) Assert.NotNull(crefNode) Dim info = model.GetSymbolInfo(crefNode) Assert.NotNull(info.Symbol) Assert.Equal(String.Format("Function Clazz.{0}(a As Clazz, b As System.Int32) As Clazz", opName), info.Symbol.ToTestDisplayString()) End Sub <Fact> Public Sub ExtendedCrefParsingTest() ParseExtendedCref("Int32.ToString", forceNoErrors:=True) ParseExtendedCref("Int32.ToString()", forceNoErrors:=False) ParseExtendedCref("Int32.ToString(String, Integer)", forceNoErrors:=False) ParseExtendedCref("Int32.ToString(ByVal String, ByRef Integer)", forceNoErrors:=False) ParseExtendedCref("Int32.ToString(ByVal ByRef String, Integer) As Integer", checkErrors:= <error> <![CDATA[ BC42309: XML comment has a tag with a 'cref' attribute 'Int32.ToString(ByVal ByRef String, Integer) As Integer' that could not be resolved. ''' <see cref="Int32.ToString(ByVal ByRef String, Integer) As Integer"/> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]> </error>) ParseExtendedCref("Int32.ToString(String, Integer) As Integer", checkErrors:= <error> <![CDATA[ BC42309: XML comment has a tag with a 'cref' attribute 'Int32.ToString(String, Integer) As Integer' that could not be resolved. ''' <see cref="Int32.ToString(String, Integer) As Integer"/> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]> </error>) ParseExtendedCref("Operator IsTrue(String)", forceNoErrors:=False) ParseExtendedCref("Operator IsFalse(String)", forceNoErrors:=False) ParseExtendedCref("Operator Not(String)", forceNoErrors:=False) ParseExtendedCref("Operator+(String, Integer)", forceNoErrors:=False) ParseExtendedCref("Operator -(String, Integer)", forceNoErrors:=False) ParseExtendedCref("Operator*(String, Integer)", forceNoErrors:=False) ParseExtendedCref("Operator /(String, Integer)", forceNoErrors:=False) ParseExtendedCref("Operator^(String, Integer)", forceNoErrors:=False) ParseExtendedCref("Operator \(String, Integer)", forceNoErrors:=False) ParseExtendedCref("Operator&(String, Integer)", forceNoErrors:=False) ParseExtendedCref("Operator<<(String, Integer)", forceNoErrors:=False) ParseExtendedCref("Operator >> (String, Integer)", forceNoErrors:=False) ParseExtendedCref("Operator Mod(String, Integer)", forceNoErrors:=False) ParseExtendedCref("Operator Or(String, Integer)", forceNoErrors:=False) ParseExtendedCref("Operator Xor(String, Integer)", forceNoErrors:=False) ParseExtendedCref("Operator And(String, Integer)", forceNoErrors:=False) ParseExtendedCref("Operator Like(String, Integer)", forceNoErrors:=False) ParseExtendedCref("Operator =(String, Integer)", forceNoErrors:=False) ParseExtendedCref("Operator <>(String, Integer)", forceNoErrors:=False) ParseExtendedCref("Operator <(String, Integer)", forceNoErrors:=False) ParseExtendedCref("Operator <=(String, Integer)", forceNoErrors:=False) ParseExtendedCref("Operator >(String, Integer)", forceNoErrors:=False) ParseExtendedCref("Operator >=(String, Integer)", forceNoErrors:=False) ParseExtendedCref("Operator \(String, Integer) As Integer", checkErrors:= <error> <![CDATA[ BC42309: XML comment has a tag with a 'cref' attribute 'Operator \(String, Integer) As Integer' that could not be resolved. ''' <see cref="Operator \(String, Integer) As Integer"/> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]> </error>) ParseExtendedCref("Operator Or(String, Integer).Name", checkErrors:= <error> <![CDATA[ BC42309: XML comment has a tag with a 'cref' attribute 'Operator Or(String, Integer).Name' that could not be resolved. ''' <see cref="Operator Or(String, Integer).Name"/> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]> </error>, overrideCrefText:="Operator Or(String, Integer)") ParseExtendedCref("Clazz.Operator >=(String, Integer)", forceNoErrors:=False) ParseExtendedCref("Clazz.Operator ctype(String)", forceNoErrors:=False) ParseExtendedCref("Clazz.Operator ctype(String) as Integer", forceNoErrors:=False) ParseExtendedCref("New", forceNoErrors:=False) ParseExtendedCref("[new]", forceNoErrors:=False) ParseExtendedCref("New()", forceNoErrors:=False) ParseExtendedCref("[new]()", forceNoErrors:=False) ParseExtendedCref("Clazz.New", forceNoErrors:=False) ParseExtendedCref("Clazz.[new]", forceNoErrors:=False) ParseExtendedCref("Clazz.New()", forceNoErrors:=False) ParseExtendedCref("Clazz.[new]()", forceNoErrors:=False) ParseExtendedCref("Clazz.[new]() As Integer", forceNoErrors:=False) ParseExtendedCref("String.ToString", overrideCrefText:="String", forceNoErrors:=True) ParseExtendedCref("String.ToString()", overrideCrefText:="String", forceNoErrors:=True) ParseExtendedCref("String.ToString(String, Integer)", overrideCrefText:="String", forceNoErrors:=True) ParseExtendedCref("sYSTEM.String") ParseExtendedCref("sYSTEM.String.", checkErrors:= <error> <![CDATA[ BC42309: XML comment has a tag with a 'cref' attribute 'sYSTEM.String.' that could not be resolved. ''' <see cref="sYSTEM.String."/> ~~~~~~~~~~~~~~~~~~~~~ ]]> </error>) ParseExtendedCref("Global.sYSTEM.String") ParseExtendedCref("Global", checkErrors:= <error> <![CDATA[ BC42309: XML comment has a tag with a 'cref' attribute 'Global' that could not be resolved. ''' <see cref="Global"/> ~~~~~~~~~~~~~ ]]> </error>) End Sub Private Sub ParseExtendedCref(cref As String, Optional checkErrors As XElement = Nothing, Optional overrideCrefText As String = Nothing, Optional forceNoErrors As Boolean = False) Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System ''' <see cref="{0}"/> Module Program End Module ]]> </file> </compilation> Dim compilation = CompileCheckDiagnosticsAndXmlDocument(FormatSourceXml(xmlSource, cref), If(forceNoErrors, <errors></errors>, checkErrors)) Dim crefNode = CrefFinder.FindCref(compilation.SyntaxTrees(0)) Assert.NotNull(crefNode) Assert.Equal(If(overrideCrefText, cref.Trim).Trim, crefNode.ToString()) End Sub <Fact> Private Sub GetAliasInfo_Namespace() Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Imports aNamespace = System.Collections.Generic ''' <see cref="aNamespace"/> Public Class Clazz End Class ]]> </file> </compilation> Dim xmlDoc = <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:Clazz"> <see cref="N:System.Collections.Generic"/> </member> </members> </doc> ]]> </xml> Dim compilation = CompileCheckDiagnosticsAndXmlDocument(xmlSource, <errors></errors>, xmlDoc) Dim model = compilation.GetSemanticModel(compilation.SyntaxTrees(0)) Dim crefNode = CrefFinder.FindCref(compilation.SyntaxTrees(0)) Assert.NotNull(crefNode) Dim info = model.GetSymbolInfo(crefNode) Assert.NotNull(info.Symbol) Assert.Equal("System.Collections.Generic", info.Symbol.ToTestDisplayString()) CheckAllAliases(model, crefNode, New AliasInfo("aNamespace", "System.Collections.Generic")) End Sub <WorkItem(757110, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/757110")> <Fact> Public Sub NoAssemblyElementForNetModule() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="EmptyCref"> <file name="a.vb"> <![CDATA[ Imports System ''' <summary> ''' Test ''' </summary> Class E End Class ]]> </file> </compilation>, TestOptions.ReleaseModule) CheckXmlDocument(comp, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <members> <member name="T:E"> <summary> Test </summary> </member> </members> </doc> ]]> </xml>) End Sub <Fact> Private Sub GetAliasInfo_Type() Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Imports aType = System.Collections.Generic.List(Of Integer) ''' <see cref="aType"/> Public Class Clazz End Class ]]> </file> </compilation> Dim xmlDoc = <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:Clazz"> <see cref="T:System.Collections.Generic.List`1"/> </member> </members> </doc> ]]> </xml> Dim compilation = CompileCheckDiagnosticsAndXmlDocument(xmlSource, <errors></errors>, xmlDoc) Dim model = compilation.GetSemanticModel(compilation.SyntaxTrees(0)) Dim crefNode = CrefFinder.FindCref(compilation.SyntaxTrees(0)) Assert.NotNull(crefNode) Dim info = model.GetSymbolInfo(crefNode) Assert.NotNull(info.Symbol) Assert.Equal("System.Collections.Generic.List(Of System.Int32)", info.Symbol.ToTestDisplayString()) CheckAllAliases(model, crefNode, New AliasInfo("aType", "System.Collections.Generic.List(Of Integer)")) End Sub <Fact> Private Sub GetAliasInfo_NamespaceAndType() Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Imports aNamespace = System.Collections.Generic ''' <see cref="aNamespace.List(Of T)"/> Public Class Clazz End Class ]]> </file> </compilation> Dim xmlDoc = <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:Clazz"> <see cref="T:System.Collections.Generic.List`1"/> </member> </members> </doc> ]]> </xml> Dim compilation = CompileCheckDiagnosticsAndXmlDocument(xmlSource, <errors></errors>, xmlDoc) Dim model = compilation.GetSemanticModel(compilation.SyntaxTrees(0)) Dim crefNode = CrefFinder.FindCref(compilation.SyntaxTrees(0)) Assert.NotNull(crefNode) Dim info = model.GetSymbolInfo(crefNode) Assert.NotNull(info.Symbol) Assert.Equal("System.Collections.Generic.List(Of T)", info.Symbol.ToTestDisplayString()) CheckAllAliases(model, crefNode, New AliasInfo("aNamespace", "System.Collections.Generic"), New AliasInfo("T", Nothing)) End Sub <Fact> Private Sub GetAliasInfo_TypeAndMethodWithSignature() Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Imports aType = System.Collections.Generic.List(Of Integer) ''' <see cref="aType.ToString()"/> Public Class Clazz End Class ]]> </file> </compilation> Dim xmlDoc = <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:Clazz"> <see cref="M:System.Object.ToString"/> </member> </members> </doc> ]]> </xml> Dim compilation = CompileCheckDiagnosticsAndXmlDocument(xmlSource, <errors></errors>, xmlDoc) Dim model = compilation.GetSemanticModel(compilation.SyntaxTrees(0)) Dim crefNode = CrefFinder.FindCref(compilation.SyntaxTrees(0)) Assert.NotNull(crefNode) Dim info = model.GetSymbolInfo(crefNode) Assert.NotNull(info.Symbol) Assert.Equal("Function System.Object.ToString() As System.String", info.Symbol.ToTestDisplayString()) CheckAllAliases(model, crefNode, New AliasInfo("aType", "System.Collections.Generic.List(Of Integer)"), New AliasInfo("ToString", Nothing)) End Sub <Fact> Private Sub GetAliasInfo_TypeAndMethodCompat() Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Imports aType = System.Collections.Generic.List(Of Integer) ''' <see cref="aType.ToString"/> Public Class Clazz End Class ]]> </file> </compilation> Dim xmlDoc = <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:Clazz"> <see cref="M:System.Object.ToString"/> </member> </members> </doc> ]]> </xml> Dim compilation = CompileCheckDiagnosticsAndXmlDocument(xmlSource, <errors></errors>, xmlDoc) Dim model = compilation.GetSemanticModel(compilation.SyntaxTrees(0)) Dim crefNode = CrefFinder.FindCref(compilation.SyntaxTrees(0)) Assert.NotNull(crefNode) Dim info = model.GetSymbolInfo(crefNode) Assert.NotNull(info.Symbol) Assert.Equal("Function System.Object.ToString() As System.String", info.Symbol.ToTestDisplayString()) CheckAllAliases(model, crefNode, New AliasInfo("aType", "System.Collections.Generic.List(Of Integer)"), New AliasInfo("ToString", Nothing)) End Sub <WorkItem(568006, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/568006")> <Fact> Public Sub Inaccessible1() Dim source = <compilation> <file name="test.vb"><![CDATA[ ''' <summary> ''' See <see cref="C.M"/>. ''' </summary> Class A End Class Class C Private Sub M() End Sub End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, parseOptions:=s_optionsDiagnoseDocComments) ' Compat fix: match dev11 with inaccessible lookup compilation.AssertNoDiagnostics() End Sub <WorkItem(568006, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/568006")> <Fact> Public Sub Inaccessible2() Dim source = <compilation> <file name="test.vb"><![CDATA[ ''' <summary> ''' See <see cref="C.Inner.M"/>. ''' </summary> Class A End Class Class C Private Class Inner Private Sub M() End Sub End Class End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, parseOptions:=s_optionsDiagnoseDocComments) ' Compat fix: match dev11 with inaccessible lookup compilation.AssertNoDiagnostics() End Sub <WorkItem(568006, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/568006")> <Fact> Public Sub Inaccessible3() Dim lib1Source = <compilation name="A"> <file name="a.vb"> Friend Class C End Class </file> </compilation> Dim lib2Source = <compilation name="B"> <file name="b.vb"> Public Class C End Class </file> </compilation> Dim source = <compilation> <file name="test.vb"><![CDATA[ ''' <summary> ''' See <see cref="C"/>. ''' </summary> Public Class Test End Class ]]> </file> </compilation> Dim lib1Ref = CreateCompilationWithMscorlib40(lib1Source).EmitToImageReference() Dim lib2Ref = CreateCompilationWithMscorlib40(lib2Source).EmitToImageReference() Dim compilation = CreateCompilationWithMscorlib40AndReferences(source, {lib1Ref, lib2Ref}, parseOptions:=s_optionsDiagnoseDocComments) Dim tree = compilation.SyntaxTrees.Single() Dim model = compilation.GetSemanticModel(tree) Dim crefSyntax = tree.GetRoot().DescendantNodes(descendIntoTrivia:=True).OfType(Of CrefReferenceSyntax).Single() ' Break: In dev11 the accessible symbol is preferred. We produce an ambiguity Dim symbolInfo = model.GetSymbolInfo(crefSyntax) Dim symbols = symbolInfo.CandidateSymbols Assert.Equal(CandidateReason.Ambiguous, symbolInfo.CandidateReason) Assert.Equal(2, symbols.Length) Assert.Equal("A", symbols(0).ContainingAssembly.Name) Assert.Equal("B", symbols(1).ContainingAssembly.Name) End Sub <WorkItem(568006, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/568006")> <WorkItem(709199, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/709199")> <Fact> Public Sub ProtectedInstanceBaseMember() Dim source = <compilation> <file name="test.vb"><![CDATA[ Class Base Protected F As Integer End Class ''' Accessible: <see cref="Base.F"/> Class Derived : Inherits Base End Class ''' Inaccessible: <see cref="Base.F"/> Class Other End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, parseOptions:=s_optionsDiagnoseDocComments) compilation.AssertNoDiagnostics() Dim tree = compilation.SyntaxTrees.Single() Dim model = compilation.GetSemanticModel(tree) Dim crefSyntax = tree.GetRoot().DescendantNodes(descendIntoTrivia:=True).OfType(Of CrefReferenceSyntax).First() Dim expectedSymbol = compilation.GlobalNamespace.GetMember(Of NamedTypeSymbol)("Base").GetMember(Of FieldSymbol)("F") Dim actualSymbol = model.GetSymbolInfo(crefSyntax).Symbol Assert.Equal(expectedSymbol, actualSymbol) End Sub <WorkItem(568006, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/568006")> <WorkItem(709199, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/709199")> <Fact> Public Sub ProtectedSharedBaseMember() Dim source = <compilation> <file name="test.vb"><![CDATA[ Class Base Protected Shared F As Integer End Class ''' Accessible: <see cref="Base.F"/> Class Derived : Inherits Base End Class ''' Inaccessible: <see cref="Base.F"/> Class Other End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, parseOptions:=s_optionsDiagnoseDocComments) compilation.AssertNoDiagnostics() Dim tree = compilation.SyntaxTrees.Single() Dim model = compilation.GetSemanticModel(tree) Dim crefSyntax = tree.GetRoot().DescendantNodes(descendIntoTrivia:=True).OfType(Of CrefReferenceSyntax).First() Dim expectedSymbol = compilation.GlobalNamespace.GetMember(Of NamedTypeSymbol)("Base").GetMember(Of FieldSymbol)("F") Dim actualSymbol = model.GetSymbolInfo(crefSyntax).Symbol Assert.Equal(expectedSymbol, actualSymbol) End Sub <WorkItem(768624, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768624")> <Fact> Public Sub CrefsOnDelegate() Dim source = <compilation> <file name="test.vb"><![CDATA[ ''' <see cref="T"/> ''' <see cref="p"/> ''' <see cref="Invoke"/> ''' <see cref="ToString"/> Delegate Sub D(Of T)(p As T) ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, parseOptions:=s_optionsDiagnoseDocComments) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC42309: XML comment has a tag with a 'cref' attribute 'T' that could not be resolved. ''' <see cref="T"/> ~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'p' that could not be resolved. ''' <see cref="p"/> ~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'Invoke' that could not be resolved. ''' <see cref="Invoke"/> ~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'ToString' that could not be resolved. ''' <see cref="ToString"/> ~~~~~~~~~~~~~~~ ]]></errors>) End Sub <WorkItem(768624, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768624")> <Fact> Public Sub TypeParametersOfAssociatedSymbol() Dim source = <compilation> <file name="test.vb"><![CDATA[ ''' <see cref='T'/> Class C(Of T) ''' <see cref='U'/> Sub M(Of U)() End Sub End Class ''' <see cref='V'/> Delegate Sub D(Of V)() ]]> </file> </compilation> ' NOTE: Unlike C#, VB allows crefs to type parameters. Dim compilation = CreateCompilationWithMscorlib40(source, parseOptions:=s_optionsDiagnoseDocComments) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC42375: XML comment has a tag with a 'cref' attribute 'T' that bound to a type parameter. Use the <typeparamref> tag instead. ''' <see cref='T'/> ~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'U' that could not be resolved. ''' <see cref='U'/> ~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'V' that could not be resolved. ''' <see cref='V'/> ~~~~~~~~ ]]></errors>) Dim tree = compilation.SyntaxTrees.Single() Dim model = compilation.GetSemanticModel(tree) Dim crefSyntaxes = tree.GetRoot().DescendantNodes(descendIntoTrivia:=True).OfType(Of CrefReferenceSyntax).ToArray() Dim [class] = compilation.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C") Dim method = [class].GetMember(Of MethodSymbol)("M") Dim [delegate] = compilation.GlobalNamespace.GetMember(Of NamedTypeSymbol)("D") Dim info0 As SymbolInfo = model.GetSymbolInfo(crefSyntaxes(0)) Assert.Null(info0.Symbol) ' As in dev11. Assert.Equal([class].TypeParameters.Single(), info0.CandidateSymbols.Single()) Assert.Equal(CandidateReason.NotReferencable, info0.CandidateReason) Assert.True(model.GetSymbolInfo(crefSyntaxes(1)).IsEmpty) Assert.True(model.GetSymbolInfo(crefSyntaxes(2)).IsEmpty) End Sub <WorkItem(768624, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768624")> <Fact> Public Sub MembersOfAssociatedSymbol() Dim source = <compilation> <file name="test.vb"><![CDATA[ ''' <see cref='F'/> Class C Private F As Integer End Class ''' <see cref='F'/> Structure S Private F As Integer End Structure ''' <see cref='P'/> Interface I Property P As Integer End Interface ''' <see cref='F'/> Module M Private F As Integer End Module ''' <see cref='F'/> Enum E F End Enum ]]> </file> </compilation> ' None of these work in dev11. Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, parseOptions:=s_optionsDiagnoseDocComments) compilation.AssertNoDiagnostics() Dim tree = compilation.SyntaxTrees.Single() Dim model = compilation.GetSemanticModel(tree) Dim crefSyntaxes = tree.GetRoot().DescendantNodes(descendIntoTrivia:=True).OfType(Of CrefReferenceSyntax).ToArray() Assert.Equal("C.F As System.Int32", model.GetSymbolInfo(crefSyntaxes(0)).Symbol.ToTestDisplayString()) Assert.Equal("S.F As System.Int32", model.GetSymbolInfo(crefSyntaxes(1)).Symbol.ToTestDisplayString()) Assert.Equal("Property I.P As System.Int32", model.GetSymbolInfo(crefSyntaxes(2)).Symbol.ToTestDisplayString()) Assert.Equal("M.F As System.Int32", model.GetSymbolInfo(crefSyntaxes(3)).Symbol.ToTestDisplayString()) Assert.Equal("E.F", model.GetSymbolInfo(crefSyntaxes(4)).Symbol.ToTestDisplayString()) End Sub <WorkItem(768624, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768624")> <Fact> Public Sub InnerVersusOuter() Dim source = <compilation> <file name="test.vb"><![CDATA[ Class Outer Private F As Integer ''' <see cref='F'/> Class Inner Private F As Integer End Class End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, parseOptions:=s_optionsDiagnoseDocComments) compilation.AssertNoDiagnostics() Dim tree = compilation.SyntaxTrees.Single() Dim model = compilation.GetSemanticModel(tree) Dim crefSyntax = tree.GetRoot().DescendantNodes(descendIntoTrivia:=True).OfType(Of CrefReferenceSyntax).Single() ' BREAK: In dev11, it refers to Outer.F. Assert.Equal("Outer.Inner.F As System.Int32", model.GetSymbolInfo(crefSyntax).Symbol.ToTestDisplayString()) End Sub <WorkItem(531505, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531505")> <Fact> Private Sub Pia() Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ ''' <see cref='FooStruct'/> ''' <see cref='FooStruct.NET'/> Public Class C End Class ]]> </file> </compilation> Dim xmlDoc = <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:C"> <see cref='T:FooStruct'/> <see cref='F:FooStruct.NET'/> </member> </members> </doc> ]]> </xml> Dim reference1 = TestReferences.SymbolsTests.NoPia.GeneralPia.WithEmbedInteropTypes(False) Dim reference2 = TestReferences.SymbolsTests.NoPia.GeneralPia.WithEmbedInteropTypes(True) Dim comp1 = CompileCheckDiagnosticsAndXmlDocument(xmlSource, <errors></errors>, xmlDoc, additionalRefs:={reference1}) Dim comp2 = CompileCheckDiagnosticsAndXmlDocument(xmlSource, <errors></errors>, xmlDoc, additionalRefs:={reference2}) Dim validator As Action(Of ModuleSymbol) = Sub(m As ModuleSymbol) DirectCast(m, PEModuleSymbol).Module.PretendThereArentNoPiaLocalTypes() ' No reference added. AssertEx.None(m.GetReferencedAssemblies(), Function(id) id.Name.Contains("GeneralPia")) ' No type embedded. Assert.Equal(0, m.GlobalNamespace.GetMembers("FooStruct").Length) End Sub CompileAndVerify(comp1, symbolValidator:=validator) CompileAndVerify(comp2, symbolValidator:=validator) End Sub <WorkItem(790978, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/790978")> <Fact> Public Sub SingleSymbol() Dim source = <compilation> <file name="a.vb"> <![CDATA[ ''' <summary> ''' summary information ''' </summary> ''' <remarks>nothing</remarks> Public Class C End Class ]]> </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(source, parseOptions:=s_optionsDiagnoseDocComments) comp.VerifyDiagnostics() Dim expectedXmlText = <![CDATA[ <member name="T:C"> <summary> summary information </summary> <remarks>nothing</remarks> </member> ]]>.Value.Replace(vbLf, Environment.NewLine).Trim Dim sourceSymbol = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C") Assert.Equal(expectedXmlText, sourceSymbol.GetDocumentationCommentXml()) Dim metadataRef = comp.EmitToImageReference() Dim comp2 = CreateEmptyCompilationWithReferences(<source/>, {metadataRef}) Dim metadataSymbol = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C") Assert.Equal(expectedXmlText, metadataSymbol.GetDocumentationCommentXml()) End Sub <Fact, WorkItem(908893, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908893")> Private Sub GenericTypeWithinGenericType() Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Public Class ClazzA(Of A) ''' <see cref="Test"/> Public Class ClazzB(Of B) Public Sub Test(x as ClazzB(Of B)) End Sub End Class End Class ]]> </file> </compilation> Dim xmlDoc = <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:ClazzA`1.ClazzB`1"> <see cref="M:ClazzA`1.ClazzB`1.Test(ClazzA{`0}.ClazzB{`1})"/> </member> </members> </doc> ]]> </xml> Dim compilation = CompileCheckDiagnosticsAndXmlDocument(xmlSource, <errors> </errors>, xmlDoc) End Sub #Region "Helpers" Private Structure AliasInfo Public ReadOnly Name As String Public ReadOnly Target As String Public Sub New(name As String, target As String) Me.Name = name Me.Target = target End Sub End Structure Private Sub CheckAllAliases(model As SemanticModel, cref As CrefReferenceSyntax, ParamArray expected As AliasInfo()) Dim names = SyntaxNodeFinder.FindNodes(Of IdentifierNameSyntax)(cref, SyntaxKind.IdentifierName) Assert.Equal(expected.Length, names.Count) For i = 0 To names.Count - 1 Dim e = expected(i) Dim sym = names(i) Assert.Equal(e.Name, sym.ToString().Trim()) Dim actual = model.GetAliasInfo(sym) If e.Target Is Nothing Then Assert.Null(actual) Else Assert.Equal(e.Target, actual.Target.ToDisplayString) End If Next End Sub Private Class CrefFinder Public Shared Function FindCref(tree As SyntaxTree) As CrefReferenceSyntax Dim crefs = SyntaxNodeFinder.FindNodes(Of CrefReferenceSyntax)(tree.GetRoot(), SyntaxKind.CrefReference) Return If(crefs.Count > 0, crefs(0), Nothing) End Function Public Shared Function FindAllCrefs(tree As SyntaxTree) As List(Of CrefReferenceSyntax) Return SyntaxNodeFinder.FindNodes(Of CrefReferenceSyntax)(tree.GetRoot(), SyntaxKind.CrefReference) End Function End Class Private Shared Function StringReplace(obj As Object, what As String, [with] As String) As Object Dim str = TryCast(obj, String) Return If(str Is Nothing, obj, str.Replace(what, [with])) End Function Private Shared Function AsXmlCommentText(file As TempFile) As String Return TestHelpers.AsXmlCommentText(file.ToString()) End Function Private Function FormatSourceXml(xml As XElement, ParamArray obj() As Object) As XElement For Each file In xml.<file> file.Value = String.Format(file.Value, obj) Next Return xml End Function Private Function FormatXmlSimple(xml As XElement, ParamArray obj() As Object) As XElement xml.Value = String.Format(xml.Value, obj) Return xml End Function Private Shared Function FilterOfSymbolKindOnly(symbols As ImmutableArray(Of ISymbol), ParamArray kinds() As SymbolKind) As ImmutableArray(Of ISymbol) Dim filter As New HashSet(Of SymbolKind)(kinds) Return (From s In symbols Where filter.Contains(s.Kind) Select s).AsImmutable() End Function Private Shared Sub AssertLookupResult(actual As ImmutableArray(Of ISymbol), ParamArray expected() As String) AssertStringArraysEqual(expected, (From s In actual Select s.ToTestDisplayString()).ToArray) End Sub Private Function CheckSymbolInfoOnly(model As SemanticModel, syntax As ExpressionSyntax, ParamArray expected() As String) As ImmutableArray(Of ISymbol) EnsureSymbolInfoOnCrefReference(model, syntax) Dim actual = model.GetSymbolInfo(syntax) If expected.Length = 0 Then Assert.True(actual.IsEmpty) ElseIf expected.Length = 1 Then Assert.NotNull(actual.Symbol) Assert.Equal(expected(0), actual.Symbol.ToTestDisplayString) Else Assert.Equal(CandidateReason.Ambiguous, actual.CandidateReason) AssertStringArraysEqual(expected, (From s In actual.CandidateSymbols Select s.ToTestDisplayString()).ToArray) End If Dim typeInfo = model.GetTypeInfo(syntax) If actual.Symbol IsNot Nothing AndAlso actual.Symbol.Kind = SymbolKind.TypeParameter Then ' Works everywhere since we want it to work in name attributes. Assert.Equal(actual.Symbol, typeInfo.Type) Else Assert.Null(typeInfo.Type) End If Return actual.GetAllSymbols() End Function Private Function GetEnclosingCrefReference(syntax As ExpressionSyntax) As CrefReferenceSyntax Dim node As VisualBasicSyntaxNode = syntax While node IsNot Nothing AndAlso node.Kind <> SyntaxKind.CrefReference node = node.Parent End While Return DirectCast(node, CrefReferenceSyntax) End Function Private Sub EnsureSymbolInfoOnCrefReference(model As SemanticModel, syntax As ExpressionSyntax) Dim cref = GetEnclosingCrefReference(syntax) If cref Is Nothing Then Return End If Debug.Assert(cref.Signature IsNot Nothing OrElse cref.AsClause Is Nothing) If cref.Signature IsNot Nothing Then Return End If Dim fromName = model.GetSymbolInfo(cref.Name) Dim fromCref = model.GetSymbolInfo(cref) Assert.Equal(fromCref.CandidateReason, fromName.CandidateReason) AssertStringArraysEqual((From s In fromName.GetAllSymbols() Select s.ToTestDisplayString()).ToArray, (From s In fromCref.GetAllSymbols() Select s.ToTestDisplayString()).ToArray) End Sub Private Function CheckTypeParameterCrefSymbolInfoAndTypeInfo(model As SemanticModel, syntax As ExpressionSyntax, Optional expected As String = Nothing) As ImmutableArray(Of Symbol) EnsureSymbolInfoOnCrefReference(model, syntax) Dim actual = model.GetSymbolInfo(syntax) Dim typeInfo = model.GetTypeInfo(syntax) If expected Is Nothing Then Assert.True(actual.IsEmpty) Assert.Null(typeInfo.Type) Return ImmutableArray.Create(Of Symbol)() Else Assert.Equal(CandidateReason.NotReferencable, actual.CandidateReason) Dim symbol = actual.CandidateSymbols.Single() Assert.NotNull(symbol) Assert.Equal(expected, symbol.ToTestDisplayString) Assert.NotNull(typeInfo.Type) Assert.Equal(typeInfo.Type, symbol) Return ImmutableArray.Create(DirectCast(symbol, Symbol)) End If End Function Private Function CheckSymbolInfoAndTypeInfo(model As SemanticModel, syntax As ExpressionSyntax, ParamArray expected() As String) As ImmutableArray(Of Symbol) EnsureSymbolInfoOnCrefReference(model, syntax) Dim actual = model.GetSymbolInfo(syntax) Dim typeInfo = model.GetTypeInfo(syntax) If expected.Length = 0 Then Assert.True(actual.IsEmpty) Assert.Null(typeInfo.Type) Return ImmutableArray.Create(Of Symbol)() ElseIf expected.Length = 1 Then Assert.NotNull(actual.Symbol) Assert.Equal(expected(0), actual.Symbol.ToTestDisplayString) Assert.NotNull(typeInfo.Type) Assert.Equal(typeInfo.Type, actual.Symbol) Return ImmutableArray.Create(Of Symbol)(DirectCast(actual.Symbol, Symbol)) Else Assert.Equal(CandidateReason.Ambiguous, actual.CandidateReason) AssertStringArraysEqual(expected, (From s In actual.CandidateSymbols Select s.ToTestDisplayString()).ToArray) Assert.Null(typeInfo.Type) Return actual.CandidateSymbols.Cast(Of Symbol).ToImmutableArray() End If End Function Private Shared Sub AssertStringArraysEqual(a() As String, b() As String) Assert.NotNull(a) Assert.NotNull(b) Assert.Equal(StringArraysToSortedString(a), StringArraysToSortedString(b)) End Sub Private Shared Function StringArraysToSortedString(a() As String) As String Dim builder As New StringBuilder Array.Sort(a) For Each s In a builder.AppendLine(s) Next Return builder.ToString() End Function Private Sub TestSymbolAndTypeInfoForType(model As SemanticModel, syntax As TypeSyntax, expected As ISymbol) EnsureSymbolInfoOnCrefReference(model, syntax) Dim expSymInfo = model.GetSymbolInfo(syntax) Assert.NotNull(expSymInfo.Symbol) Assert.Same(expected, expSymInfo.Symbol.OriginalDefinition) Dim expTypeInfo = model.GetTypeInfo(syntax) Assert.Equal(expected, expTypeInfo.Type.OriginalDefinition) Dim conversion = model.GetConversion(syntax) Assert.Equal(ConversionKind.Identity, conversion.Kind) End Sub Private Shared Function FindNodesOfTypeFromText(Of TNode As VisualBasicSyntaxNode)(tree As SyntaxTree, textToFind As String) As TNode() Dim text As String = tree.GetText().ToString() Dim list As New List(Of TNode) Dim position As Integer = text.IndexOf(textToFind, StringComparison.Ordinal) While position >= 0 Dim token As SyntaxToken = tree.GetRoot().FindToken(position, True) If token.ValueText = textToFind Then Dim node = TryCast(token.Parent, TNode) If node IsNot Nothing Then list.Add(node) End If End If position = text.IndexOf(textToFind, position + 1, StringComparison.Ordinal) End While Return list.ToArray() End Function Private Shared Function CompileCheckDiagnosticsAndXmlDocument( sources As XElement, errors As XElement, Optional expectedDocXml As XElement = Nothing, Optional withDiagnostics As Boolean = True, Optional stringMapper As Func(Of Object, Object) = Nothing, Optional additionalRefs As MetadataReference() = Nothing, Optional ensureEnglishUICulture As Boolean = False ) As VisualBasicCompilation Dim parseOptions As VisualBasicParseOptions = VisualBasicParseOptions.Default.WithDocumentationMode( If(withDiagnostics, DocumentationMode.Diagnose, DocumentationMode.Parse)) Dim compilation = CreateCompilation(sources, additionalRefs, TestOptions.ReleaseDll.WithXmlReferenceResolver(XmlFileResolver.Default), parseOptions) If errors IsNot Nothing Then Dim diagnostics As Diagnostic() Dim saveUICulture As Globalization.CultureInfo = Nothing If ensureEnglishUICulture Then Dim preferred = Roslyn.Test.Utilities.EnsureEnglishUICulture.PreferredOrNull If preferred Is Nothing Then ensureEnglishUICulture = False Else saveUICulture = Threading.Thread.CurrentThread.CurrentUICulture Threading.Thread.CurrentThread.CurrentUICulture = preferred End If End If Try diagnostics = compilation.GetDiagnostics(CompilationStage.Compile).ToArray() Finally If ensureEnglishUICulture Then Threading.Thread.CurrentThread.CurrentUICulture = saveUICulture End If End Try CompilationUtils.AssertTheseDiagnostics(diagnostics.AsImmutable(), errors) End If If expectedDocXml IsNot Nothing Then CheckXmlDocument(compilation, expectedDocXml, stringMapper, ensureEnglishUICulture) End If Return compilation End Function Private Shared Sub CheckXmlDocument( compilation As VisualBasicCompilation, expectedDocXml As XElement, Optional stringMapper As Func(Of Object, Object) = Nothing, Optional ensureEnglishUICulture As Boolean = False ) Assert.NotNull(expectedDocXml) Using output = New MemoryStream() Using xml = New MemoryStream() Dim emitResult As CodeAnalysis.Emit.EmitResult Dim saveUICulture As Globalization.CultureInfo = Nothing If ensureEnglishUICulture Then Dim preferred = Roslyn.Test.Utilities.EnsureEnglishUICulture.PreferredOrNull If preferred Is Nothing Then ensureEnglishUICulture = False Else saveUICulture = Threading.Thread.CurrentThread.CurrentUICulture Threading.Thread.CurrentThread.CurrentUICulture = preferred End If End If Try emitResult = compilation.Emit(output, xmlDocumentationStream:=xml) Finally If ensureEnglishUICulture Then Threading.Thread.CurrentThread.CurrentUICulture = saveUICulture End If End Try xml.Seek(0, SeekOrigin.Begin) Dim xmlDoc = New StreamReader(xml).ReadToEnd().Trim() If stringMapper IsNot Nothing Then xmlDoc = CStr(stringMapper(xmlDoc)) End If Assert.Equal( expectedDocXml.Value.Trim(), xmlDoc.Replace(vbCrLf, vbLf).Trim()) End Using End Using End Sub #End Region <WorkItem(1087447, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1087447"), WorkItem(436, "CodePlex")> <Fact> Public Sub Bug1087447_01() Dim compilation = CompileCheckDiagnosticsAndXmlDocument( <compilation name="EmptyCref"> <file name="a.vb"> <![CDATA[ ''' <summary> ''' <see cref="C(Of Integer).f()"/> ''' </summary> Class C(Of T) Sub f() End Sub End Class ]]> </file> </compilation>, <error><![CDATA[ BC42309: XML comment has a tag with a 'cref' attribute 'C(Of Integer).f()' that could not be resolved. ''' <see cref="C(Of Integer).f()"/> ~~~~~~~~~~~~~~~~~~~~~~~~ ]]></error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> EmptyCref </name> </assembly> <members> <member name="T:C`1"> <summary> <see cref="!:C(Of Integer).f()"/> </summary> </member> </members> </doc> ]]> </xml>) Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes(descendIntoTrivia:=True).OfType(Of IdentifierNameSyntax)().Where(Function(n) n.Identifier.ValueText = "f").Single() Dim symbolInfo1 = model.GetSymbolInfo(node1.Parent) Assert.Equal("Sub C(Of ?).f()", symbolInfo1.Symbol.ToTestDisplayString()) Dim node = tree.GetRoot().DescendantNodes(descendIntoTrivia:=True).OfType(Of TypeSyntax)().Where(Function(n) n.ToString() = "Integer").Single() Dim symbolInfo = model.GetSymbolInfo(node) Assert.Equal("?", symbolInfo.Symbol.ToTestDisplayString()) End Sub <WorkItem(1087447, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1087447"), WorkItem(436, "CodePlex")> <Fact> Public Sub Bug1087447_02() Dim compilation = CompileCheckDiagnosticsAndXmlDocument( <compilation name="EmptyCref"> <file name="a.vb"> <![CDATA[ ''' <summary> ''' <see cref="C(Of System.Int32).f()"/> ''' </summary> Class C(Of T) Sub f() End Sub End Class ]]> </file> </compilation>, <error><![CDATA[ BC42309: XML comment has a tag with a 'cref' attribute 'C(Of System.Int32).f()' that could not be resolved. ''' <see cref="C(Of System.Int32).f()"/> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> EmptyCref </name> </assembly> <members> <member name="T:C`1"> <summary> <see cref="!:C(Of System.Int32).f()"/> </summary> </member> </members> </doc> ]]> </xml>) Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes(descendIntoTrivia:=True).OfType(Of IdentifierNameSyntax)().Where(Function(n) n.Identifier.ValueText = "f").Single() Dim symbolInfo1 = model.GetSymbolInfo(node1.Parent) Assert.Equal("Sub C(Of ?).f()", symbolInfo1.Symbol.ToTestDisplayString()) Dim node = tree.GetRoot().DescendantNodes(descendIntoTrivia:=True).OfType(Of TypeSyntax)().Where(Function(n) n.ToString() = "System.Int32").Single() Dim symbolInfo = model.GetSymbolInfo(node) Assert.Equal("?", symbolInfo.Symbol.ToTestDisplayString()) End Sub <Fact, WorkItem(1115058, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1115058")> Public Sub UnterminatedElement() Dim sources = <compilation> <file name="a.vb"> <![CDATA[ Module Module1 '''<summary> ''' Something '''<summary> Sub Main() System.Console.WriteLine("Here") End Sub End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( sources, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.Regular.WithDocumentationMode(DocumentationMode.Diagnose)) ' Compilation should succeed with warnings AssertTheseDiagnostics(CompileAndVerify(compilation, expectedOutput:="Here").Diagnostics, <![CDATA[ BC42304: XML documentation parse error: Element is missing an end tag. XML comment will be ignored. '''<summary> ~~~~~~~~~ BC42304: XML documentation parse error: Element is missing an end tag. XML comment will be ignored. '''<summary> ~~~~~~~~~ BC42304: XML documentation parse error: '>' expected. XML comment will be ignored. '''<summary> ~ BC42304: XML documentation parse error: '>' expected. XML comment will be ignored. '''<summary> ~ BC42304: XML documentation parse error: Expected beginning '<' for an XML tag. XML comment will be ignored. '''<summary> ~ BC42304: XML documentation parse error: Expected beginning '<' for an XML tag. XML comment will be ignored. '''<summary> ~ ]]>) End Sub ''' <summary> ''' "--" is not valid within an XML comment. ''' </summary> <WorkItem(8807, "https://github.com/dotnet/roslyn/issues/8807")> <Fact> Public Sub IncludeErrorDashDashInName() Dim dir = Temp.CreateDirectory() Dim path = dir.Path Dim xmlFile = dir.CreateFile("---.xml").WriteAllText("<summary attrib="""" attrib=""""/>") Dim source = <compilation name="DashDash"> <file name="a.vb"> <![CDATA[ ''' <include file='{0}' path='//param'/> Class C End Class ]]> </file> </compilation> CompileCheckDiagnosticsAndXmlDocument(FormatSourceXml(source, System.IO.Path.Combine(path, "---.xml")), <error/>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> DashDash </name> </assembly> <members> <member name="T:C"> <!--warning BC42320: Unable to include XML fragment '//param' of file '**FILE**'.--> </member> </members> </doc> ]]> </xml>, stringMapper:=Function(o) StringReplace(o, System.IO.Path.Combine(TestHelpers.AsXmlCommentText(path), "- - -.xml"), "**FILE**"), ensureEnglishUICulture:=True) End Sub <Fact> <WorkItem(410932, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?id=410932")> Public Sub LookupOnCrefTypeParameter() Dim sources = <compilation> <file name="a.vb"> <![CDATA[ Public Class Test Function F(Of T)() As T End Function ''' <summary> ''' <see cref="F(Of U)()"/> ''' </summary> Public Sub S() End Sub End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( sources, options:=TestOptions.ReleaseDll) Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim name = FindNodesOfTypeFromText(Of NameSyntax)(tree, "U").Single() Dim typeParameter = DirectCast(model.GetSymbolInfo(name).Symbol, TypeParameterSymbol) Assert.Empty(model.LookupSymbols(name.SpanStart, typeParameter, "GetAwaiter")) End Sub <Fact> Public Sub LookupOnCrefOfTupleType() Dim sources = <compilation> <file name="a.vb"> <![CDATA[ Imports System ''' <summary> ''' <see cref="ValueTuple(Of U,U)"/> ''' </summary> Public Class Test End Class ]]> </file> </compilation> Dim references = TargetFrameworkUtil.GetReferences(TargetFramework.StandardAndVBRuntime) Dim compilation = CreateEmptyCompilationWithReferences( sources, references) Dim cMember = compilation.GetMember(Of NamedTypeSymbol)("Test") Dim xmlDocumentationString = cMember.GetDocumentationCommentXml() Dim xml = System.Xml.Linq.XDocument.Parse(xmlDocumentationString) Dim cref = xml.Descendants("see").Single().Attribute("cref").Value Assert.Equal("T:System.ValueTuple`2", cref) End Sub <Fact> Public Sub LookupOnCrefOfTupleTypeField() Dim sources = <compilation> <file name="a.vb"> <![CDATA[ Imports System ''' <summary> ''' <see cref="ValueTuple(Of U,U).Item1"/> ''' </summary> Public Class Test End Class ]]> </file> </compilation> Dim references = TargetFrameworkUtil.GetReferences(TargetFramework.StandardAndVBRuntime) Dim compilation = CreateEmptyCompilationWithReferences( sources, references) Dim cMember = compilation.GetMember(Of NamedTypeSymbol)("Test") Dim xmlDocumentationString = cMember.GetDocumentationCommentXml() Dim xml = System.Xml.Linq.XDocument.Parse(xmlDocumentationString) Dim cref = xml.Descendants("see").Single().Attribute("cref").Value Assert.Equal("F:System.ValueTuple`2.Item1", cref) End Sub <Fact> <WorkItem(39315, "https://github.com/dotnet/roslyn/issues/39315")> Public Sub WriteDocumentationCommentXml_01() Dim sources = <compilation> <file name="a.vb"> <![CDATA[ ''' <summary> a.vb ''' </summary> ]]> </file> <file name="b.vb"> <![CDATA[ ''' <summary> b.vb ''' </summary> ]]> </file> </compilation> Using (New EnsureEnglishUICulture()) Dim comp = CreateCompilationWithMscorlib40(sources, parseOptions:=s_optionsDiagnoseDocComments) Dim diags = DiagnosticBag.GetInstance() DocumentationCommentCompiler.WriteDocumentationCommentXml( comp, assemblyName:=Nothing, xmlDocStream:=Nothing, diagnostics:=New BindingDiagnosticBag(diags), cancellationToken:=Nothing, filterTree:=comp.SyntaxTrees(0)) AssertTheseDiagnostics(diags.ToReadOnlyAndFree(), <errors><![CDATA[ BC42312: XML documentation comments must precede member or type declarations. ''' <summary> a.vb ~~~~~~~~~~~~~~~~ ]]></errors>) diags = DiagnosticBag.GetInstance() DocumentationCommentCompiler.WriteDocumentationCommentXml( comp, assemblyName:=Nothing, xmlDocStream:=Nothing, diagnostics:=New BindingDiagnosticBag(diags), cancellationToken:=Nothing, filterTree:=comp.SyntaxTrees(0), filterSpanWithinTree:=New Text.TextSpan(0, 0)) Assert.Empty(diags.ToReadOnlyAndFree()) diags = DiagnosticBag.GetInstance() DocumentationCommentCompiler.WriteDocumentationCommentXml( comp, assemblyName:=Nothing, xmlDocStream:=Nothing, diagnostics:=New BindingDiagnosticBag(diags), cancellationToken:=Nothing, filterTree:=comp.SyntaxTrees(1)) AssertTheseDiagnostics(diags.ToReadOnlyAndFree(), <errors><![CDATA[ BC42312: XML documentation comments must precede member or type declarations. ''' <summary> b.vb ~~~~~~~~~~~~~~~~ ]]></errors>) diags = DiagnosticBag.GetInstance() DocumentationCommentCompiler.WriteDocumentationCommentXml( comp, assemblyName:=Nothing, xmlDocStream:=Nothing, diagnostics:=New BindingDiagnosticBag(diags), cancellationToken:=Nothing, filterTree:=Nothing) AssertTheseDiagnostics(diags.ToReadOnlyAndFree(), <errors><![CDATA[ BC42312: XML documentation comments must precede member or type declarations. ''' <summary> a.vb ~~~~~~~~~~~~~~~~ BC42312: XML documentation comments must precede member or type declarations. ''' <summary> b.vb ~~~~~~~~~~~~~~~~ ]]></errors>) diags = DiagnosticBag.GetInstance() DocumentationCommentCompiler.WriteDocumentationCommentXml( comp, assemblyName:=Nothing, xmlDocStream:=Nothing, diagnostics:=New BindingDiagnosticBag(diags), cancellationToken:=Nothing, filterTree:=Nothing, filterSpanWithinTree:=New Text.TextSpan(0, 0)) AssertTheseDiagnostics(diags.ToReadOnlyAndFree(), <errors><![CDATA[ BC42312: XML documentation comments must precede member or type declarations. ''' <summary> a.vb ~~~~~~~~~~~~~~~~ BC42312: XML documentation comments must precede member or type declarations. ''' <summary> b.vb ~~~~~~~~~~~~~~~~ ]]></errors>) End Using End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.Test.Utilities Imports System.Xml.Linq Imports System.Text Imports System.IO Imports Roslyn.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.VisualBasicCompilation Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class DocCommentTests Inherits BasicTestBase Private Shared ReadOnly s_optionsDiagnoseDocComments As VisualBasicParseOptions = VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose) <Fact> Public Sub DocCommentWriteException() Dim sources = <compilation name="DocCommentException"> <file name="a.vb"> <![CDATA[ ''' <summary> ''' Doc comment for <see href="C" /> ''' </summary> Public Class C ''' <summary> ''' Doc comment for method M ''' </summary> Public Sub M() End Sub End Class ]]> </file> </compilation> Using (new EnsureEnglishUICulture()) Dim comp = CreateCompilationWithMscorlib40(sources) Dim diags = New DiagnosticBag() Dim badStream = New BrokenStream() badStream.BreakHow = BrokenStream.BreakHowType.ThrowOnWrite DocumentationCommentCompiler.WriteDocumentationCommentXml( comp, assemblyName:=Nothing, xmlDocStream:=badStream, diagnostics:=New BindingDiagnosticBag(diags), cancellationToken:=Nothing) AssertTheseDiagnostics(diags.ToReadOnlyAndFree(), <errors><![CDATA[ BC37258: Error writing to XML documentation file: I/O error occurred. ]]></errors>) End Using End Sub <Fact> Public Sub NoXmlResolver() Dim sources = <compilation name="DocumentationMode"> <file name="a.vb"> <![CDATA[ ''' <summary> <include file='abc' path='def' /> </summary> Class C End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40( sources, options:=TestOptions.ReleaseDll.WithXmlReferenceResolver(Nothing), parseOptions:=TestOptions.Regular.WithDocumentationMode(DocumentationMode.Parse)) compilation.VerifyDiagnostics() CheckXmlDocument(compilation, expectedDocXml:= <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> DocumentationMode </name> </assembly> <members> <member name="T:C"> <summary> <!--warning BC42321: Unable to include XML fragment 'def' of file 'abc'. References to XML documents are not supported.--> </summary> </member> </members> </doc> ]]> </xml>, ensureEnglishUICulture:=True) End Sub <Fact> Public Sub DocumentationMode_None() Dim sources = <compilation name="DocumentationMode"> <file name="a.vb"> <![CDATA[ Imports System ''' <summary> </summary Module Module0 End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( sources, parseOptions:=(New VisualBasicParseOptions()).WithDocumentationMode(DocumentationMode.None)) Dim tree = compilation.SyntaxTrees(0) Dim moduleStatement = tree.FindNodeOrTokenByKind(SyntaxKind.ModuleStatement) Assert.True(moduleStatement.IsNode) Dim node = moduleStatement.AsNode() Dim trivia = node.GetLeadingTrivia().ToArray() Assert.True(trivia.Any(Function(x) x.Kind = SyntaxKind.CommentTrivia)) Assert.False(trivia.Any(Function(x) x.Kind = SyntaxKind.DocumentationCommentTrivia)) CompilationUtils.AssertTheseDiagnostics(compilation.GetSemanticModel(tree).GetDiagnostics(), <errors></errors>) End Sub <Fact> Public Sub DocumentationMode_Parse() Dim sources = <compilation name="DocumentationMode"> <file name="a.vb"> <![CDATA[ Imports System ''' <summary> </summary Module Module0 End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( sources, parseOptions:=(New VisualBasicParseOptions()).WithDocumentationMode(DocumentationMode.Parse)) Dim tree = compilation.SyntaxTrees(0) Dim moduleStatement = tree.FindNodeOrTokenByKind(SyntaxKind.ModuleStatement) Assert.True(moduleStatement.IsNode) Dim node = moduleStatement.AsNode() Dim trivia = node.GetLeadingTrivia().ToArray() Assert.False(trivia.Any(Function(x) x.Kind = SyntaxKind.CommentTrivia)) Assert.True(trivia.Any(Function(x) x.Kind = SyntaxKind.DocumentationCommentTrivia)) CompilationUtils.AssertTheseDiagnostics(compilation.GetSemanticModel(tree).GetDiagnostics(), <errors></errors>) End Sub <Fact> Public Sub DocumentationMode_ParseAndDiagnose() Dim sources = <compilation name="DocumentationMode"> <file name="a.vb"> <![CDATA[ Imports System ''' <summary> </summary Module Module0 End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( sources, parseOptions:=s_optionsDiagnoseDocComments) Dim tree = compilation.SyntaxTrees(0) Dim moduleStatement = tree.FindNodeOrTokenByKind(SyntaxKind.ModuleStatement) Assert.True(moduleStatement.IsNode) Dim node = moduleStatement.AsNode() Dim trivia = node.GetLeadingTrivia().ToArray() Assert.False(trivia.Any(Function(x) x.Kind = SyntaxKind.CommentTrivia)) Assert.True(trivia.Any(Function(x) x.Kind = SyntaxKind.DocumentationCommentTrivia)) CompilationUtils.AssertTheseDiagnostics(compilation.GetSemanticModel(tree).GetDiagnostics(), <errors> <![CDATA[ BC42304: XML documentation parse error: '>' expected. XML comment will be ignored. ''' <summary> </summary ~ ]]> </errors>) End Sub <Fact> Public Sub DocCommentOnUnsupportedSymbol() CompileCheckDiagnosticsAndXmlDocument( <compilation name="EmptyCref"> <file name="a.vb"> <![CDATA[ Imports System Class E ReadOnly Property quoteForTheDay() As String ''' <summary></summary> Get Return "hello" End Get End Property End Class ]]> </file> </compilation>, <error> <![CDATA[ BC42312: XML documentation comments must precede member or type declarations. ''' <summary></summary> ~~~~~~~~~~~~~~~~~~~~~ ]]> </error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> EmptyCref </name> </assembly> <members> </members> </doc> ]]> </xml>) End Sub <WorkItem(720931, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720931")> <Fact> Public Sub Bug720931() Dim compilation = CompileCheckDiagnosticsAndXmlDocument( <compilation name="EmptyCref"> <file name="a.vb"> <![CDATA[ Imports System ''' <see cref="Integer"/> ''' <see cref="UShort"/> ''' <see cref="Object"/> ''' <see cref="Date"/> Public Class CLAZZ End Class ]]> </file> </compilation>, <error></error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> EmptyCref </name> </assembly> <members> <member name="T:CLAZZ"> <see cref="T:System.Int32"/> <see cref="T:System.UInt16"/> <see cref="T:System.Object"/> <see cref="T:System.DateTime"/> </member> </members> </doc> ]]> </xml>) End Sub <WorkItem(705788, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/705788")> <Fact> Public Sub Bug705788() Dim compilation = CompileCheckDiagnosticsAndXmlDocument( <compilation name="Bug705788"> <file name="a.vb"> <![CDATA[ Imports System ''' <c name="Scenario1"/> ''' <code name="Scenario1"/> ''' <example name="Scenario1"/> ''' <list name="Scenario1"/> ''' <paramref name="Scenario1"/> ''' <remarks name="Scenario1"/> ''' <summary name="Scenario1"/> Module Scenario1 ''' <para name="Scenario2"/> ''' <paramref name="Scenario2"/> ''' <permission cref="Scenario2" name="Scenario2"/> ''' <see cref="Scenario2" name="Scenario2"/> ''' <seealso cref="Scenario2" name="Scenario2"/> Class Scenario2 End Class Sub Main() End Sub End Module ]]> </file> </compilation>, <error> <![CDATA[ BC42306: XML comment tag 'paramref' is not permitted on a 'module' language element. ''' <paramref name="Scenario1"/> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'paramref' is not permitted on a 'class' language element. ''' <paramref name="Scenario2"/> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]> </error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> Bug705788 </name> </assembly> <members> <member name="T:Scenario1"> <c name="Scenario1"/> <code name="Scenario1"/> <example name="Scenario1"/> <list name="Scenario1"/> <paramref name="Scenario1"/> <remarks name="Scenario1"/> <summary name="Scenario1"/> </member> <member name="T:Scenario1.Scenario2"> <para name="Scenario2"/> <paramref name="Scenario2"/> <permission cref="T:Scenario1.Scenario2" name="Scenario2"/> <see cref="T:Scenario1.Scenario2" name="Scenario2"/> <seealso cref="T:Scenario1.Scenario2" name="Scenario2"/> </member> </members> </doc> ]]> </xml>) End Sub <WorkItem(658453, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/658453")> <Fact> Public Sub Bug658453() Dim compilation = CompileCheckDiagnosticsAndXmlDocument( <compilation name="EmptyCref"> <file name="a.vb"> <![CDATA[ Imports System Namespace Microsoft.VisualBasic ''' <summary> ''' Provides core iterator implementation. ''' </summary> ''' <typeparam name="TState">Type of iterator state data.</typeparam> ''' <typeparam name="TItem">Type of items returned from the iterator.</typeparam> ''' <param name="state">Iteration data.</param> ''' <param name="item">Element produced at this step.</param> ''' <returns>Whether the step was successful.</returns> Friend Delegate Function IteratorStep(Of TState, TItem)( ByRef state As TState, ByRef item As TItem) As Boolean End Namespace ]]> </file> </compilation>, <error></error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> EmptyCref </name> </assembly> <members> <member name="T:Microsoft.VisualBasic.IteratorStep`2"> <summary> Provides core iterator implementation. </summary> <typeparam name="TState">Type of iterator state data.</typeparam> <typeparam name="TItem">Type of items returned from the iterator.</typeparam> <param name="state">Iteration data.</param> <param name="item">Element produced at this step.</param> <returns>Whether the step was successful.</returns> </member> </members> </doc> ]]> </xml>) Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "TState").ToArray() Assert.Equal(2, names.Length) CheckSymbolInfoAndTypeInfo(model, names(0), "TState") End Sub <WorkItem(762687, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/762687")> <Fact> Public Sub Bug762687a() CompileCheckDiagnosticsAndXmlDocument( <compilation name="Bug762687"> <file name="a.vb"> <![CDATA[ Imports System Class B Public Property System As Object End Class Class D Inherits B ''' <see cref="System.Console"/> Public X As Integer End Class ]]> </file> </compilation>, <error></error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> Bug762687 </name> </assembly> <members> <member name="F:D.X"> <see cref="T:System.Console"/> </member> </members> </doc> ]]> </xml>) End Sub <WorkItem(762687, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/762687")> <Fact> Public Sub Bug762687b() CompileCheckDiagnosticsAndXmlDocument( <compilation name="Bug762687"> <file name="a.vb"> <![CDATA[ Imports System Class B Public Property System As Object End Class Class D Inherits B ''' <see cref="System.Console.WriteLine()"/> Public X As Integer End Class ]]> </file> </compilation>, <error></error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> Bug762687 </name> </assembly> <members> <member name="F:D.X"> <see cref="M:System.Console.WriteLine"/> </member> </members> </doc> ]]> </xml>) End Sub <WorkItem(664943, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/664943")> <Fact> Public Sub Bug664943() CompileCheckDiagnosticsAndXmlDocument( <compilation name="EmptyCref"> <file name="a.vb"> <![CDATA[ Imports System ''' <summary></summary> ''' Class E End Class ]]> </file> </compilation>, <error></error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> EmptyCref </name> </assembly> <members> <member name="T:E"> <summary></summary> </member> </members> </doc> ]]> </xml>) End Sub <WorkItem(679833, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/679833")> <Fact> Public Sub Bug679833_DontCrash() CompileCheckDiagnosticsAndXmlDocument( <compilation name="EmptyCref"> <file name="a.vb"> <![CDATA[ Public Sub New() d Sub Public ''' As String ''' summary> End Enum ]]> </file> </compilation>, <error> <![CDATA[ BC30203: Identifier expected. Public ~ BC30026: 'End Sub' expected. Sub New() ~~~~~~~~~ BC30451: 'd' is not declared. It may be inaccessible due to its protection level. d Sub ~ BC36673: Multiline lambda expression is missing 'End Sub'. d Sub ~~~ BC30800: Method arguments must be enclosed in parentheses. d Sub ~~~~ BC30198: ')' expected. d Sub ~ BC30199: '(' expected. d Sub ~ BC30203: Identifier expected. Public ''' As String ~ BC42302: XML comment must be the first statement on a line. XML comment will be ignored. Public ''' As String ~~~~~~~~~~~~~ BC42303: XML comment cannot appear within a method or a property. XML comment will be ignored. ''' ~ BC30201: Expression expected. summary> ~ BC30800: Method arguments must be enclosed in parentheses. summary> ~ BC30201: Expression expected. summary> ~ BC30184: 'End Enum' must be preceded by a matching 'Enum'. End Enum ~~~~~~~~ ]]> </error>) End Sub <WorkItem(665883, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/665883")> <Fact> Public Sub Bug665883() CompileCheckDiagnosticsAndXmlDocument( <compilation name="EmptyCref"> <file name="a.vb"> <![CDATA[ Imports System ''' <see cref="Console.WriteLine"/> Module M End Module ]]> </file> </compilation>, <error></error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> EmptyCref </name> </assembly> <members> <member name="T:M"> <see cref="M:System.Console.WriteLine"/> </member> </members> </doc> ]]> </xml>) End Sub <WorkItem(666241, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/666241")> <Fact> Public Sub Bug666241() Dim compilation = CompileCheckDiagnosticsAndXmlDocument( <compilation name="EmptyCref"> <file name="a.vb"> <![CDATA[ Imports System Namespace System.Drawing ''' <summary> ''' Opt-In flag to look for resources in the another assembly ''' with the "bitmapSuffix" config setting ''' </summary> <AttributeUsage(AttributeTargets.Assembly)> Friend Class BitmapSuffixInSatelliteAssemblyAttribute Inherits Attribute End Class End Namespace ]]> </file> <file name="b.vb"> <![CDATA[ Imports System.Diagnostics.CodeAnalysis Namespace Microsoft.VisualBasic.PowerPacks.Printing.Compatibility.VB6 Public Module SystemColorConstants ''' <include file='doc\Constants.uex' path='docs/doc[@for="SystemColorConstants.vbScrollBars"]/*' /> <SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")> _ <SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")> _ Public Const vbScrollBars As Integer = &H80000000 End Module End Namespace ]]> </file> </compilation>, <error></error>) Dim model = compilation.GetSemanticModel(compilation.SyntaxTrees(0)) CompilationUtils.AssertTheseDiagnostics(model.GetDiagnostics(), <error></error>) model = compilation.GetSemanticModel(compilation.SyntaxTrees(1)) CompilationUtils.AssertTheseDiagnostics(model.GetDiagnostics(), <error></error>) End Sub <WorkItem(658793, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/658793")> <Fact> Public Sub Bug658793() CompileCheckDiagnosticsAndXmlDocument( <compilation name="EmptyCref"> <file name="a.vb"> <![CDATA[ Imports System ''' <summary cref="(" /> ''' Class E End Class ]]> </file> </compilation>, <error> <![CDATA[ BC42309: XML comment has a tag with a 'cref' attribute '(' that could not be resolved. ''' <summary cref="(" /> ~~~~~~~~ ]]> </error>) End Sub <WorkItem(721582, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/721582")> <Fact> Public Sub Bug721582() CompileCheckDiagnosticsAndXmlDocument( <compilation name="EmptyCref"> <file name="a.vb"> <![CDATA[ Imports System ''' <see cref="object"/> ''' <see cref="object.tostring"/> ''' <see cref="system.object"/> ''' <see cref="system.object.tostring"/> ''' <see cref="object.tostring()"/> ''' <see cref="system.object.tostring()"/> Class E End Class ]]> </file> </compilation>, <error></error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> EmptyCref </name> </assembly> <members> <member name="T:E"> <see cref="T:System.Object"/> <see cref="T:System.Object"/> <see cref="T:System.Object"/> <see cref="M:System.Object.ToString"/> <see cref="T:System.Object"/> <see cref="M:System.Object.ToString"/> </member> </members> </doc> ]]> </xml>) End Sub <WorkItem(657426, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/657426")> <Fact> Public Sub Bug657426() CompileCheckDiagnosticsAndXmlDocument( <compilation name="EmptyCref"> <file name="a.vb"> <![CDATA[ Imports System ''' <summary> ''' <see ''' cref="Int32"/> ''' </summary> Class E End Class ]]> </file> </compilation>, <error></error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> EmptyCref </name> </assembly> <members> <member name="T:E"> <summary> <see cref="T:System.Int32"/> </summary> </member> </members> </doc> ]]> </xml>) End Sub <WorkItem(658322, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/658322")> <Fact> Public Sub Bug658322a() CompileCheckDiagnosticsAndXmlDocument( <compilation name="EmptyCref"> <file name="a.vb"> <![CDATA[ Imports System Class E ''' <param name="next">The next binder.</param> Public Sub New([next] As Integer) End Sub End Class ]]> </file> </compilation>, <error></error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> EmptyCref </name> </assembly> <members> <member name="M:E.#ctor(System.Int32)"> <param name="next">The next binder.</param> </member> </members> </doc> ]]> </xml>) End Sub <WorkItem(658322, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/658322")> <Fact> Public Sub Bug658322b() CompileCheckDiagnosticsAndXmlDocument( <compilation name="EmptyCref"> <file name="a.vb"> <![CDATA[ Imports System Namespace Roslyn.Compilers.VisualBasic Partial Class BoundAddressOfOperator ''' <returns>The <see cref="Binder.DelegateResolutionResult">Binder.DelegateResolutionResult</see> for the conversion </returns> Friend Function GetDelegateResolutionResult(ByRef delegateResolutionResult As Binder.DelegateResolutionResult) As Boolean Return Nothing End Function Public Property Binder As Binder End Class End Namespace ]]> </file> <file name="b.vb"> <![CDATA[ Imports System Namespace Roslyn.Compilers.VisualBasic Partial Friend Class Binder Friend Structure DelegateResolutionResult End Structure End Class End Namespace ]]> </file> </compilation>, <error></error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> EmptyCref </name> </assembly> <members> <member name="M:Roslyn.Compilers.VisualBasic.BoundAddressOfOperator.GetDelegateResolutionResult(Roslyn.Compilers.VisualBasic.Binder.DelegateResolutionResult@)"> <returns>The <see cref="T:Roslyn.Compilers.VisualBasic.Binder.DelegateResolutionResult">Binder.DelegateResolutionResult</see> for the conversion </returns> </member> </members> </doc> ]]> </xml>) End Sub <WorkItem(658322, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/658322")> <Fact> Public Sub Bug658322c() CompileCheckDiagnosticsAndXmlDocument( <compilation name="EmptyCref"> <file name="a.vb"> <![CDATA[ Imports System Namespace Roslyn.Compilers.VisualBasic Partial Class BoundAddressOfOperator ''' <returns>The <see cref="Binder.DelegateResolutionResult">Binder.DelegateResolutionResult</see> for the conversion </returns> Friend Function GetDelegateResolutionResult(ByRef delegateResolutionResult As Binder.DelegateResolutionResult) As Boolean Return Nothing End Function Public Binder As Binder End Class End Namespace ]]> </file> <file name="b.vb"> <![CDATA[ Imports System Namespace Roslyn.Compilers.VisualBasic Partial Friend Class Binder Friend Structure DelegateResolutionResult End Structure End Class End Namespace ]]> </file> </compilation>, <error></error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> EmptyCref </name> </assembly> <members> <member name="M:Roslyn.Compilers.VisualBasic.BoundAddressOfOperator.GetDelegateResolutionResult(Roslyn.Compilers.VisualBasic.Binder.DelegateResolutionResult@)"> <returns>The <see cref="T:Roslyn.Compilers.VisualBasic.Binder.DelegateResolutionResult">Binder.DelegateResolutionResult</see> for the conversion </returns> </member> </members> </doc> ]]> </xml>) End Sub <WorkItem(658322, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/658322")> <Fact> Public Sub Bug658322d() CompileCheckDiagnosticsAndXmlDocument( <compilation name="EmptyCref"> <file name="a.vb"> <![CDATA[ Imports System Namespace Roslyn.Compilers.VisualBasic Partial Class BoundAddressOfOperator ''' <returns>The <see cref="Binder.DelegateResolutionResult">Binder.DelegateResolutionResult</see> for the conversion </returns> Friend Function GetDelegateResolutionResult(ByRef delegateResolutionResult As Binder.DelegateResolutionResult) As Boolean Return Nothing End Function Public Function Binder() As Binder Return Nothing End Function End Class End Namespace ]]> </file> <file name="b.vb"> <![CDATA[ Imports System Namespace Roslyn.Compilers.VisualBasic Partial Friend Class Binder Friend Structure DelegateResolutionResult End Structure End Class End Namespace ]]> </file> </compilation>, <error></error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> EmptyCref </name> </assembly> <members> <member name="M:Roslyn.Compilers.VisualBasic.BoundAddressOfOperator.GetDelegateResolutionResult(Roslyn.Compilers.VisualBasic.Binder.DelegateResolutionResult@)"> <returns>The <see cref="T:Roslyn.Compilers.VisualBasic.Binder.DelegateResolutionResult">Binder.DelegateResolutionResult</see> for the conversion </returns> </member> </members> </doc> ]]> </xml>) End Sub <WorkItem(658322, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/658322")> <Fact()> Public Sub Bug658322e() Dim compilation = CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Option Explicit On Imports System Public Class TAttribute : Inherits Attribute End Class ''' <remarks cref="TAttribute">Clazz</remarks> <TAttribute> Public Class Clazz ''' <remarks cref="TAttribute">Clazz</remarks> <TAttribute> Public d As Integer End Class ''' <remarks cref="TAttribute">Clazz</remarks> <TAttribute> Public Enum E1 ''' <remarks cref="TAttribute">Clazz</remarks> <TAttribute> Any End Enum ]]> </file> </compilation>, <error></error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:Clazz"> <remarks cref="T:TAttribute">Clazz</remarks> </member> <member name="F:Clazz.d"> <remarks cref="T:TAttribute">Clazz</remarks> </member> <member name="T:E1"> <remarks cref="T:TAttribute">Clazz</remarks> </member> <member name="F:E1.Any"> <remarks cref="T:TAttribute">Clazz</remarks> </member> </members> </doc> ]]> </xml>) Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "TAttribute").ToArray() Assert.Equal(8, names.Length) CheckSymbolInfoAndTypeInfo(model, names(0), "TAttribute") CheckSymbolInfoAndTypeInfo(model, names(2), "TAttribute") CheckSymbolInfoAndTypeInfo(model, names(4), "TAttribute") CheckSymbolInfoAndTypeInfo(model, names(6), "TAttribute") End Sub <WorkItem(665961, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/665961")> <Fact()> Public Sub Bug665961() Dim compilation = CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Module M Sub Main() ''' <see cref="x"/> Dim x End Sub End Module ]]> </file> </compilation>, <error> <![CDATA[ BC42303: XML comment cannot appear within a method or a property. XML comment will be ignored. ''' <see cref="x"/> ~~~~~~~~~~~~~~~~~ BC42024: Unused local variable: 'x'. Dim x ~ ]]> </error>) Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "x").ToArray() Assert.Equal(1, names.Length) CheckSymbolInfoAndTypeInfo(model, names(0)) Assert.Equal("Public Sub Main()", TryCast(model, SemanticModel).GetEnclosingSymbol(names(0).SpanStart).ToDisplayString()) End Sub <WorkItem(685473, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/685473")> <ConditionalFact(GetType(WindowsDesktopOnly), Reason:=ConditionalSkipReason.TestExecutionNeedsDesktopTypes)> Public Sub Bug685473() CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System.CodeDom Namespace ABCD.PRODUCT.Current.SDK.Legacy.PackageGenerator '''------------</------------------------------------------------ ''' Project : ABCD.PRODUCT.Current.SDK.Legacy ''' Class : ProvideAutomationObject ''' '''------------------------------------------------ ''' <summary> ''' This class models the ProvideAutomationObject attribute ''' in Project : ABCD.PRODUCT.Current.SDK.Legacyry> ''' [user] 11/17/2004 Created ''' </history> '''-------If--------------------------------------- P lic Class ProvideAutomationObject : Inherits VsipCodeAttributeGenerator Public ObjectName As String = Nothing Public Description As String = Nothing '''------------------------------------------------ ''' <summary> ''' Generates the code for this element ''' </summary> ''' <returns>A string representing the code</returns> '''------------------------------------------------ Public Overrides Function Generate() As String ObjectNametr As New CodeAttributeDeclaration(Me.GetAttributeName()) attr.Arguments.Add(New CodeAttributeArgument(New CodePrimitiveExpressi=n(ObjectName))) If Not Description = Nothing hen attr.Arguments.Add(New C------------------------------------------------itiveExpression(Description))) End If Return PackageCodeGenerator.GetAttributeCode(attr) End Functio End Class End Namespace ]]> </file> </compilation>, <error> <![CDATA[BC42312: XML documentation comments must precede member or type declarations. '''------------</------------------------------------------------ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42304: XML documentation parse error: XML end element must be preceded by a matching start element. XML comment will be ignored. '''------------</------------------------------------------------ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42304: XML documentation parse error: Character '-' (&H2D) is not allowed at the beginning of an XML name. XML comment will be ignored. '''------------</------------------------------------------------ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42304: XML documentation parse error: '>' expected. XML comment will be ignored. '''------------</------------------------------------------------ ~ BC42304: XML documentation parse error: Syntax error. XML comment will be ignored. ''' Project : ABCD.PRODUCT.Current.SDK.Legacy ~~~~~~~ BC42304: XML documentation parse error: Element is missing an end tag. XML comment will be ignored. ''' <summary> ~~~~~~~~~ BC42304: XML documentation parse error: End tag </summary> expected. XML comment will be ignored. ''' </history> ~~~~~~~~~~ BC30188: Declaration expected. lic Class ProvideAutomationObject : Inherits VsipCodeAttributeGenerator ~~~ BC30002: Type 'VsipCodeAttributeGenerator' is not defined. lic Class ProvideAutomationObject : Inherits VsipCodeAttributeGenerator ~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30027: 'End Function' expected. Public Overrides Function Generate() As String ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30284: function 'Generate' cannot be declared 'Overrides' because it does not override a function in a base class. Public Overrides Function Generate() As String ~~~~~~~~ BC30451: 'ObjectNametr' is not declared. It may be inaccessible due to its protection level. ObjectNametr As New CodeAttributeDeclaration(Me.GetAttributeName()) ~~~~~~~~~~~~ BC30201: Expression expected. ObjectNametr As New CodeAttributeDeclaration(Me.GetAttributeName()) ~ BC30800: Method arguments must be enclosed in parentheses. ObjectNametr As New CodeAttributeDeclaration(Me.GetAttributeName()) ~ BC30451: 'attr' is not declared. It may be inaccessible due to its protection level. attr.Arguments.Add(New CodeAttributeArgument(New CodePrimitiveExpressi=n(ObjectName))) ~~~~ BC30002: Type 'CodePrimitiveExpressi' is not defined. attr.Arguments.Add(New CodeAttributeArgument(New CodePrimitiveExpressi=n(ObjectName))) ~~~~~~~~~~~~~~~~~~~~~ BC30451: 'n' is not declared. It may be inaccessible due to its protection level. attr.Arguments.Add(New CodeAttributeArgument(New CodePrimitiveExpressi=n(ObjectName))) ~ BC30451: 'hen' is not declared. It may be inaccessible due to its protection level. hen ~~~ BC30451: 'attr' is not declared. It may be inaccessible due to its protection level. attr.Arguments.Add(New C------------------------------------------------itiveExpression(Description))) ~~~~ BC30002: Type 'C' is not defined. attr.Arguments.Add(New C------------------------------------------------itiveExpression(Description))) ~ BC30451: 'itiveExpression' is not declared. It may be inaccessible due to its protection level. attr.Arguments.Add(New C------------------------------------------------itiveExpression(Description))) ~~~~~~~~~~~~~~~ BC30205: End of statement expected. attr.Arguments.Add(New C------------------------------------------------itiveExpression(Description))) ~ BC30451: 'PackageCodeGenerator' is not declared. It may be inaccessible due to its protection level. Return PackageCodeGenerator.GetAttributeCode(attr) ~~~~~~~~~~~~~~~~~~~~ BC30451: 'attr' is not declared. It may be inaccessible due to its protection level. Return PackageCodeGenerator.GetAttributeCode(attr) ~~~~ BC30615: 'End' statement cannot be used in class library projects. End Functio ~~~ BC30678: 'End' statement not valid. End Functio ~~~ ]]> </error>) End Sub <Fact> Public Sub DocCommentOnUnsupportedSymbol_ParseOnly() CompileCheckDiagnosticsAndXmlDocument( <compilation name="EmptyCref"> <file name="a.vb"> <![CDATA[ Imports System Class E ReadOnly Property quoteForTheDay() As String ''' <summary></summary> Get Return "hello" End Get End Property End Class ]]> </file> </compilation>, <error></error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> EmptyCref </name> </assembly> <members> </members> </doc> ]]> </xml>, withDiagnostics:=False) End Sub <Fact> Public Sub EmptyCref() CompileCheckDiagnosticsAndXmlDocument( <compilation name="EmptyCref"> <file name="a.vb"> <![CDATA[ Imports System ''' <summary> ''' See <see cref=""/>. ''' </summary> ''' <remarks></remarks> Module Module0 End Module ]]> </file> </compilation>, <error> <![CDATA[ BC42309: XML comment has a tag with a 'cref' attribute '' that could not be resolved. ''' See <see cref=""/>. ~~~~~~~ ]]> </error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> EmptyCref </name> </assembly> <members> <member name="T:Module0"> <summary> See <see cref="!:"/>. </summary> <remarks></remarks> </member> </members> </doc> ]]> </xml>) End Sub <Fact> Public Sub Cref_Error() CompileCheckDiagnosticsAndXmlDocument( <compilation name="EmptyCref"> <file name="a.vb"> <![CDATA[ Imports System ''' <summary> ''' See <see cref="Module0."/>. ''' See <see cref="Module0. ''' "/>. ''' See <see cref="Module0 ''' "/>. ''' See <see cref="Module0.' ''' "/>. ''' See <see cref="Module0. _ ''' "/>. ''' </summary> ''' <remarks></remarks> Module Module0 End Module ]]> </file> </compilation>, <error> <![CDATA[ BC42309: XML comment has a tag with a 'cref' attribute 'Module0.' that could not be resolved. ''' See <see cref="Module0."/>. ~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'Module0. '''' that could not be resolved. ''' See <see cref="Module0. ~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'Module0.'' that could not be resolved. ''' See <see cref="Module0.' ~~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'Module0. _' that could not be resolved. ''' See <see cref="Module0. _ ~~~~~~~~~~~~~~~~~ ]]> </error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> EmptyCref </name> </assembly> <members> <member name="T:Module0"> <summary> See <see cref="!:Module0."/>. See <see cref="!:Module0. "/>. See <see cref="T:Module0"/>. See <see cref="!:Module0.' "/>. See <see cref="!:Module0. _ "/>. </summary> <remarks></remarks> </member> </members> </doc> ]]> </xml>) End Sub <Fact> Public Sub Cref_Me_MyBase_MyClass() CompileCheckDiagnosticsAndXmlDocument( <compilation name="EmptyCref"> <file name="a.vb"> <![CDATA[ Imports System Public Class BaseClass Public Overridable Sub S() End Sub End Class Public Class DerivedClass : Inherits BaseClass Public Overrides Sub S() End Sub ''' <summary> ''' <see cref="Me.S"/> ''' <see cref="MyClass.S"/> ''' <see cref="MyBase.S"/> ''' </summary> Public F As Integer End Class ]]> </file> </compilation>, <error> <![CDATA[ BC42309: XML comment has a tag with a 'cref' attribute 'Me.S' that could not be resolved. ''' <see cref="Me.S"/> ~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'MyClass.S' that could not be resolved. ''' <see cref="MyClass.S"/> ~~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'MyBase.S' that could not be resolved. ''' <see cref="MyBase.S"/> ~~~~~~~~~~~~~~~ ]]> </error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> EmptyCref </name> </assembly> <members> <member name="F:DerivedClass.F"> <summary> <see cref="!:Me.S"/> <see cref="!:MyClass.S"/> <see cref="!:MyBase.S"/> </summary> </member> </members> </doc> ]]> </xml>) End Sub <Fact> Public Sub Cref_Type_Namespace_Alias() CompileCheckDiagnosticsAndXmlDocument( <compilation name="EmptyCref"> <file name="a.vb"> <![CDATA[ Imports System Imports ABC = System.Collections.Generic Imports ABCD = System.Collections.Generic.IList(Of Integer) Public Class BaseClass ''' <summary> ''' <see cref="System.Collections.Generic"/> ''' <see cref="System.Collections.Generic.IList(Of Integer)"/> ''' <see cref="ABC"/> ''' <see cref="ABC.IList(Of Integer)"/> ''' <see cref="ABCD"/> ''' </summary> Public F As Integer End Class ]]> </file> </compilation>, <error></error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> EmptyCref </name> </assembly> <members> <member name="F:BaseClass.F"> <summary> <see cref="N:System.Collections.Generic"/> <see cref="T:System.Collections.Generic.IList`1"/> <see cref="N:System.Collections.Generic"/> <see cref="T:System.Collections.Generic.IList`1"/> <see cref="T:System.Collections.Generic.IList`1"/> </summary> </member> </members> </doc> ]]> </xml>) End Sub <Fact> Public Sub Name_Error() ' NOTE: the first error is a breaking change CompileCheckDiagnosticsAndXmlDocument( <compilation name="EmptyCref"> <file name="a.vb"> <![CDATA[ Imports System ''' <typeparam name="X ''' "/> ''' <typeparam name="X 'abc ''' "/> Class Clazz(Of X) End Class ]]> </file> </compilation>, <error> <![CDATA[ BC42317: XML comment type parameter 'X ' does not match a type parameter on the corresponding 'class' statement. ''' <typeparam name="X ~~~~~~~~ BC42317: XML comment type parameter 'X 'abc ' does not match a type parameter on the corresponding 'class' statement. ''' <typeparam name="X 'abc ~~~~~~~~~~~~~ ]]> </error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> EmptyCref </name> </assembly> <members> <member name="T:Clazz`1"> <typeparam name="X "/> <typeparam name="X 'abc "/> </member> </members> </doc> ]]> </xml>) End Sub <Fact> Public Sub Cref_Error_ParseOnly() CompileCheckDiagnosticsAndXmlDocument( <compilation name="EmptyCref"> <file name="a.vb"> <![CDATA[ Imports System ''' <summary> ''' See <see cref="Module0."/>. ''' See <see cref="Module0. ''' "/>. ''' See <see cref="Module0 ''' "/>. ''' See <see cref="Module0.' ''' "/>. ''' See <see cref="Module0. _ ''' "/>. ''' </summary> ''' <remarks></remarks> Module Module0 End Module ]]> </file> </compilation>, <error></error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> EmptyCref </name> </assembly> <members> <member name="T:Module0"> <summary> See <see cref="!:Module0."/>. See <see cref="!:Module0. "/>. See <see cref="T:Module0"/>. See <see cref="!:Module0.' "/>. See <see cref="!:Module0. _ "/>. </summary> <remarks></remarks> </member> </members> </doc> ]]> </xml>, withDiagnostics:=False) End Sub <Fact> Public Sub Name_Error_ParseOnly() CompileCheckDiagnosticsAndXmlDocument( <compilation name="EmptyCref"> <file name="a.vb"> <![CDATA[ Imports System ''' <typeparam name="X ''' "/> ''' <typeparam name="X 'abc ''' "/> Class Clazz(Of X) End Class ]]> </file> </compilation>, <error></error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> EmptyCref </name> </assembly> <members> <member name="T:Clazz`1"> <typeparam name="X "/> <typeparam name="X 'abc "/> </member> </members> </doc> ]]> </xml>, withDiagnostics:=False) End Sub <Fact> Public Sub DiagnosticsWithoutEmit() CompileCheckDiagnosticsAndXmlDocument( <compilation name="DiagnosticsWithoutEmit"> <file name="a.vb"> <![CDATA[ Imports System ''' <summary> ''' See <see cref=""/>. ''' </summary> ''' <remarks></remarks> Module Module0 End Module ]]> </file> </compilation>, <error> <![CDATA[ BC42309: XML comment has a tag with a 'cref' attribute '' that could not be resolved. ''' See <see cref=""/>. ~~~~~~~ ]]> </error>, Nothing) End Sub <Fact> Public Sub GeneralDocCommentOnTypes() CompileCheckDiagnosticsAndXmlDocument( <compilation name="GeneralDocCommentOnTypes"> <file name="a.vb"> <![CDATA[ Imports System ''' <summary> ''' Module M ''' commented ''' </summary> Module Module0 End Module ''' <summary> ''' Enum ''' ---======7777777%%% ''' </summary> Enum E123 E1 End Enum ''' <summary> ''' Structure ''' <a></a> iusgdfas '''ciii###### ''' </summary> Structure STR End Structure ''' <summary> ''' ------ Class -------- ''' With nested structure ''' --------------------- ''' </summary> Class Clazz ''' <summary> ''' NestedStr ''' sadjghfcasl ''' asdf ''' 21398470912 '''ciii###### ''' </summary> Public Structure NestedStr End Structure End Class ]]> </file> </compilation>, <error></error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> GeneralDocCommentOnTypes </name> </assembly> <members> <member name="T:Module0"> <summary> Module M commented </summary> </member> <member name="T:E123"> <summary> Enum ---======7777777%%% </summary> </member> <member name="T:STR"> <summary> Structure <a></a> iusgdfas ciii###### </summary> </member> <member name="T:Clazz"> <summary> ------ Class -------- With nested structure --------------------- </summary> </member> <member name="T:Clazz.NestedStr"> <summary> NestedStr sadjghfcasl asdf 21398470912 ciii###### </summary> </member> </members> </doc> ]]> </xml>) End Sub <Fact> Public Sub MultipartDocCommentOnTypes() CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System ''' <summary> ''' Class Part #1 ''' -=-=-=-=-=-=- <aaa> ' Error -- unended tag ''' (o) ''' </summary> Public Partial Class Clazz End Class ''' <summary> ''' (o) ''' Class Part #2 ''' -=-=-=-=-=-=- ''' </summary> Public Partial Class Clazz End Class ]]> </file> </compilation>, <error> <![CDATA[ BC42314: XML comment cannot be applied more than once on a partial class. XML comments for this class will be ignored. ''' <summary> ~~~~~~~~~~~ BC42304: XML documentation parse error: Element is missing an end tag. XML comment will be ignored. ''' -=-=-=-=-=-=- <aaa> ' Error -- unended tag ~~~~~ BC42304: XML documentation parse error: '>' expected. XML comment will be ignored. ''' </summary> ~ BC42304: XML documentation parse error: Expected beginning '<' for an XML tag. XML comment will be ignored. ''' </summary> ~ BC42304: XML documentation parse error: XML name expected. XML comment will be ignored. ''' </summary> ~ BC42314: XML comment cannot be applied more than once on a partial class. XML comments for this class will be ignored. ''' <summary> ~~~~~~~~~~~ ]]> </error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> </members> </doc> ]]> </xml>) End Sub <Fact> Public Sub DocCommentAndAccessibility() CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System ''' <summary> ''' ''' -=( Clazz(Of X, Y) )=- ''' ''' </summary> Public Class Clazz(Of X, Y) ''' <summary> ''' -=( Clazz(Of X, Y).PublicClazz )=- ''' </summary> Public Class PublicClazz End Class ''' <summary> ''' -=( Clazz(Of X, Y).PrivateClazz )=- ''' </summary> Private Class PrivateClazz End Class End Class ''' <summary> ''' ''' -=( Clazz(Of X) )=- ''' ''' </summary> Friend Class Clazz(Of X) ''' <summary> ''' -=( Clazz(Of X).PublicClazz )=- ''' </summary> Public Class PublicClazz End Class ''' <summary> ''' -=( Clazz(Of X).PrivateClazz )=- ''' </summary> Private Class PrivateClazz End Class End Class ]]> </file> </compilation>, <error></error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:Clazz`2"> <summary> -=( Clazz(Of X, Y) )=- </summary> </member> <member name="T:Clazz`2.PublicClazz"> <summary> -=( Clazz(Of X, Y).PublicClazz )=- </summary> </member> <member name="T:Clazz`2.PrivateClazz"> <summary> -=( Clazz(Of X, Y).PrivateClazz )=- </summary> </member> <member name="T:Clazz`1"> <summary> -=( Clazz(Of X) )=- </summary> </member> <member name="T:Clazz`1.PublicClazz"> <summary> -=( Clazz(Of X).PublicClazz )=- </summary> </member> <member name="T:Clazz`1.PrivateClazz"> <summary> -=( Clazz(Of X).PrivateClazz )=- </summary> </member> </members> </doc> ]]> </xml>) End Sub <ConditionalFact(GetType(DesktopOnly), Reason:="https://github.com/dotnet/roslyn/issues/18610")> Public Sub IllegalXmlInDocComment() CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System ''' <summary> ''' ''' -=( <a> )=- ''' ''' </summary> Public Class Clazz(Of X, Y) End Class ]]> </file> </compilation>, <error> <![CDATA[ BC42304: XML documentation parse error: Element is missing an end tag. XML comment will be ignored. ''' -=( <a> )=- ~~~ BC42304: XML documentation parse error: '>' expected. XML comment will be ignored. ''' </summary> ~ BC42304: XML documentation parse error: Expected beginning '<' for an XML tag. XML comment will be ignored. ''' </summary> ~ BC42304: XML documentation parse error: XML name expected. XML comment will be ignored. ''' </summary> ~ ]]> </error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> </members> </doc> ]]> </xml>) End Sub <ConditionalFact(GetType(DesktopOnly), Reason:="https://github.com/dotnet/roslyn/issues/18610")> Public Sub IllegalXmlInDocComment_Schema() CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System ''' <summary> ''' ''' -=( <a x="1" x="2"/> )=- ''' ''' </summary> Public Class Clazz(Of X, Y) End Class ]]> </file> </compilation>, <error> <![CDATA[ BC42304: XML documentation parse error: 'x' is a duplicate attribute name. XML comment will be ignored. ''' <summary> ~~~~~~~~~~~ ]]> </error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> </members> </doc> ]]> </xml>, ensureEnglishUICulture:=True) End Sub <Fact> Public Sub GeneralDocCommentOnFields() CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System ''' <summary> ''' Class ''' Clazz(Of X, Y) ''' Comment ''' </summary> Public Class Clazz(Of X, Y) ''' <summary> (* F1 *) </summary> Public F1 As Integer ''' <summary> ''' F@ 2 % ''' </summary> Private F2 As Integer End Class ]]> </file> </compilation>, <error></error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:Clazz`2"> <summary> Class Clazz(Of X, Y) Comment </summary> </member> <member name="F:Clazz`2.F1"> <summary> (* F1 *) </summary> </member> <member name="F:Clazz`2.F2"> <summary> F@ 2 % </summary> </member> </members> </doc> ]]> </xml>) End Sub <Fact> Public Sub GeneralDocCommentOnEnumConstants() CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System ''' <summary> ''' Some ''' documentation ''' comment ''' </summary> ''' <remarks></remarks> Public Enum En ''' <summary> Just the first value </summary> First ''' <summary> ''' Another value ''' </summary> ''' <remarks></remarks> Second End Enum ]]> </file> </compilation>, <error></error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:En"> <summary> Some documentation comment </summary> <remarks></remarks> </member> <member name="F:En.First"> <summary> Just the first value </summary> </member> <member name="F:En.Second"> <summary> Another value </summary> ''' <remarks></remarks> </member> </members> </doc> ]]> </xml>) End Sub <Fact> Public Sub GeneralDocCommentOnEvents() CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System ''' <summary> Class Clazz(Of X, Y) ''' </summary> Public Class ubClazz(Of X, Y) ''' <summary> ''' (* E(X) </summary> ''' <param name="f1"></param> Public Event E(f1 As X) ''' <summary> Sub P(X,Y) </summary> Private Shared Event P As Action(Of X, Y) End Class ]]> </file> </compilation>, <error></error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:ubClazz`2"> <summary> Class Clazz(Of X, Y) </summary> </member> <member name="E:ubClazz`2.E"> <summary> (* E(X) </summary> <param name="f1"></param> </member> <member name="E:ubClazz`2.P"> <summary> Sub P(X,Y) </summary> </member> </members> </doc> ]]> </xml>) End Sub <Fact> Public Sub GeneralDocCommentOnProperties() CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System ''' <summary> Class Clazz(Of X, Y) </summary> Public Class ubClazz(Of X, Y) ''' <summary> ''' P1</summary> Public Shared Property P1 As Integer ''' <summary> ''' S P(X,Y) ''' </summary> ''' <param name="A"></param> Private ReadOnly Property P2(a As Integer) As String Get Return Nothing End Get End Property End Class ]]> </file> </compilation>, <error></error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:ubClazz`2"> <summary> Class Clazz(Of X, Y) </summary> </member> <member name="P:ubClazz`2.P1"> <summary> P1</summary> </member> <member name="P:ubClazz`2.P2(System.Int32)"> <summary> S P(X,Y) </summary> <param name="A"></param> </member> </members> </doc> ]]> </xml>) End Sub <Fact> Public Sub GeneralDocCommentOnMethods() CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System ''' <summary> Class Clazz(Of X, Y) </summary> Partial Public Class Clazz(Of X, Y) ''' <summary>.cctor()</summary> Shared Sub New() End Sub ''' <summary> F32(Integer) As Integer </summary> ''' <param name="a"></param> ''' <returns></returns> Protected Function F32(a As Integer) As Integer Return Nothing End Function ''' <summary> a*b </summary> Public Shared Operator *(a As Integer, b As Clazz(Of X, Y)) As Clazz(Of Integer, Integer) Return Nothing End Operator ''' <summary>DECL: Priv1(a As Integer)</summary> Partial Private Sub Priv1(a As Integer) End Sub Partial Private Sub Priv2(a As Integer) End Sub ''' <summary>DECL: Priv3(a As Integer)</summary> Partial Private Sub Priv3(a As Integer) End Sub ''' <summary>DECL: Priv4(a As Integer)</summary> Partial Private Sub Priv4(a As Integer) End Sub End Class Partial Public Class Clazz(Of X, Y) ''' <summary>.ctor()</summary> Public Sub New() End Sub ''' <summary> integer -> Clazz(Of X, Y) </summary> Public Shared Narrowing Operator CType(a As Integer) As Clazz(Of X, Y) Return Nothing End Operator ''' <summary>IMPL: Priv1(a As Integer)</summary> Private Sub Priv1(a As Integer) End Sub ''' <summary>IMPL: Priv2(a As Integer)</summary> Private Sub Priv2(a As Integer) End Sub Private Sub Priv3(a As Integer) End Sub End Class ]]> </file> </compilation>, <error></error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:Clazz`2"> <summary> Class Clazz(Of X, Y) </summary> </member> <member name="M:Clazz`2.#cctor"> <summary>.cctor()</summary> </member> <member name="M:Clazz`2.F32(System.Int32)"> <summary> F32(Integer) As Integer </summary> <param name="a"></param> <returns></returns> </member> <member name="M:Clazz`2.op_Multiply(System.Int32,Clazz{`0,`1})"> <summary> a*b </summary> </member> <member name="M:Clazz`2.Priv1(System.Int32)"> <summary>IMPL: Priv1(a As Integer)</summary> </member> <member name="M:Clazz`2.Priv2(System.Int32)"> <summary>IMPL: Priv2(a As Integer)</summary> </member> <member name="M:Clazz`2.Priv3(System.Int32)"> <summary>DECL: Priv3(a As Integer)</summary> </member> <member name="M:Clazz`2.Priv4(System.Int32)"> <summary>DECL: Priv4(a As Integer)</summary> </member> <member name="M:Clazz`2.#ctor"> <summary>.ctor()</summary> </member> <member name="M:Clazz`2.op_Explicit(System.Int32)~Clazz{`0,`1}"> <summary> integer -> Clazz(Of X, Y) </summary> </member> </members> </doc> ]]> </xml>) End Sub <Fact> Public Sub GeneralDocCommentOnDeclMethods() CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System ''' <summary> Class [[Clazz]] </summary> Public Class Clazz ''' <summary> ''' Declared function DeclareFtn ''' </summary> Public Declare Function DeclareFtn Lib "bar" () As Integer End Class ]]> </file> </compilation>, <error></error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:Clazz"> <summary> Class [[Clazz]] </summary> </member> <member name="M:Clazz.DeclareFtn"> <summary> Declared function DeclareFtn </summary> </member> </members> </doc> ]]> </xml>) End Sub <Fact> Public Sub Tags_Summary_C_Code_Example() CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System ''' <summary> ''' Some comment here ''' and here ''' ''' <example> e.g. ''' <code> ''' ' No further processing ''' If docCommentXml Is Nothing Then ''' Debug.Assert(documentedParameters Is Nothing) ''' Debug.Assert(documentedTypeParameters Is Nothing) ''' Return False ''' End If ''' </code> ''' Returns <c>False</c> in the statement above. ''' </example> ''' ''' Done. ''' </summary> ''' <summary a="1"> ''' </summary> ''' <code> ''' If docCommentXml Is Nothing Then ''' Return False ''' End If ''' </code> ''' <example> e.g. </example> ''' Returns <c>False</c> in the statement above. Public Class Clazz End Class ]]> </file> </compilation>, <error></error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:Clazz"> <summary> Some comment here and here <example> e.g. <code> ' No further processing If docCommentXml Is Nothing Then Debug.Assert(documentedParameters Is Nothing) Debug.Assert(documentedTypeParameters Is Nothing) Return False End If </code> Returns <c>False</c> in the statement above. </example> Done. </summary> <summary a="1"> </summary> <code> If docCommentXml Is Nothing Then Return False End If </code> <example> e.g. </example> Returns <c>False</c> in the statement above. </member> </members> </doc> ]]> </xml>) End Sub <Fact> Public Sub Tags_Exception_Errors() CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System ''' <exception cref="Exception">Module0</exception> Public Module Module0 End Module ''' <summary><exception cref="Exception">E inside summary tag</exception></summary> ''' <exception cref="Exception">Clazz</exception> Public Class Clazz(Of X) ''' <summary></summary> ''' <exception cref="11111">X1</exception> Public Sub X1() End Sub ''' <summary><exception cref="Exception">E inside summary tag</exception></summary> ''' <exception cref="Exception">E</exception> Public Event E As Action ''' <summary></summary> ''' <exception cref="X">X2</exception> Public Sub X2() End Sub ''' <summary></summary> ''' <exception cref="Exception">F</exception> Public F As Integer ''' <summary></summary> ''' <exception cref="Exception">P</exception> Public Property P As Integer ''' <summary></summary> ''' <exception cref="Exception">FDelegate</exception> Public Delegate Function FDelegate(a As Integer) As String ''' <summary></summary> ''' <exception cref="Exception">En</exception> Public Enum En : A : End Enum ''' <summary></summary> ''' <exception cref="Exception">STR</exception> Public Structure STR : End Structure ''' <summary></summary> ''' <exception cref="Exception">STR</exception> Public ReadOnly Property A(x As String) As String Get Return x End Get End Property End Class ]]> </file> </compilation>, <error> <![CDATA[ BC42306: XML comment tag 'exception' is not permitted on a 'module' language element. ''' <exception cref="Exception">Module0</exception> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'exception' is not permitted on a 'class' language element. ''' <summary><exception cref="Exception">E inside summary tag</exception></summary> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'exception' is not permitted on a 'class' language element. ''' <exception cref="Exception">Clazz</exception> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute '11111' that could not be resolved. ''' <exception cref="11111">X1</exception> ~~~~~~~~~~~~ BC42375: XML comment has a tag with a 'cref' attribute 'X' that bound to a type parameter. Use the <typeparamref> tag instead. ''' <exception cref="X">X2</exception> ~~~~~~~~ BC42306: XML comment tag 'exception' is not permitted on a 'variable' language element. ''' <exception cref="Exception">F</exception> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'exception' is not permitted on a 'delegate' language element. ''' <exception cref="Exception">FDelegate</exception> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'exception' is not permitted on a 'enum' language element. ''' <exception cref="Exception">En</exception> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'exception' is not permitted on a 'structure' language element. ''' <exception cref="Exception">STR</exception> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]> </error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:Module0"> <exception cref="T:System.Exception">Module0</exception> </member> <member name="T:Clazz`1"> <summary><exception cref="T:System.Exception">E inside summary tag</exception></summary> <exception cref="T:System.Exception">Clazz</exception> </member> <member name="M:Clazz`1.X1"> <summary></summary> <exception cref="!:11111">X1</exception> </member> <member name="E:Clazz`1.E"> <summary><exception cref="T:System.Exception">E inside summary tag</exception></summary> <exception cref="T:System.Exception">E</exception> </member> <member name="M:Clazz`1.X2"> <summary></summary> <exception cref="!:X">X2</exception> </member> <member name="F:Clazz`1.F"> <summary></summary> <exception cref="T:System.Exception">F</exception> </member> <member name="P:Clazz`1.P"> <summary></summary> <exception cref="T:System.Exception">P</exception> </member> <member name="T:Clazz`1.FDelegate"> <summary></summary> <exception cref="T:System.Exception">FDelegate</exception> </member> <member name="T:Clazz`1.En"> <summary></summary> <exception cref="T:System.Exception">En</exception> </member> <member name="T:Clazz`1.STR"> <summary></summary> <exception cref="T:System.Exception">STR</exception> </member> <member name="P:Clazz`1.A(System.String)"> <summary></summary> <exception cref="T:System.Exception">STR</exception> </member> </members> </doc> ]]> </xml>) End Sub <Fact> Public Sub QualifiedCref() CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Public Class Clazz(Of X, Y) Public Class MyException : Inherits Exception ''' <summary> </summary> ''' <exception cref="MyException">Clazz(Of Integer).MyException::S</exception> Public Sub S() End Sub End Class End Class Public Class Clazz Public Class MyException : Inherits Exception ''' <summary> </summary> ''' <exception cref="MyException">Clazz(Of Integer).MyException::S</exception> Public Sub S() End Sub End Class End Class Public Module Module0 ''' <summary> </summary> ''' <exception cref="Clazz.MyException">Module0::S0</exception> Public Sub S0() End Sub ''' <summary> </summary> ''' <exception cref="Clazz(Of ).MyException">Module0::S1</exception> Public Sub S1() End Sub ''' <summary> </summary> ''' <exception cref="Clazz(Of X).MyException">Module0::S2</exception> Public Sub S2() End Sub ''' <summary> </summary> ''' <exception cref="Clazz(Of X, Y).MyException">Module0::S2</exception> Public Sub S2a() End Sub ''' <summary> </summary> ''' <exception cref="Global">Module0::S3</exception> ''' <exception cref="oBjeCt">Module0::S3:OBJECT</exception> Public Sub S3() End Sub ''' <summary> </summary> ''' <exception cref="MyOuterException">Module0::S4</exception> Public Sub S4() End Sub ''' <summary> </summary> ''' <exception cref="MyOuterException(Of )">Module0::S5</exception> Public Sub S5() End Sub ''' <summary> </summary> ''' <exception cref="MyOuterException(Of T)">Module0::S6</exception> Public Sub S6() End Sub ''' <summary> </summary> ''' <exception cref="MyOuterException(Of T, Y)">Module0::S7</exception> Public Sub S7() End Sub End Module Public Class MyOuterException(Of T) : Inherits Exception ''' <summary> </summary> ''' <exception cref="MyOuterException">MyOuterException(Of )::S</exception> Public Sub S() End Sub End Class Public Class MyOuterException : Inherits Exception ''' <summary> </summary> ''' <exception cref="MyOuterException(Of X)">MyOuterException::S</exception> Public Sub S() End Sub End Class ''' <summary><exception cref="Exception">E inside summary tag</exception></summary> Public Class Clazz(Of X) ''' <summary> </summary> ''' <exception cref="MyException">Clazz::S1</exception> Public Sub S1() End Sub ''' <summary> </summary> ''' <exception cref="System.Exception">Clazz::S2</exception> Public Sub S2() End Sub ''' <summary> </summary> ''' <exception cref="Global.System.Exception">Clazz::S3</exception> Public Sub S3() End Sub Public Class MyException : Inherits Exception ''' <summary> </summary> ''' <exception cref="MyException">MyException::S</exception> Public Sub S() End Sub End Class End Class ]]> </file> </compilation>, <error> <![CDATA[ BC42309: XML comment has a tag with a 'cref' attribute 'Clazz(Of ).MyException' that could not be resolved. ''' <exception cref="Clazz(Of ).MyException">Module0::S1</exception> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'Global' that could not be resolved. ''' <exception cref="Global">Module0::S3</exception> ~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'MyOuterException(Of )' that could not be resolved. ''' <exception cref="MyOuterException(Of )">Module0::S5</exception> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'MyOuterException(Of T, Y)' that could not be resolved. ''' <exception cref="MyOuterException(Of T, Y)">Module0::S7</exception> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'exception' is not permitted on a 'class' language element. ''' <summary><exception cref="Exception">E inside summary tag</exception></summary> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]> </error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="M:Clazz`2.MyException.S"> <summary> </summary> <exception cref="T:Clazz`2.MyException">Clazz(Of Integer).MyException::S</exception> </member> <member name="M:Clazz.MyException.S"> <summary> </summary> <exception cref="T:Clazz.MyException">Clazz(Of Integer).MyException::S</exception> </member> <member name="M:Module0.S0"> <summary> </summary> <exception cref="T:Clazz.MyException">Module0::S0</exception> </member> <member name="M:Module0.S1"> <summary> </summary> <exception cref="!:Clazz(Of ).MyException">Module0::S1</exception> </member> <member name="M:Module0.S2"> <summary> </summary> <exception cref="T:Clazz`1.MyException">Module0::S2</exception> </member> <member name="M:Module0.S2a"> <summary> </summary> <exception cref="T:Clazz`2.MyException">Module0::S2</exception> </member> <member name="M:Module0.S3"> <summary> </summary> <exception cref="!:Global">Module0::S3</exception> <exception cref="T:System.Object">Module0::S3:OBJECT</exception> </member> <member name="M:Module0.S4"> <summary> </summary> <exception cref="T:MyOuterException">Module0::S4</exception> </member> <member name="M:Module0.S5"> <summary> </summary> <exception cref="!:MyOuterException(Of )">Module0::S5</exception> </member> <member name="M:Module0.S6"> <summary> </summary> <exception cref="T:MyOuterException`1">Module0::S6</exception> </member> <member name="M:Module0.S7"> <summary> </summary> <exception cref="!:MyOuterException(Of T, Y)">Module0::S7</exception> </member> <member name="M:MyOuterException`1.S"> <summary> </summary> <exception cref="T:MyOuterException">MyOuterException(Of )::S</exception> </member> <member name="M:MyOuterException.S"> <summary> </summary> <exception cref="T:MyOuterException`1">MyOuterException::S</exception> </member> <member name="T:Clazz`1"> <summary><exception cref="T:System.Exception">E inside summary tag</exception></summary> </member> <member name="M:Clazz`1.S1"> <summary> </summary> <exception cref="T:Clazz`1.MyException">Clazz::S1</exception> </member> <member name="M:Clazz`1.S2"> <summary> </summary> <exception cref="T:System.Exception">Clazz::S2</exception> </member> <member name="M:Clazz`1.S3"> <summary> </summary> <exception cref="T:System.Exception">Clazz::S3</exception> </member> <member name="M:Clazz`1.MyException.S"> <summary> </summary> <exception cref="T:Clazz`1.MyException">MyException::S</exception> </member> </members> </doc> ]]> </xml>) End Sub <Fact> Public Sub QualifiedCref_More() CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Module Module1 Public Sub Main() End Sub Public Property PRST As String Public Event EVNT As action End Module Public Class BaseClass ''' <summary> ''' <reference cref="Module1"/> ''' <reference cref="Module1.PRST"/> ''' <reference cref="Module1.get_PRST"/> ''' <reference cref="Module1.EVNT"/> ''' <reference cref="Module1.add_EVNT"/> ''' <reference cref="BaseClass.New"/> ''' <reference cref="BaseClass.op_multiply"/> ''' <reference cref="BaseClass.op_explicit"/> ''' </summary> Public F As Integer Public Shared Operator *(bc As BaseClass, i As Integer) As BaseClass Return bc End Operator Public Shared Narrowing Operator CType(bc As BaseClass) As String Return Nothing End Operator End Class ]]> </file> </compilation>, <error> <![CDATA[ BC42309: XML comment has a tag with a 'cref' attribute 'Module1.get_PRST' that could not be resolved. ''' <reference cref="Module1.get_PRST"/> ~~~~~~~~~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'Module1.add_EVNT' that could not be resolved. ''' <reference cref="Module1.add_EVNT"/> ~~~~~~~~~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'BaseClass.New' that could not be resolved. ''' <reference cref="BaseClass.New"/> ~~~~~~~~~~~~~~~~~~~~ ]]> </error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="F:BaseClass.F"> <summary> <reference cref="T:Module1"/> <reference cref="P:Module1.PRST"/> <reference cref="!:Module1.get_PRST"/> <reference cref="E:Module1.EVNT"/> <reference cref="!:Module1.add_EVNT"/> <reference cref="!:BaseClass.New"/> <reference cref="M:BaseClass.op_Multiply(BaseClass,System.Int32)"/> <reference cref="M:BaseClass.op_Explicit(BaseClass)~System.String"/> </summary> </member> </members> </doc> ]]> </xml>) End Sub <Fact> Public Sub QualifiedCref_GenericMethod() CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System ''' <summary> ''' 1) <see cref="Foo.Method"/> ''' 2) <see cref="Foo.Method(Of T)"/> ''' 3) <see cref="Foo.Method(Of T, U)"/> ''' 4) <see cref="Foo.Method(Of )"/> ''' 5) <see cref="Foo.Method(Of ,)"/> ''' </summary> Public Class Foo Public Sub Method() End Sub End Class ]]> </file> </compilation>, <error> <![CDATA[ BC42309: XML comment has a tag with a 'cref' attribute 'Foo.Method(Of T)' that could not be resolved. ''' 2) <see cref="Foo.Method(Of T)"/> ~~~~~~~~~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'Foo.Method(Of T, U)' that could not be resolved. ''' 3) <see cref="Foo.Method(Of T, U)"/> ~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'Foo.Method(Of )' that could not be resolved. ''' 4) <see cref="Foo.Method(Of )"/> ~~~~~~~~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'Foo.Method(Of ,)' that could not be resolved. ''' 5) <see cref="Foo.Method(Of ,)"/> ~~~~~~~~~~~~~~~~~~~~~~~ ]]> </error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:Foo"> <summary> 1) <see cref="M:Foo.Method"/> 2) <see cref="!:Foo.Method(Of T)"/> 3) <see cref="!:Foo.Method(Of T, U)"/> 4) <see cref="!:Foo.Method(Of )"/> 5) <see cref="!:Foo.Method(Of ,)"/> </summary> </member> </members> </doc> ]]> </xml>) End Sub <Fact> Public Sub Cref_Scopes() CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System ' NOTE: The first "tostring" did not resolve in dev11. ''' <see cref="c.tostring"/> ''' <see cref="tostring"/> Public Class C(Of X, Y) ''' <see cref="c.tostring"/> ''' <see cref="tostring"/> Public Sub New() End Sub End Class ]]> </file> </compilation>, <error></error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:C`2"> <see cref="M:System.Object.ToString"/> <see cref="M:System.Object.ToString"/> </member> <member name="M:C`2.#ctor"> <see cref="M:System.Object.ToString"/> <see cref="M:System.Object.ToString"/> </member> </members> </doc> ]]> </xml>) End Sub <ConditionalFact(GetType(WindowsDesktopOnly), Reason:=ConditionalSkipReason.TestExecutionNeedsDesktopTypes)> Public Sub Tags_Summary_Permission_See_SeeAlso_List_Para() CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Imports System.Collections.Generic ''' <summary> ''' This is the entry point of the Point class testing program. ''' <para>This program tests each method and operator, and ''' is intended to be run after any non-trivial maintenance has ''' been performed on the Point class.</para> ''' </summary> ''' <permission cref="System.Security.PermissionSet"> ''' Everyone can access this class.<see cref="List(Of X)"/> ''' </permission> Public Class TestClass ''' <remarks> ''' Here is an example of a bulleted list: ''' <list type="bullet"> ''' <listheader> ''' <term>term</term> ''' <description>description</description> ''' </listheader> ''' <item> ''' <term>A</term> ''' <description>Item 1.</description> ''' </item> ''' <item> ''' <description>Item 2.</description> ''' </item> ''' </list> ''' </remarks> ''' <list type="bullet"> ''' <item> ''' <description>Item 1.</description> ''' <seealso cref="TestClass"/> ''' </item> ''' </list> Public Shared Sub Main() Dim a As TestClass = Nothing End Sub End Class ]]> </file> </compilation>, <error></error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:TestClass"> <summary> This is the entry point of the Point class testing program. <para>This program tests each method and operator, and is intended to be run after any non-trivial maintenance has been performed on the Point class.</para> </summary> <permission cref="T:System.Security.PermissionSet"> Everyone can access this class.<see cref="T:System.Collections.Generic.List`1"/> </permission> </member> <member name="M:TestClass.Main"> <remarks> Here is an example of a bulleted list: <list type="bullet"> <listheader> <term>term</term> <description>description</description> </listheader> <item> <term>A</term> <description>Item 1.</description> </item> <item> <description>Item 2.</description> </item> </list> </remarks> <list type="bullet"> <item> <description>Item 1.</description> <seealso cref="T:TestClass"/> </item> </list> </member> </members> </doc> ]]> </xml>) End Sub <Fact> Public Sub Tags_ParamRef() CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Imports System.Collections.Generic ''' <summary> ''' <paramref name="P1"></paramref> ''' </summary> ''' <paramref name="P2"></paramref> Public Class TestClass ''' <summary> ''' <paramref name="P3"></paramref> ''' </summary> ''' <paramref name="P4"></paramref> ''' <paramref></paramref> Public Shared Sub M(p3 As Integer, p4 As String) Dim a As TestClass = Nothing End Sub ''' <summary> ''' <paramref name="P5"></paramref> ''' </summary> ''' <paramref name="P6"></paramref> Public F As Integer ''' <summary> ''' <paramref name="P7"></paramref> ''' </summary> ''' <paramref name="P8"></paramref> Public Property P As Integer ''' <summary> ''' <paramref name="P9"></paramref> ''' </summary> ''' <paramref name="P10"></paramref> Public ReadOnly Property P(P9 As String) As Integer Get Return Nothing End Get End Property ''' <summary> ''' <paramref name="P11"></paramref> ''' </summary> ''' <paramref name="P12"></paramref> Public Event EE(p11 As String) End Class ]]> </file> </compilation>, <error> <![CDATA[ BC42306: XML comment tag 'paramref' is not permitted on a 'class' language element. ''' <paramref name="P1"></paramref> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'paramref' is not permitted on a 'class' language element. ''' <paramref name="P2"></paramref> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'paramref' is not permitted on a 'variable' language element. ''' <paramref name="P5"></paramref> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'paramref' is not permitted on a 'variable' language element. ''' <paramref name="P6"></paramref> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42307: XML comment parameter 'P7' does not match a parameter on the corresponding 'property' statement. ''' <paramref name="P7"></paramref> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42307: XML comment parameter 'P8' does not match a parameter on the corresponding 'property' statement. ''' <paramref name="P8"></paramref> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42307: XML comment parameter 'P10' does not match a parameter on the corresponding 'property' statement. ''' <paramref name="P10"></paramref> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42307: XML comment parameter 'P12' does not match a parameter on the corresponding 'event' statement. ''' <paramref name="P12"></paramref> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]> </error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:TestClass"> <summary> <paramref name="P1"></paramref> </summary> <paramref name="P2"></paramref> </member> <member name="M:TestClass.M(System.Int32,System.String)"> <summary> <paramref name="P3"></paramref> </summary> <paramref name="P4"></paramref> <paramref></paramref> </member> <member name="F:TestClass.F"> <summary> <paramref name="P5"></paramref> </summary> <paramref name="P6"></paramref> </member> <member name="P:TestClass.P"> <summary> <paramref name="P7"></paramref> </summary> <paramref name="P8"></paramref> </member> <member name="P:TestClass.P(System.String)"> <summary> <paramref name="P9"></paramref> </summary> <paramref name="P10"></paramref> </member> <member name="E:TestClass.EE"> <summary> <paramref name="P11"></paramref> </summary> <paramref name="P12"></paramref> </member> </members> </doc> ]]> </xml>) End Sub <Fact> Public Sub Tags_ParamRef_NoErrors() CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Imports System.Collections.Generic ''' <summary> ''' <paramref name="P1"></paramref> ''' </summary> ''' <paramref name="P2"></paramref> Public Class TestClass ''' <summary> ''' <paramref name="P3"></paramref> ''' </summary> ''' <paramref name="P4"></paramref> ''' <paramref></paramref> Public Shared Sub M(p3 As Integer, p4 As String) Dim a As TestClass = Nothing End Sub ''' <summary> ''' <paramref name="P5"></paramref> ''' </summary> ''' <paramref name="P6"></paramref> Public F As Integer ''' <summary> ''' <paramref name="P7"></paramref> ''' </summary> ''' <paramref name="P8"></paramref> Public Property P As Integer ''' <summary> ''' <paramref name="P9"></paramref> ''' </summary> ''' <paramref name="P10"></paramref> Public ReadOnly Property P(P9 As String) As Integer Get Return Nothing End Get End Property ''' <summary> ''' <paramref name="P11"></paramref> ''' </summary> ''' <paramref name="P12"></paramref> Public Event EE(p11 As String) End Class ]]> </file> </compilation>, <error></error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:TestClass"> <summary> <paramref name="P1"></paramref> </summary> <paramref name="P2"></paramref> </member> <member name="M:TestClass.M(System.Int32,System.String)"> <summary> <paramref name="P3"></paramref> </summary> <paramref name="P4"></paramref> <paramref></paramref> </member> <member name="F:TestClass.F"> <summary> <paramref name="P5"></paramref> </summary> <paramref name="P6"></paramref> </member> <member name="P:TestClass.P"> <summary> <paramref name="P7"></paramref> </summary> <paramref name="P8"></paramref> </member> <member name="P:TestClass.P(System.String)"> <summary> <paramref name="P9"></paramref> </summary> <paramref name="P10"></paramref> </member> <member name="E:TestClass.EE"> <summary> <paramref name="P11"></paramref> </summary> <paramref name="P12"></paramref> </member> </members> </doc> ]]> </xml>, withDiagnostics:=False) End Sub <Fact> Public Sub Tags_Returns() CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Imports System.Collections.Generic ''' <summary> ''' <paramref name="P1"></paramref> ''' </summary> ''' <returns>TestClass</returns> Public Class TestClass ''' <returns>EN</returns> Public Enum EN : A : End Enum ''' <returns>DelSub</returns> Public Delegate Sub DelSub(a As Integer) ''' <returns>DelFunc</returns> Public Delegate Function DelFunc(a As Integer) As Integer ''' <returns>MSub</returns> Public Shared Sub MSub(p3 As Integer, p4 As String) End Sub ''' <returns>MFunc</returns> Public Shared Function MFunc(p3 As Integer, p4 As String) As Integer Return Nothing End Function ''' <summary><returns nested="true">Field</returns></summary> ''' <returns>Field</returns> Public Field As Integer ''' <returns>FieldWE</returns> WithEvents FieldWE As TestClass ''' <returns>DeclareFtn</returns> Public Declare Function DeclareFtn Lib "bar" () As Integer ''' <returns>DeclareSub</returns> Public Declare Sub DeclareSub Lib "bar" () ''' <returns>PReadOnly</returns> Public ReadOnly Property PReadOnly As Integer Get Return Nothing End Get End Property ''' <returns>PReadWrite</returns> Public Property PReadWrite As Integer Get Return Nothing End Get Set(value As Integer) End Set End Property ''' <returns>PWriteOnly</returns> Public WriteOnly Property PWriteOnly As Integer Set(value As Integer) End Set End Property ''' <returns>EE</returns> Public Event EE(p11 As String) End Class ]]> </file> </compilation>, <error> <![CDATA[ BC42306: XML comment tag 'paramref' is not permitted on a 'class' language element. ''' <paramref name="P1"></paramref> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'returns' is not permitted on a 'class' language element. ''' <returns>TestClass</returns> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'returns' is not permitted on a 'enum' language element. ''' <returns>EN</returns> ~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'returns' is not permitted on a 'delegate sub' language element. ''' <returns>DelSub</returns> ~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'returns' is not permitted on a 'sub' language element. ''' <returns>MSub</returns> ~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'returns' is not permitted on a 'variable' language element. ''' <summary><returns nested="true">Field</returns></summary> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'returns' is not permitted on a 'variable' language element. ''' <returns>Field</returns> ~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'returns' is not permitted on a 'WithEvents variable' language element. ''' <returns>FieldWE</returns> ~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42315: XML comment tag 'returns' is not permitted on a 'declare sub' language element. ''' <returns>DeclareSub</returns> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42313: XML comment tag 'returns' is not permitted on a 'WriteOnly' Property. ''' <returns>PWriteOnly</returns> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'returns' is not permitted on a 'event' language element. ''' <returns>EE</returns> ~~~~~~~~~~~~~~~~~~~~~ ]]> </error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:TestClass"> <summary> <paramref name="P1"></paramref> </summary> <returns>TestClass</returns> </member> <member name="T:TestClass.EN"> <returns>EN</returns> </member> <member name="T:TestClass.DelSub"> <returns>DelSub</returns> </member> <member name="T:TestClass.DelFunc"> <returns>DelFunc</returns> </member> <member name="M:TestClass.MSub(System.Int32,System.String)"> <returns>MSub</returns> </member> <member name="M:TestClass.MFunc(System.Int32,System.String)"> <returns>MFunc</returns> </member> <member name="F:TestClass.Field"> <summary><returns nested="true">Field</returns></summary> <returns>Field</returns> </member> <member name="F:TestClass._FieldWE"> <returns>FieldWE</returns> </member> <member name="M:TestClass.DeclareFtn"> <returns>DeclareFtn</returns> </member> <member name="M:TestClass.DeclareSub"> <returns>DeclareSub</returns> </member> <member name="P:TestClass.PReadOnly"> <returns>PReadOnly</returns> </member> <member name="P:TestClass.PReadWrite"> <returns>PReadWrite</returns> </member> <member name="P:TestClass.PWriteOnly"> <returns>PWriteOnly</returns> </member> <member name="E:TestClass.EE"> <returns>EE</returns> </member> </members> </doc> ]]> </xml>) End Sub <Fact> Public Sub Tags_Param() CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Imports System.Collections.Generic ''' <summary><param name="P_outer + aaa">@TestClass</param></summary> ''' <param name="P">@TestClass</param> Public Class TestClass ''' <param name="P">@EN</param> Public Enum EN : A : End Enum ''' <param name="a">@DelSub</param> Public Delegate Sub DelSub(a As Integer) ''' <param name="a">@DelFunc</param> ''' <summary><param name="P_outer + aaa">@TestClass</param></summary> Public Delegate Function DelFunc(a As Integer) As Integer ''' <param name="a">@MSub</param> Public Shared Sub MSub(p3 As Integer, p4 As String) End Sub ''' <param name="">@MSubWithErrors1</param> Public Shared Sub MSubWithErrors1(p3 As Integer, p4 As String) End Sub ''' <param name="1">@MSubWithErrors2</param> Public Shared Sub MSubWithErrors2(p3 As Integer, p4 As String) End Sub ''' <param>@MSubWithErrors3</param> Public Shared Sub MSubWithErrors3(p3 As Integer, p4 As String) End Sub ''' <param name="p3">@MFunc</param> Public Shared Function MFunc(p3 As Integer, p4 As String) As Integer Return Nothing End Function ''' <param name="p3">@Field</param> Public Field As Integer ''' <param name="p3">@DeclareFtn</param> Public Declare Function DeclareFtn Lib "bar" (p3 As Integer) As Integer ''' <param name="p">@PReadOnly</param> Public ReadOnly Property PReadOnly(p As Integer) As Integer Get Return Nothing End Get End Property ''' <param name="p">@PReadWrite</param> Public Property PReadWrite As Integer ''' <param name="ppp">@EVE</param> Public Event EVE(ppp As Integer) ''' <param name="paramName">@EVE2</param> Public Event EVE2 As Action(Of Integer) ''' <param name="arg1">@EVE3</param> ''' <param name="arg2">@EVE3</param> Public Event EVE3 As Action(Of Integer, Integer) End Class ]]> </file> </compilation>, <error> <![CDATA[ BC42306: XML comment tag 'param' is not permitted on a 'class' language element. ''' <summary><param name="P_outer + aaa">@TestClass</param></summary> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'param' is not permitted on a 'class' language element. ''' <param name="P">@TestClass</param> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'param' is not permitted on a 'enum' language element. ''' <param name="P">@EN</param> ~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42307: XML comment parameter 'P_outer + aaa' does not match a parameter on the corresponding 'function' statement. ''' <summary><param name="P_outer + aaa">@TestClass</param></summary> ~~~~~~~~~~~~~~~~~~~~ BC42307: XML comment parameter 'a' does not match a parameter on the corresponding 'sub' statement. ''' <param name="a">@MSub</param> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42307: XML comment parameter '' does not match a parameter on the corresponding 'sub' statement. ''' <param name="">@MSubWithErrors1</param> ~~~~~~~ BC42307: XML comment parameter '1' does not match a parameter on the corresponding 'sub' statement. ''' <param name="1">@MSubWithErrors2</param> ~~~~~~~~ BC42308: XML comment parameter must have a 'name' attribute. ''' <param>@MSubWithErrors3</param> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'param' is not permitted on a 'variable' language element. ''' <param name="p3">@Field</param> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42307: XML comment parameter 'p' does not match a parameter on the corresponding 'property' statement. ''' <param name="p">@PReadWrite</param> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42307: XML comment parameter 'paramName' does not match a parameter on the corresponding 'event' statement. ''' <param name="paramName">@EVE2</param> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]> </error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:TestClass"> <summary><param name="P_outer + aaa">@TestClass</param></summary> <param name="P">@TestClass</param> </member> <member name="T:TestClass.EN"> <param name="P">@EN</param> </member> <member name="T:TestClass.DelSub"> <param name="a">@DelSub</param> </member> <member name="T:TestClass.DelFunc"> <param name="a">@DelFunc</param> <summary><param name="P_outer + aaa">@TestClass</param></summary> </member> <member name="M:TestClass.MSub(System.Int32,System.String)"> <param name="a">@MSub</param> </member> <member name="M:TestClass.MSubWithErrors1(System.Int32,System.String)"> <param name="">@MSubWithErrors1</param> </member> <member name="M:TestClass.MSubWithErrors2(System.Int32,System.String)"> <param name="1">@MSubWithErrors2</param> </member> <member name="M:TestClass.MSubWithErrors3(System.Int32,System.String)"> <param>@MSubWithErrors3</param> </member> <member name="M:TestClass.MFunc(System.Int32,System.String)"> <param name="p3">@MFunc</param> </member> <member name="F:TestClass.Field"> <param name="p3">@Field</param> </member> <member name="M:TestClass.DeclareFtn(System.Int32)"> <param name="p3">@DeclareFtn</param> </member> <member name="P:TestClass.PReadOnly(System.Int32)"> <param name="p">@PReadOnly</param> </member> <member name="P:TestClass.PReadWrite"> <param name="p">@PReadWrite</param> </member> <member name="E:TestClass.EVE"> <param name="ppp">@EVE</param> </member> <member name="E:TestClass.EVE2"> <param name="paramName">@EVE2</param> </member> <member name="E:TestClass.EVE3"> <param name="arg1">@EVE3</param> <param name="arg2">@EVE3</param> </member> </members> </doc> ]]> </xml>) End Sub <Fact> Public Sub Tags_Param_10Plus() CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Imports System.Collections.Generic Public Class TestClass ''' <param name="a1"/> ''' <param name="a14"/> Private Sub PS(a0 As Integer, 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) End Sub End Class ]]> </file> </compilation>, <error></error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="M:TestClass.PS(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)"> <param name="a1"/> <param name="a14"/> </member> </members> </doc> ]]> </xml>) End Sub <Fact> Public Sub Tags_Value() CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Imports System.Collections.Generic ''' <summary><param name="P_outer + aaa"/>@TestClass</summary> ''' <value>@TestClass</value> Public Class TestClass ''' <value>@EN</value> Public Enum EN : A : End Enum ''' <value>@STR</value> Public Structure STR : End Structure ''' <value>@INTERF</value> Public Interface INTERF : End Interface ''' <value>@DelSub</value> Public Delegate Sub DelSub(a As Integer) ''' <value>@DelFunc</value> Public Delegate Function DelFunc(a As Integer) As Integer ''' <value>@MSub</value> Public Shared Sub MSub(p3 As Integer, p4 As String) End Sub ''' <value>@MFunc</value> Public Shared Function MFunc(p3 As Integer, p4 As String) As Integer Return Nothing End Function ''' <value>@DeclareFtn</value> Public Declare Function DeclareFtn Lib "bar" (p3 As Integer) As Integer ''' <value>@Field</value> Public Field As Integer ''' <value>@PWriteOnly</value> Public WriteOnly Property PWriteOnly(p As Integer) As Integer Set(value As Integer) End Set End Property ''' <value>@PReadWrite</value> Public Property PReadWrite As Integer ''' <value>@EVE</value> Public Event EVE(ppp As Integer) End Class ]]> </file> </compilation>, <error> <![CDATA[ BC42306: XML comment tag 'param' is not permitted on a 'class' language element. ''' <summary><param name="P_outer + aaa"/>@TestClass</summary> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'value' is not permitted on a 'class' language element. ''' <value>@TestClass</value> ~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'value' is not permitted on a 'enum' language element. ''' <value>@EN</value> ~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'value' is not permitted on a 'structure' language element. ''' <value>@STR</value> ~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'value' is not permitted on a 'interface' language element. ''' <value>@INTERF</value> ~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'value' is not permitted on a 'delegate' language element. ''' <value>@DelSub</value> ~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'value' is not permitted on a 'delegate' language element. ''' <value>@DelFunc</value> ~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'value' is not permitted on a 'sub' language element. ''' <value>@MSub</value> ~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'value' is not permitted on a 'function' language element. ''' <value>@MFunc</value> ~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'value' is not permitted on a 'declare' language element. ''' <value>@DeclareFtn</value> ~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'value' is not permitted on a 'variable' language element. ''' <value>@Field</value> ~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'value' is not permitted on a 'event' language element. ''' <value>@EVE</value> ~~~~~~~~~~~~~~~~~~~ ]]> </error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:TestClass"> <summary><param name="P_outer + aaa"/>@TestClass</summary> <value>@TestClass</value> </member> <member name="T:TestClass.EN"> <value>@EN</value> </member> <member name="T:TestClass.STR"> <value>@STR</value> </member> <member name="T:TestClass.INTERF"> <value>@INTERF</value> </member> <member name="T:TestClass.DelSub"> <value>@DelSub</value> </member> <member name="T:TestClass.DelFunc"> <value>@DelFunc</value> </member> <member name="M:TestClass.MSub(System.Int32,System.String)"> <value>@MSub</value> </member> <member name="M:TestClass.MFunc(System.Int32,System.String)"> <value>@MFunc</value> </member> <member name="M:TestClass.DeclareFtn(System.Int32)"> <value>@DeclareFtn</value> </member> <member name="F:TestClass.Field"> <value>@Field</value> </member> <member name="P:TestClass.PWriteOnly(System.Int32)"> <value>@PWriteOnly</value> </member> <member name="P:TestClass.PReadWrite"> <value>@PReadWrite</value> </member> <member name="E:TestClass.EVE"> <value>@EVE</value> </member> </members> </doc> ]]> </xml>) End Sub <Fact> Public Sub Tags_TypeParam() CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Imports System.Collections.Generic ''' <typeparam name="X">@Module0</typeparam> Public Module Module0 End Module ''' <summary><param name="P_outer + aaa"/>@TestClass</summary> ''' <typeparam>@TestClass</typeparam> Public Class TestClass ''' <typeparam name="X">@EN</typeparam> Public Enum EN : A : End Enum ''' <typeparam name="X">@STR</typeparam> Public Structure STR(Of X) : End Structure ''' <typeparam name="Y">@INTERF</typeparam> Public Interface INTERF(Of X, Y) : End Interface ''' <typeparam name="W">@DelSub</typeparam> Public Delegate Sub DelSub(Of W)(a As Integer) ''' <typeparam name="UV">@DelFunc</typeparam> Public Delegate Function DelFunc(Of W)(a As Integer) As Integer ''' <typeparam name="TT">@MSub</typeparam> Public Shared Sub MSub(Of TT)(p3 As Integer, p4 As String) End Sub ''' <typeparam name="TT">@MFunc</typeparam> Public Shared Function MFunc(p3 As Integer, p4 As String) As Integer Return Nothing End Function ''' <typeparam name="TT">@Field</typeparam> Public Field As Integer ''' <typeparam name="TT">@DeclareFtn</typeparam> Public Declare Function DeclareFtn Lib "bar" (p3 As Integer) As Integer ''' <typeparam name="TT">@PWriteOnly</typeparam> Public WriteOnly Property PWriteOnly(p As Integer) As Integer Set(value As Integer) End Set End Property ''' <typeparam name="TT">@PReadWrite</typeparam> Public Property PReadWrite As Integer ''' <typeparam name="TT">@EVE</typeparam> Public Event EVE(ppp As Integer) End Class ]]> </file> </compilation>, <error> <![CDATA[ BC42306: XML comment tag 'typeparam' is not permitted on a 'module' language element. ''' <typeparam name="X">@Module0</typeparam> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'param' is not permitted on a 'class' language element. ''' <summary><param name="P_outer + aaa"/>@TestClass</summary> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42318: XML comment type parameter must have a 'name' attribute. ''' <typeparam>@TestClass</typeparam> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'typeparam' is not permitted on a 'enum' language element. ''' <typeparam name="X">@EN</typeparam> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42317: XML comment type parameter 'UV' does not match a type parameter on the corresponding 'delegate' statement. ''' <typeparam name="UV">@DelFunc</typeparam> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42317: XML comment type parameter 'TT' does not match a type parameter on the corresponding 'function' statement. ''' <typeparam name="TT">@MFunc</typeparam> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'typeparam' is not permitted on a 'variable' language element. ''' <typeparam name="TT">@Field</typeparam> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'typeparam' is not permitted on a 'declare' language element. ''' <typeparam name="TT">@DeclareFtn</typeparam> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'typeparam' is not permitted on a 'property' language element. ''' <typeparam name="TT">@PWriteOnly</typeparam> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'typeparam' is not permitted on a 'property' language element. ''' <typeparam name="TT">@PReadWrite</typeparam> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'typeparam' is not permitted on a 'event' language element. ''' <typeparam name="TT">@EVE</typeparam> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]> </error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:Module0"> <typeparam name="X">@Module0</typeparam> </member> <member name="T:TestClass"> <summary><param name="P_outer + aaa"/>@TestClass</summary> <typeparam>@TestClass</typeparam> </member> <member name="T:TestClass.EN"> <typeparam name="X">@EN</typeparam> </member> <member name="T:TestClass.STR`1"> <typeparam name="X">@STR</typeparam> </member> <member name="T:TestClass.INTERF`2"> <typeparam name="Y">@INTERF</typeparam> </member> <member name="T:TestClass.DelSub`1"> <typeparam name="W">@DelSub</typeparam> </member> <member name="T:TestClass.DelFunc`1"> <typeparam name="UV">@DelFunc</typeparam> </member> <member name="M:TestClass.MSub``1(System.Int32,System.String)"> <typeparam name="TT">@MSub</typeparam> </member> <member name="M:TestClass.MFunc(System.Int32,System.String)"> <typeparam name="TT">@MFunc</typeparam> </member> <member name="F:TestClass.Field"> <typeparam name="TT">@Field</typeparam> </member> <member name="M:TestClass.DeclareFtn(System.Int32)"> <typeparam name="TT">@DeclareFtn</typeparam> </member> <member name="P:TestClass.PWriteOnly(System.Int32)"> <typeparam name="TT">@PWriteOnly</typeparam> </member> <member name="P:TestClass.PReadWrite"> <typeparam name="TT">@PReadWrite</typeparam> </member> <member name="E:TestClass.EVE"> <typeparam name="TT">@EVE</typeparam> </member> </members> </doc> ]]> </xml>) End Sub <Fact> Public Sub BC42300WRN_XMLDocBadXMLLine() CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Option Explicit On Imports System Class C1 '''<remarks>this XML comment does not immediately appear before any type</remarks> '''<remarks>Line#2</remarks> ' this is a regular comment Interface I1 End Interface End Class ]]> </file> </compilation>, <error> <![CDATA[ BC42301: Only one XML comment block is allowed per language element. '''<remarks>this XML comment does not immediately appear before any type</remarks> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42300: XML comment block must immediately precede the language element to which it applies. XML comment will be ignored. '''<remarks>Line#2</remarks> ~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]> </error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> </members> </doc> ]]> </xml>) End Sub <Fact> Public Sub BC42301WRN_XMLDocMoreThanOneCommentBlock() CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Option Explicit On Imports System '''<remarks>Line#1</remarks> 'comment '''<remarks>Line#2</remarks> Class C1 ' this is a regular comment '''<remarks>this XML comment does not immediately appear before any type</remarks> '''<remarks>Line#2</remarks> Interface I1 End Interface End Class ]]> </file> </compilation>, <error> <![CDATA[ BC42301: Only one XML comment block is allowed per language element. '''<remarks>Line#1</remarks> ~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42301: Only one XML comment block is allowed per language element. '''<remarks>this XML comment does not immediately appear before any type</remarks> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]> </error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:C1"> <remarks>Line#2</remarks> </member> <member name="T:C1.I1"> <remarks>Line#2</remarks> </member> </members> </doc> ]]> </xml>) End Sub <Fact> Public Sub WRN_XMLDocInsideMethod() CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Option Explicit On Imports System Module Module11 Public x As Object = Function() ''' Return 1 End Function Public y As Object = Function() _ ''' _ Sub Main2() ''' End Sub Public Property PPP As Object = Function() 1 ''' 1 Public Property PPP2 As Object = Function() ''' Return 1 End Function End Module ]]> </file> </compilation>, <error> <![CDATA[ BC42303: XML comment cannot appear within a method or a property. XML comment will be ignored. ''' ~ BC36674: Multiline lambda expression is missing 'End Function'. Public y As Object = Function() _ ~~~~~~~~~~ BC42105: Function '<anonymous method>' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used. Public y As Object = Function() _ ~ BC42303: XML comment cannot appear within a method or a property. XML comment will be ignored. ''' ~ BC42302: XML comment must be the first statement on a line. XML comment will be ignored. Public Property PPP As Object = Function() 1 ''' 1 ~~~~~ BC42303: XML comment cannot appear within a method or a property. XML comment will be ignored. ''' ~~ ]]> </error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="M:Module11.Main2"> _ </member> </members> </doc> ]]> </xml>) End Sub <Fact> Public Sub WRN_XMLDocInsideMethod_NoError() CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Option Explicit On Imports System Module Module11 Public x As Object = Function() ''' Return 1 End Function Public y As Object = Function() _ ''' _ Sub Main2() ''' End Sub Public Property PPP As Object = Function() 1 ''' 1 Public Property PPP2 As Object = Function() ''' Return 1 End Function End Module ]]> </file> </compilation>, <error> <![CDATA[ BC36674: Multiline lambda expression is missing 'End Function'. Public y As Object = Function() _ ~~~~~~~~~~ BC42105: Function '<anonymous method>' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used. Public y As Object = Function() _ ~ ]]> </error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="M:Module11.Main2"> _ </member> </members> </doc> ]]> </xml>, withDiagnostics:=False) End Sub <ConditionalFact(GetType(WindowsDesktopOnly), Reason:=ConditionalSkipReason.TestExecutionNeedsDesktopTypes)> Public Sub BC42305WRN_XMLDocDuplicateXMLNode() CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Option Explicit On Imports System ''' <summary cref="a b"> ''' </summary> ''' <typeparam name="X"></typeparam> ''' <typeparam name=" X " /> ''' <typeparam name="Y"></typeparam> ''' <typeparam name="X"></typeparam> ''' <summary cref="a B "/> ''' <summary cref=" a b "/> Public Class C(Of X, Y) ''' <include file=" a.vb" path=" c:\ww "/> ''' <include path="c:\ww" file="a.vb"/> Public FLD As String ''' <mysummary cref="SSS"></mysummary> Public FLD2 As String ''' <param name="x"></param> ''' <param name="x"></param> Public Sub SSS(x As Integer) End Sub ''' <remarks x=" A" y="" z = "B"></remarks> ''' <remarks y="" z = "B" x="A "/> ''' <remarks y=" " z = "B" x="a"/> ''' <remarks y=" " x="A" z = "B"/> Public F As Integer ''' <returns what="a"></returns> ''' <returns what="b"></returns> ''' <returns what=" b "/> Public Shared Operator -(a As C(Of X, Y), b As Integer) As C(Of X, Y) Return Nothing End Operator ''' <permission cref="System.Security.PermissionSet"/> ''' <permission cref="System.Security.PermissionSet "></permission> ''' <permission cref="System.Security. PermissionSet"></permission> Public Shared Narrowing Operator CType(a As C(Of X, Y)) As Integer Return Nothing End Operator End Class ''' <remarks x=" A" y=""></remarks> ''' <remarks y="" x="A "/> Module M ''' <remarks></remarks> ''' <remarks/> ''' <param name="x"></param> ''' <param name="x"></param> Public Event A(x As Integer, x As Integer) ''' <param name="a" noname="b"></param> ''' <param noname=" b " name="a"></param> ''' <value></value> ''' <value/> Public WriteOnly Property PROP(a As String) As String Set(value As String) End Set End Property End Module ]]> </file> </compilation>, <error> <![CDATA[ BC42309: XML comment has a tag with a 'cref' attribute 'a b' that could not be resolved. ''' <summary cref="a b"> ~~~~~~~~~~ BC42305: XML comment tag 'typeparam' appears with identical attributes more than once in the same XML comment block. ''' <typeparam name=" X " /> ~~~~~~~~~~~~~~~~~~~~~~~~ BC42305: XML comment tag 'typeparam' appears with identical attributes more than once in the same XML comment block. ''' <typeparam name="X"></typeparam> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'a B' that could not be resolved. ''' <summary cref="a B "/> ~~~~~~~~~~~ BC42305: XML comment tag 'summary' appears with identical attributes more than once in the same XML comment block. ''' <summary cref=" a b "/> ~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute ' a b' that could not be resolved. ''' <summary cref=" a b "/> ~~~~~~~~~~~~~~~~ BC42305: XML comment tag 'include' appears with identical attributes more than once in the same XML comment block. ''' <include path="c:\ww" file="a.vb"/> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42305: XML comment tag 'param' appears with identical attributes more than once in the same XML comment block. ''' <param name="x"></param> ~~~~~~~~~~~~~~~~~~~~~~~~ BC42305: XML comment tag 'remarks' appears with identical attributes more than once in the same XML comment block. ''' <remarks y="" z = "B" x="A "/> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42305: XML comment tag 'remarks' appears with identical attributes more than once in the same XML comment block. ''' <remarks y=" " x="A" z = "B"/> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42305: XML comment tag 'returns' appears with identical attributes more than once in the same XML comment block. ''' <returns what=" b "/> ~~~~~~~~~~~~~~~~~~~~~~ BC42305: XML comment tag 'permission' appears with identical attributes more than once in the same XML comment block. ''' <permission cref="System.Security.PermissionSet "></permission> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42305: XML comment tag 'remarks' appears with identical attributes more than once in the same XML comment block. ''' <remarks y="" x="A "/> ~~~~~~~~~~~~~~~~~~~~~~~~~ BC42305: XML comment tag 'remarks' appears with identical attributes more than once in the same XML comment block. ''' <remarks/> ~~~~~~~~~~ BC42305: XML comment tag 'param' appears with identical attributes more than once in the same XML comment block. ''' <param noname=" b " name="a"></param> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42305: XML comment tag 'value' appears with identical attributes more than once in the same XML comment block. ''' <value/> ~~~~~~~~ ]]> </error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:C`2"> <summary cref="!:a b"> </summary> <typeparam name="X"></typeparam> <typeparam name=" X " /> <typeparam name="Y"></typeparam> <typeparam name="X"></typeparam> <summary cref="!:a B "/> <summary cref="!: a b "/> </member> <member name="F:C`2.FLD"> <!--warning BC42321: Unable to include XML fragment ' c:\ww ' of file ' a.vb'. File not found.--> <!--warning BC42321: Unable to include XML fragment 'c:\ww' of file 'a.vb'. File not found.--> </member> <member name="F:C`2.FLD2"> <mysummary cref="M:C`2.SSS(System.Int32)"></mysummary> </member> <member name="M:C`2.SSS(System.Int32)"> <param name="x"></param> <param name="x"></param> </member> <member name="F:C`2.F"> <remarks x=" A" y="" z = "B"></remarks> <remarks y="" z = "B" x="A "/> <remarks y=" " z = "B" x="a"/> <remarks y=" " x="A" z = "B"/> </member> <member name="M:C`2.op_Subtraction(C{`0,`1},System.Int32)"> <returns what="a"></returns> <returns what="b"></returns> <returns what=" b "/> </member> <member name="M:C`2.op_Explicit(C{`0,`1})~System.Int32"> <permission cref="T:System.Security.PermissionSet"/> <permission cref="T:System.Security.PermissionSet"></permission> <permission cref="T:System.Security.PermissionSet"></permission> </member> <member name="T:M"> <remarks x=" A" y=""></remarks> <remarks y="" x="A "/> </member> <member name="E:M.A"> <remarks></remarks> <remarks/> <param name="x"></param> <param name="x"></param> </member> <member name="P:M.PROP(System.String)"> <param name="a" noname="b"></param> <param noname=" b " name="a"></param> <value></value> <value/> </member> </members> </doc> ]]> </xml>, ensureEnglishUICulture:=True) End Sub <ConditionalFact(GetType(WindowsDesktopOnly), Reason:=ConditionalSkipReason.TestExecutionNeedsDesktopTypes)> Public Sub BC42305WRN_XMLDocDuplicateXMLNode_NoError() CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Option Explicit On Imports System ''' <summary cref="a b"> ''' </summary> ''' <typeparam name="X"></typeparam> ''' <typeparam name=" X " /> ''' <typeparam name="Y"></typeparam> ''' <typeparam name="X"></typeparam> ''' <summary cref="a B "/> ''' <summary cref=" a b "/> Public Class C(Of X, Y) ''' <include file=" a.vb" path=" c:\ww "/> ''' <include path="c:\ww" file="a.vb"/> Public FLD As String ''' <mysummary cref="SSS"></mysummary> Public FLD2 As String ''' <param name="x"></param> ''' <param name="x"></param> Public Sub SSS(x As Integer) End Sub ''' <remarks x=" A" y="" z = "B"></remarks> ''' <remarks y="" z = "B" x="A "/> ''' <remarks y=" " z = "B" x="a"/> ''' <remarks y=" " x="A" z = "B"/> Public F As Integer ''' <returns what="a"></returns> ''' <returns what="b"></returns> ''' <returns what=" b "/> Public Shared Operator -(a As C(Of X, Y), b As Integer) As C(Of X, Y) Return Nothing End Operator ''' <permission cref="System.Security.PermissionSet"/> ''' <permission cref="System.Security.PermissionSet "></permission> ''' <permission cref="System.Security. PermissionSet"></permission> Public Shared Narrowing Operator CType(a As C(Of X, Y)) As Integer Return Nothing End Operator End Class ''' <remarks x=" A" y=""></remarks> ''' <remarks y="" x="A "/> Module M ''' <remarks></remarks> ''' <remarks/> ''' <param name="x"></param> ''' <param name="x"></param> Public Event A(x As Integer, x As Integer) ''' <param name="a" noname="b"></param> ''' <param noname=" b " name="a"></param> ''' <value></value> ''' <value/> Public WriteOnly Property PROP(a As String) As String Set(value As String) End Set End Property End Module ]]> </file> </compilation>, <error></error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:C`2"> <summary cref="!:a b"> </summary> <typeparam name="X"></typeparam> <typeparam name=" X " /> <typeparam name="Y"></typeparam> <typeparam name="X"></typeparam> <summary cref="!:a B "/> <summary cref="!: a b "/> </member> <member name="F:C`2.FLD"> <!--warning BC42321: Unable to include XML fragment ' c:\ww ' of file ' a.vb'. File not found.--> <!--warning BC42321: Unable to include XML fragment 'c:\ww' of file 'a.vb'. File not found.--> </member> <member name="F:C`2.FLD2"> <mysummary cref="M:C`2.SSS(System.Int32)"></mysummary> </member> <member name="M:C`2.SSS(System.Int32)"> <param name="x"></param> <param name="x"></param> </member> <member name="F:C`2.F"> <remarks x=" A" y="" z = "B"></remarks> <remarks y="" z = "B" x="A "/> <remarks y=" " z = "B" x="a"/> <remarks y=" " x="A" z = "B"/> </member> <member name="M:C`2.op_Subtraction(C{`0,`1},System.Int32)"> <returns what="a"></returns> <returns what="b"></returns> <returns what=" b "/> </member> <member name="M:C`2.op_Explicit(C{`0,`1})~System.Int32"> <permission cref="T:System.Security.PermissionSet"/> <permission cref="T:System.Security.PermissionSet"></permission> <permission cref="T:System.Security.PermissionSet"></permission> </member> <member name="T:M"> <remarks x=" A" y=""></remarks> <remarks y="" x="A "/> </member> <member name="E:M.A"> <remarks></remarks> <remarks/> <param name="x"></param> <param name="x"></param> </member> <member name="P:M.PROP(System.String)"> <param name="a" noname="b"></param> <param noname=" b " name="a"></param> <value></value> <value/> </member> </members> </doc> ]]> </xml>, withDiagnostics:=False, ensureEnglishUICulture:=True) End Sub <Fact> Public Sub ByRefByValOverloading() CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Public Structure TestStruct ''' <see cref="S1(ByVal TestStruct)"/> ''' <see cref="S1(ByRef TestStruct)"/> ''' <see cref="S2(ByVal TestStruct)"/> ''' <see cref="S2(ByRef TestStruct)"/> Public Shared field As Integer Public Sub S1(i As TestStruct) End Sub Public Sub S2(ByRef i As TestStruct) End Sub End Structure ]]> </file> </compilation>, <error> <![CDATA[ BC42309: XML comment has a tag with a 'cref' attribute 'S1(ByRef TestStruct)' that could not be resolved. ''' <see cref="S1(ByRef TestStruct)"/> ~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'S2(ByVal TestStruct)' that could not be resolved. ''' <see cref="S2(ByVal TestStruct)"/> ~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]> </error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="F:TestStruct.field"> <see cref="M:TestStruct.S1(TestStruct)"/> <see cref="!:S1(ByRef TestStruct)"/> <see cref="!:S2(ByVal TestStruct)"/> <see cref="M:TestStruct.S2(TestStruct@)"/> </member> </members> </doc> ]]> </xml>) End Sub <WorkItem(751828, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/751828")> <Fact()> Public Sub GetSymbolInfo_Bug_751828() Dim compilation = CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Option Explicit On Imports System Imports <xmlns="http://www.w3.org/2005/Atom"> Public Class C End Class ]]> </file> </compilation>, <error></error>) Dim tree = compilation.SyntaxTrees(0) Dim names = FindNodesOfTypeFromText(Of XmlStringSyntax)(tree, "http://www.w3.org/2005/Atom").ToArray() Assert.Equal(1, names.Length) Dim model = compilation.GetSemanticModel(tree) Dim expSymInfo1 = model.GetSymbolInfo(names(0)) Assert.True(expSymInfo1.IsEmpty) End Sub <WorkItem(768639, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768639")> <Fact()> Public Sub GetSymbolInfo_Bug_768639a() Dim compilation = CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Interface I Sub Bar() End Interface MustInherit Class C Public MustOverride Sub Bar() End Class Class B : Inherits C : Implements I ''' <see cref="Bar"/> Public Overrides Sub Bar() Implements I.Bar End Sub End Class ]]> </file> </compilation>, <error></error>) Dim tree = compilation.SyntaxTrees(0) Dim names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "Bar").ToArray() Assert.Equal(2, names.Length) Dim model = compilation.GetSemanticModel(tree) Dim expSymInfo1 = model.GetSymbolInfo(names(0)) Assert.NotNull(expSymInfo1.Symbol) End Sub <WorkItem(768639, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768639")> <Fact()> Public Sub GetSymbolInfo_Bug_768639b() Dim compilation = CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ MustInherit Class C Public MustOverride Property PPP End Class Class B : Inherits C ''' <see cref="PPP"/> Public Overrides Property PPP As Object Get Return Nothing End Get Set(value As Object) End Set End Property End Class ]]> </file> </compilation>, <error></error>) Dim tree = compilation.SyntaxTrees(0) Dim names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "PPP").ToArray() Assert.Equal(1, names.Length) Dim model = compilation.GetSemanticModel(tree) Dim expSymInfo1 = model.GetSymbolInfo(names(0)) Assert.NotNull(expSymInfo1.Symbol) End Sub <WorkItem(768639, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768639")> <Fact()> Public Sub GetSymbolInfo_Bug_768639c() Dim compilation = CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Interface I Sub Bar() End Interface MustInherit Class C Public MustOverride Sub Bar() End Class Class B : Inherits C : Implements I ''' <see cref="Bar()"/> Public Overrides Sub Bar() Implements I.Bar End Sub End Class ]]> </file> </compilation>, <error></error>) Dim tree = compilation.SyntaxTrees(0) Dim names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "Bar").ToArray() Assert.Equal(2, names.Length) Dim model = compilation.GetSemanticModel(tree) Dim expSymInfo1 = model.GetSymbolInfo(names(0)) Assert.NotNull(expSymInfo1.Symbol) End Sub <WorkItem(768639, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768639")> <Fact()> Public Sub GetSymbolInfo_Bug_768639d() Dim compilation = CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ MustInherit Class C Public MustOverride Property PPP End Class Class B : Inherits C ''' <see cref="PPP()"/> Public Overrides Property PPP As Object Get Return Nothing End Get Set(value As Object) End Set End Property End Class ]]> </file> </compilation>, <error></error>) Dim tree = compilation.SyntaxTrees(0) Dim names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "PPP").ToArray() Assert.Equal(1, names.Length) Dim model = compilation.GetSemanticModel(tree) Dim expSymInfo1 = model.GetSymbolInfo(names(0)) Assert.NotNull(expSymInfo1.Symbol) End Sub <Fact()> Public Sub GetSymbolInfo_PredefinedTypeSyntax_UShort() Dim compilation = CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Option Explicit On Imports System ''' <see cref="UShort"/> ''' <see cref="UShort.ToString()S"/> Public Class C End Class ]]> </file> </compilation>, <error></error>) Dim tree = compilation.SyntaxTrees(0) Dim names = FindNodesOfTypeFromText(Of PredefinedTypeSyntax)(tree, "UShort").ToArray() Assert.Equal(2, names.Length) Dim model = compilation.GetSemanticModel(tree) TestSymbolAndTypeInfoForType(model, names(0), compilation.GetSpecialType(SpecialType.System_UInt16)) TestSymbolAndTypeInfoForType(model, names(1), compilation.GetSpecialType(SpecialType.System_UInt16)) End Sub <Fact()> Public Sub GetSymbolInfo_PredefinedTypeSyntax_String() Dim compilation = CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Option Explicit On Imports System ''' <see cref="String"/> ''' <see cref="String.GetHashCode()S"/> Public Class C End Class ]]> </file> </compilation>, <error></error>) Dim tree = compilation.SyntaxTrees(0) Dim names = FindNodesOfTypeFromText(Of PredefinedTypeSyntax)(tree, "String").ToArray() Assert.Equal(2, names.Length) Dim model = compilation.GetSemanticModel(tree) TestSymbolAndTypeInfoForType(model, names(0), compilation.GetSpecialType(SpecialType.System_String)) TestSymbolAndTypeInfoForType(model, names(1), compilation.GetSpecialType(SpecialType.System_String)) End Sub <Fact()> Public Sub GetSymbolInfo_NameSyntax_Type() Dim compilation = CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Option Explicit On Imports System Public Class C(Of X) End Class ''' <see cref="Y"/> ' failed in dev11 ''' <see cref="S"/> ' failed in dev11 Public Class C(Of X, Y) Public FLD As String ''' <see cref="X"/> ''' <see cref="T"/> ''' <see cref="C"/> ''' <see cref="C(of x)"/> ''' <see cref="C(of x, y)"/> ''' <see cref="C(of x, y).s"/> Public Shared Sub S(Of T)() C(Of X, Y).S(Of Integer)() Dim a As C(Of X, Y) = Nothing Dim b As C(Of X) = Nothing End Sub End Class ]]> </file> </compilation>, <error> <![CDATA[ BC42375: XML comment has a tag with a 'cref' attribute 'Y' that bound to a type parameter. Use the <typeparamref> tag instead. ''' <see cref="Y"/> ' failed in dev11 ~~~~~~~~ BC42375: XML comment has a tag with a 'cref' attribute 'X' that bound to a type parameter. Use the <typeparamref> tag instead. ''' <see cref="X"/> ~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'T' that could not be resolved. ''' <see cref="T"/> ~~~~~~~~ ]]> </error>) Dim tree = compilation.SyntaxTrees(0) Dim names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "C").ToArray() Assert.Equal(7, names.Length) Dim model = compilation.GetSemanticModel(tree) Dim expSymInfo1 = model.GetSymbolInfo(names(4)) Assert.NotNull(expSymInfo1.Symbol) TestSymbolAndTypeInfoForType(model, names(5), expSymInfo1.Symbol.OriginalDefinition) Dim expSymInfo3 = model.GetSymbolInfo(names(6)) Assert.NotNull(expSymInfo3.Symbol) Assert.NotSame(expSymInfo1.Symbol.OriginalDefinition, expSymInfo3.Symbol.OriginalDefinition) Dim actSymInfo1 = model.GetSymbolInfo(names(0)) Assert.Equal(CandidateReason.Ambiguous, actSymInfo1.CandidateReason) Assert.Equal(2, actSymInfo1.CandidateSymbols.Length) Dim list = actSymInfo1.CandidateSymbols.ToArray() Array.Sort(list, Function(x As ISymbol, y As ISymbol) compilation.CompareSourceLocations(x.Locations(0), y.Locations(0))) Assert.Same(expSymInfo3.Symbol.OriginalDefinition, list(0).OriginalDefinition) Assert.Same(expSymInfo1.Symbol.OriginalDefinition, list(1).OriginalDefinition) TestSymbolAndTypeInfoForType(model, names(1), expSymInfo3.Symbol.OriginalDefinition) TestSymbolAndTypeInfoForType(model, names(2), expSymInfo1.Symbol.OriginalDefinition) TestSymbolAndTypeInfoForType(model, names(3), expSymInfo1.Symbol.OriginalDefinition) names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "X").ToArray() Assert.Equal(4, names.Length) Dim typeParamSymInfo = model.GetSymbolInfo(names(0)) Assert.Null(typeParamSymInfo.Symbol) Assert.Equal(SymbolKind.TypeParameter, typeParamSymInfo.CandidateSymbols.Single().Kind) Assert.Equal(CandidateReason.NotReferencable, typeParamSymInfo.CandidateReason) End Sub <Fact()> Public Sub GetSymbolInfo_NameSyntax() Dim compilation = CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Option Explicit On Imports System Class OuterClass Public Class C(Of X) End Class Public Class C(Of X, Y) Public F As Integer End Class End Class Public Class OtherClass ''' <see cref="OuterClass.C"/> ''' <see cref="OuterClass.C(of x)"/> ''' <see cref="OuterClass.C(of x, y)"/> ''' <see cref="OuterClass.C(of x, y).f"/> ''' <see cref="OuterClass.C(of x, y).X"/> Public Shared Sub S(Of T)() End Sub End Class ]]> </file> </compilation>, <error> <![CDATA[ BC42309: XML comment has a tag with a 'cref' attribute 'OuterClass.C(of x, y).X' that could not be resolved. ''' <see cref="OuterClass.C(of x, y).X"/> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]> </error>) Dim tree = compilation.SyntaxTrees(0) Dim names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "C").ToArray() Assert.Equal(5, names.Length) Dim model = compilation.GetSemanticModel(tree) CheckSymbolInfoAndTypeInfo(model, names(0), "OuterClass.C(Of X)", "OuterClass.C(Of X, Y)") CheckSymbolInfoAndTypeInfo(model, names(1), "OuterClass.C(Of x)") CheckSymbolInfoAndTypeInfo(model, names(2), "OuterClass.C(Of x, y)") CheckSymbolInfoAndTypeInfo(model, names(3), "OuterClass.C(Of x, y)") CheckSymbolInfoAndTypeInfo(model, names(4), "OuterClass.C(Of x, y)") End Sub <Fact()> Public Sub GetSymbolInfo_LegacyMode_1() Dim compilation = CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Option Explicit On Imports System Public Class OtherClass ''' <see cref="New"/> ''' <see cref="OtherClass.New"/> ''' <see cref="Operator"/> ''' <see cref="Operator+"/> ''' <see cref="OtherClass.Operator"/> ''' <see cref="OtherClass.Operator+"/> Public Shared Sub S(Of T)() End Sub End Class ]]> </file> </compilation>, <error> <![CDATA[ BC42309: XML comment has a tag with a 'cref' attribute 'New' that could not be resolved. ''' <see cref="New"/> ~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'OtherClass.New' that could not be resolved. ''' <see cref="OtherClass.New"/> ~~~~~~~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'Operator' that could not be resolved. ''' <see cref="Operator"/> ~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'Operator+' that could not be resolved. ''' <see cref="Operator+"/> ~~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'OtherClass.Operator' that could not be resolved. ''' <see cref="OtherClass.Operator"/> ~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'OtherClass.Operator+' that could not be resolved. ''' <see cref="OtherClass.Operator+"/> ~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]> </error>) Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "New").ToArray() Assert.Equal(2, names.Length) CheckSymbolInfoAndTypeInfo(model, names(0)) CheckSymbolInfoAndTypeInfo(model, names(1)) names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "OtherClass").ToArray() Assert.Equal(3, names.Length) CheckSymbolInfoAndTypeInfo(model, names(0), "OtherClass") CheckSymbolInfoAndTypeInfo(model, names(1), "OtherClass") CheckSymbolInfoAndTypeInfo(model, names(2), "OtherClass") Dim crefOperator = FindNodesOfTypeFromText(Of CrefOperatorReferenceSyntax)(tree, "Operator").ToArray() Assert.Equal(4, crefOperator.Length) CheckSymbolInfoAndTypeInfo(model, crefOperator(0)) CheckSymbolInfoAndTypeInfo(model, crefOperator(1)) CheckSymbolInfoAndTypeInfo(model, crefOperator(2)) CheckSymbolInfoAndTypeInfo(model, crefOperator(3)) End Sub <Fact()> Public Sub GetSymbolInfo_LegacyMode_2() Dim compilation = CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Option Explicit On Imports System Public Class OtherClass ''' <see cref="New Public Shared Sub S0(Of T)() End Sub ''' <see cref="OtherClass.New Public Shared Sub S1(Of T)() End Sub ''' <see cref="Operator Public Shared Sub S2(Of T)() End Sub ''' <see cref="Operator+ Public Shared Sub S3(Of T)() End Sub ''' <see cref="OtherClass.Operator Public Shared Sub S4(Of T)() End Sub ''' <see cref="OtherClass.Operator+ Public Shared Sub S5(Of T)() End Sub End Class ]]> </file> </compilation>, <error> <![CDATA[ BC42304: XML documentation parse error: Element is missing an end tag. XML comment will be ignored. ''' <see cref="New ~~~~~~~~~~~~~~~ BC42304: XML documentation parse error: '>' expected. XML comment will be ignored. Public Shared Sub S0(Of T)() ~ BC42304: XML documentation parse error: '>' expected. XML comment will be ignored. Public Shared Sub S0(Of T)() ~ BC42304: XML documentation parse error: Expected beginning '<' for an XML tag. XML comment will be ignored. Public Shared Sub S0(Of T)() ~ BC42304: XML documentation parse error: Element is missing an end tag. XML comment will be ignored. ''' <see cref="OtherClass.New ~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42304: XML documentation parse error: '>' expected. XML comment will be ignored. Public Shared Sub S1(Of T)() ~ BC42304: XML documentation parse error: '>' expected. XML comment will be ignored. Public Shared Sub S1(Of T)() ~ BC42304: XML documentation parse error: Expected beginning '<' for an XML tag. XML comment will be ignored. Public Shared Sub S1(Of T)() ~ BC42304: XML documentation parse error: Element is missing an end tag. XML comment will be ignored. ''' <see cref="Operator ~~~~~~~~~~~~~~~~~~~~ BC42304: XML documentation parse error: '>' expected. XML comment will be ignored. Public Shared Sub S2(Of T)() ~ BC42304: XML documentation parse error: '>' expected. XML comment will be ignored. Public Shared Sub S2(Of T)() ~ BC42304: XML documentation parse error: Expected beginning '<' for an XML tag. XML comment will be ignored. Public Shared Sub S2(Of T)() ~ BC42304: XML documentation parse error: Element is missing an end tag. XML comment will be ignored. ''' <see cref="Operator+ ~~~~~~~~~~~~~~~~~~~~~ BC42304: XML documentation parse error: '>' expected. XML comment will be ignored. Public Shared Sub S3(Of T)() ~ BC42304: XML documentation parse error: '>' expected. XML comment will be ignored. Public Shared Sub S3(Of T)() ~ BC42304: XML documentation parse error: Expected beginning '<' for an XML tag. XML comment will be ignored. Public Shared Sub S3(Of T)() ~ BC42304: XML documentation parse error: Element is missing an end tag. XML comment will be ignored. ''' <see cref="OtherClass.Operator ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42304: XML documentation parse error: '>' expected. XML comment will be ignored. Public Shared Sub S4(Of T)() ~ BC42304: XML documentation parse error: '>' expected. XML comment will be ignored. Public Shared Sub S4(Of T)() ~ BC42304: XML documentation parse error: Expected beginning '<' for an XML tag. XML comment will be ignored. Public Shared Sub S4(Of T)() ~ BC42304: XML documentation parse error: Element is missing an end tag. XML comment will be ignored. ''' <see cref="OtherClass.Operator+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42304: XML documentation parse error: '>' expected. XML comment will be ignored. Public Shared Sub S5(Of T)() ~ BC42304: XML documentation parse error: '>' expected. XML comment will be ignored. Public Shared Sub S5(Of T)() ~ BC42304: XML documentation parse error: Expected beginning '<' for an XML tag. XML comment will be ignored. Public Shared Sub S5(Of T)() ~ ]]> </error>) Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "New").ToArray() Assert.Equal(2, names.Length) CheckSymbolInfoAndTypeInfo(model, names(0)) CheckSymbolInfoAndTypeInfo(model, names(1)) names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "OtherClass").ToArray() Assert.Equal(3, names.Length) CheckSymbolInfoAndTypeInfo(model, names(0), "OtherClass") CheckSymbolInfoAndTypeInfo(model, names(1), "OtherClass") CheckSymbolInfoAndTypeInfo(model, names(2), "OtherClass") Dim crefOperator = FindNodesOfTypeFromText(Of CrefOperatorReferenceSyntax)(tree, "Operator").ToArray() Assert.Equal(4, crefOperator.Length) CheckSymbolInfoAndTypeInfo(model, crefOperator(0)) CheckSymbolInfoAndTypeInfo(model, crefOperator(1)) CheckSymbolInfoAndTypeInfo(model, crefOperator(2)) CheckSymbolInfoAndTypeInfo(model, crefOperator(3)) End Sub <Fact()> Public Sub GetSymbolInfo_NameSyntax_Method_1() Dim compilation = CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Public Class C(Of X) Public Shared Sub Sub1(a As Integer) End Sub Public Shared Sub Sub1(a As Integer, b As Integer) End Sub End Class ''' <see cref="C.Sub1"/> ''' <see cref="C.Sub1(Of A)"/> ''' <see cref="C.Sub1(Of A, B)"/> Public Class OtherClass End Class ]]> </file> </compilation>, <errors> <![CDATA[ BC42309: XML comment has a tag with a 'cref' attribute 'C.Sub1(Of A)' that could not be resolved. ''' <see cref="C.Sub1(Of A)"/> ~~~~~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'C.Sub1(Of A, B)' that could not be resolved. ''' <see cref="C.Sub1(Of A, B)"/> ~~~~~~~~~~~~~~~~~~~~~~ ]]> </errors>) Dim tree = compilation.SyntaxTrees(0) Dim names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "C").ToArray() Assert.Equal(3, names.Length) Dim model = compilation.GetSemanticModel(tree) CheckSymbolInfoOnly(model, DirectCast(names(0).Parent, ExpressionSyntax), "Sub C(Of X).Sub1(a As System.Int32)", "Sub C(Of X).Sub1(a As System.Int32, b As System.Int32)") CheckSymbolInfoOnly(model, DirectCast(names(1).Parent, ExpressionSyntax)) CheckSymbolInfoOnly(model, DirectCast(names(2).Parent, ExpressionSyntax)) End Sub <Fact()> Public Sub GetSymbolInfo_NameSyntax_Method_2() Dim compilation = CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Public Class C(Of X) Public Shared Sub Sub1(a As Integer) End Sub Public Shared Sub Sub1(Of Y)(a As Integer) End Sub End Class ''' <see cref="C.Sub1"/> ''' <see cref="C.Sub1(Of A)"/> ''' <see cref="C.Sub1(Of A, B)"/> Public Class OtherClass End Class ]]> </file> </compilation>, <errors> <![CDATA[ BC42309: XML comment has a tag with a 'cref' attribute 'C.Sub1(Of A, B)' that could not be resolved. ''' <see cref="C.Sub1(Of A, B)"/> ~~~~~~~~~~~~~~~~~~~~~~ ]]> </errors>) Dim tree = compilation.SyntaxTrees(0) Dim names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "C").ToArray() Assert.Equal(3, names.Length) Dim model = compilation.GetSemanticModel(tree) CheckSymbolInfoOnly(model, DirectCast(names(0).Parent, ExpressionSyntax), "Sub C(Of X).Sub1(a As System.Int32)") CheckSymbolInfoOnly(model, DirectCast(names(1).Parent, ExpressionSyntax), "Sub C(Of X).Sub1(Of A)(a As System.Int32)") CheckSymbolInfoOnly(model, DirectCast(names(2).Parent, ExpressionSyntax)) End Sub <Fact()> Public Sub GetSymbolInfo_NameSyntax_Method_3() Dim compilation = CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Public Class C(Of X) Public Shared Sub Sub1(Of Y, Z)(a As Integer) End Sub Public Shared Sub Sub1(Of Y)(a As Integer) End Sub End Class ''' <see cref="C.Sub1"/> ''' <see cref="C.Sub1(Of A)"/> ''' <see cref="C.Sub1(Of A, B)"/> Public Class OtherClass End Class ]]> </file> </compilation>, <errors></errors>) Dim tree = compilation.SyntaxTrees(0) Dim names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "C").ToArray() Assert.Equal(3, names.Length) Dim model = compilation.GetSemanticModel(tree) CheckSymbolInfoOnly(model, DirectCast(names(0).Parent, ExpressionSyntax), "Sub C(Of X).Sub1(Of Y)(a As System.Int32)", "Sub C(Of X).Sub1(Of Y, Z)(a As System.Int32)") CheckSymbolInfoOnly(model, DirectCast(names(1).Parent, ExpressionSyntax), "Sub C(Of X).Sub1(Of A)(a As System.Int32)") CheckSymbolInfoOnly(model, DirectCast(names(2).Parent, ExpressionSyntax), "Sub C(Of X).Sub1(Of A, B)(a As System.Int32)") End Sub <Fact()> Public Sub GetSymbolInfo_NameSyntax_Event_Field_Property() Dim compilation = CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Public Class C(Of X) Public ReadOnly Property Prop1(a As Integer) As String Get Return Nothing End Get End Property Public Property Prop1 As String Public Event Ev1 As Action Public Dim Fld As String End Class ''' <see cref="C.Fld"/> ''' <see cref="C.Fld(Of Integer)"/> ''' <see cref="C.Ev1"/> ''' <see cref="C.Ev1(Of X)"/> ''' <see cref="C.Prop1"/> ''' <see cref="C.Prop1(Of A)"/> Public Class OtherClass End Class ]]> </file> </compilation>, <errors> <![CDATA[ BC42309: XML comment has a tag with a 'cref' attribute 'C.Fld(Of Integer)' that could not be resolved. ''' <see cref="C.Fld(Of Integer)"/> ~~~~~~~~~~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'C.Ev1(Of X)' that could not be resolved. ''' <see cref="C.Ev1(Of X)"/> ~~~~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'C.Prop1(Of A)' that could not be resolved. ''' <see cref="C.Prop1(Of A)"/> ~~~~~~~~~~~~~~~~~~~~ ]]> </errors>) Dim tree As SyntaxTree = compilation.SyntaxTrees(0) Dim names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "C") Assert.Equal(6, names.Length) Dim model = compilation.GetSemanticModel(tree) CheckSymbolInfoOnly(model, DirectCast(names(0).Parent, ExpressionSyntax), "C(Of X).Fld As System.String") CheckSymbolInfoOnly(model, DirectCast(names(1).Parent, ExpressionSyntax)) CheckSymbolInfoOnly(model, DirectCast(names(2).Parent, ExpressionSyntax), "Event C(Of X).Ev1 As System.Action") CheckSymbolInfoOnly(model, DirectCast(names(3).Parent, ExpressionSyntax)) CheckSymbolInfoOnly(model, DirectCast(names(4).Parent, ExpressionSyntax), "Property C(Of X).Prop1 As System.String", "ReadOnly Property C(Of X).Prop1(a As System.Int32) As System.String") CheckSymbolInfoOnly(model, DirectCast(names(5).Parent, ExpressionSyntax)) End Sub <Fact()> Public Sub SemanticInfo_InsideCref() Dim compilation = CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Public Class Clazz(Of T) ''' <see cref="X(Of T, T(Of T, X, InnerClazz(Of X)))"/> Public Class InnerClazz(Of X) End Class End Class ]]> </file> </compilation>, <errors> <![CDATA[ BC42309: XML comment has a tag with a 'cref' attribute 'X(Of T, T(Of T, X, InnerClazz(Of X)))' that could not be resolved. ''' <see cref="X(Of T, T(Of T, X, InnerClazz(Of X)))"/> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]> </errors>) Dim tree As SyntaxTree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "InnerClazz") Assert.Equal(1, names.Length) CheckSymbolInfoAndTypeInfo(model, DirectCast(names(0), ExpressionSyntax), "Clazz(Of T).InnerClazz(Of X)") names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "T") Assert.Equal(3, names.Length) CheckSymbolInfoAndTypeInfo(model, DirectCast(names(0), ExpressionSyntax), "T") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(1), ExpressionSyntax)) CheckSymbolInfoAndTypeInfo(model, DirectCast(names(2), ExpressionSyntax), "T") names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "X") Assert.Equal(3, names.Length) CheckSymbolInfoAndTypeInfo(model, DirectCast(names(0), ExpressionSyntax)) CheckSymbolInfoAndTypeInfo(model, DirectCast(names(1), ExpressionSyntax), "X") ' Did not bind in dev11. CheckSymbolInfoAndTypeInfo(model, DirectCast(names(2), ExpressionSyntax), "X") ' Did not bind in dev11. End Sub <Fact()> Public Sub SemanticInfo_InsideParam() Dim compilation = CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System ''' <summary><param name="a" nested="true">@OuterClass(Of X)</param></summary> ''' <param name="a">@OuterClass(Of X)</param> Public MustInherit Class OuterClass(Of X) ''' <summary><param name="a" nested="true">@F</param></summary> ''' <param name="a">@F</param> Public F As String ''' <summary><param name="a" nested="true">@S(Of T)</param></summary> ''' <param name="a">@S(Of T)</param> Public Shared Sub S(Of T)(a As Integer) End Sub ''' <summary><param name="a" nested="true">@FUN(Of T)</param></summary> ''' <param name="a">@FUN(Of T)</param> Public MustOverride Function FUN(Of T)(a As T) As String ''' <summary><param name="a" nested="true">@Operator +</param></summary> ''' <param name="a">@Operator +</param> Public Shared Operator +(a As OuterClass(Of X), b As Integer) As Integer Return Nothing End Operator ''' <summary><param name="a" nested="true">@Operator CType</param></summary> ''' <param name="a">@Operator CType</param> Public Shared Narrowing Operator CType(a As Integer) As OuterClass(Of X) Return Nothing End Operator ''' <summary><param name="obj" nested="true">@E</param></summary> ''' <param name="obj">@E</param> Public Event E As Action(Of Integer) ''' <summary><param name="a" nested="true">@E2</param></summary> ''' <param name="a">@E2</param> Public Event E2(a As Integer) ''' <summary><param name="a" nested="true">@P</param></summary> ''' <param name="a">@P</param> Property P As String ''' <summary><param name="a" nested="true">@P(a As String)</param></summary> ''' <param name="a">@P(a As String)</param> ReadOnly Property P(a As String) As String Get Return Nothing End Get End Property ''' <summary><param name="a" nested="true">@D(a As Integer)</param></summary> ''' <param name="a">@D(a As Integer)</param> Public Delegate Function D(a As Integer) As String ''' <summary><param name="a" nested="true">@SD(a As Integer)</param></summary> ''' <param name="a">@SD(a As Integer)</param> Public Delegate Sub SD(a As Integer) ''' <summary><param name="a" nested="true">@ENM</param></summary> ''' <param name="a">@ENM</param> Public Enum ENM ''' <summary><param name="a" nested="true">@DefaultValue</param></summary> ''' <param name="a">@DefaultValue</param> DefaultValue End Enum ''' <summary><param name="a" nested="true">@INT(Of INTT)</param></summary> ''' <param name="a">@INT(Of INTT)</param> Public Interface INT(Of INTT) ''' <summary><param name="a" nested="true">@INTS(a As Integer)</param></summary> ''' <param name="a">@INTS(a As Integer)</param> Sub INTS(a As Integer) End Interface End Class ''' <param name="a" nested="true">@M0</param> ''' <summary><param name="a">@M0</param></summary> Public Module M0 Public a As Integer End Module ]]> </file> </compilation>, <errors> <![CDATA[ BC42306: XML comment tag 'param' is not permitted on a 'class' language element. ''' <summary><param name="a" nested="true">@OuterClass(Of X)</param></summary> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'param' is not permitted on a 'class' language element. ''' <param name="a">@OuterClass(Of X)</param> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'param' is not permitted on a 'variable' language element. ''' <summary><param name="a" nested="true">@F</param></summary> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'param' is not permitted on a 'variable' language element. ''' <param name="a">@F</param> ~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42307: XML comment parameter 'a' does not match a parameter on the corresponding 'property' statement. ''' <summary><param name="a" nested="true">@P</param></summary> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42307: XML comment parameter 'a' does not match a parameter on the corresponding 'property' statement. ''' <param name="a">@P</param> ~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'param' is not permitted on a 'enum' language element. ''' <summary><param name="a" nested="true">@ENM</param></summary> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'param' is not permitted on a 'enum' language element. ''' <param name="a">@ENM</param> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'param' is not permitted on a 'variable' language element. ''' <summary><param name="a" nested="true">@DefaultValue</param></summary> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'param' is not permitted on a 'variable' language element. ''' <param name="a">@DefaultValue</param> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'param' is not permitted on a 'interface' language element. ''' <summary><param name="a" nested="true">@INT(Of INTT)</param></summary> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'param' is not permitted on a 'interface' language element. ''' <param name="a">@INT(Of INTT)</param> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'param' is not permitted on a 'module' language element. ''' <param name="a" nested="true">@M0</param> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'param' is not permitted on a 'module' language element. ''' <summary><param name="a">@M0</param></summary> ~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]> </errors>) Dim tree As SyntaxTree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "obj") Assert.Equal(2, names.Length) CheckSymbolInfoOnly(model, DirectCast(names(0), ExpressionSyntax), "obj As System.Int32") CheckSymbolInfoOnly(model, DirectCast(names(1), ExpressionSyntax), "obj As System.Int32") names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "a") Assert.Equal(32, names.Length) CheckSymbolInfoOnly(model, DirectCast(names(0), ExpressionSyntax)) CheckSymbolInfoOnly(model, DirectCast(names(1), ExpressionSyntax)) CheckSymbolInfoOnly(model, DirectCast(names(2), ExpressionSyntax)) CheckSymbolInfoOnly(model, DirectCast(names(3), ExpressionSyntax)) CheckSymbolInfoOnly(model, DirectCast(names(4), ExpressionSyntax), "a As System.Int32") CheckSymbolInfoOnly(model, DirectCast(names(5), ExpressionSyntax), "a As System.Int32") CheckSymbolInfoOnly(model, DirectCast(names(6), ExpressionSyntax), "a As T") CheckSymbolInfoOnly(model, DirectCast(names(7), ExpressionSyntax), "a As T") CheckSymbolInfoOnly(model, DirectCast(names(8), ExpressionSyntax), "a As OuterClass(Of X)") CheckSymbolInfoOnly(model, DirectCast(names(9), ExpressionSyntax), "a As OuterClass(Of X)") CheckSymbolInfoOnly(model, DirectCast(names(10), ExpressionSyntax), "a As System.Int32") CheckSymbolInfoOnly(model, DirectCast(names(11), ExpressionSyntax), "a As System.Int32") CheckSymbolInfoOnly(model, DirectCast(names(12), ExpressionSyntax), "a As System.Int32") CheckSymbolInfoOnly(model, DirectCast(names(13), ExpressionSyntax), "a As System.Int32") CheckSymbolInfoOnly(model, DirectCast(names(14), ExpressionSyntax)) CheckSymbolInfoOnly(model, DirectCast(names(15), ExpressionSyntax)) CheckSymbolInfoOnly(model, DirectCast(names(16), ExpressionSyntax), "a As System.String") CheckSymbolInfoOnly(model, DirectCast(names(17), ExpressionSyntax), "a As System.String") CheckSymbolInfoOnly(model, DirectCast(names(18), ExpressionSyntax), "a As System.Int32") CheckSymbolInfoOnly(model, DirectCast(names(19), ExpressionSyntax), "a As System.Int32") CheckSymbolInfoOnly(model, DirectCast(names(20), ExpressionSyntax), "a As System.Int32") CheckSymbolInfoOnly(model, DirectCast(names(21), ExpressionSyntax), "a As System.Int32") CheckSymbolInfoOnly(model, DirectCast(names(22), ExpressionSyntax)) CheckSymbolInfoOnly(model, DirectCast(names(23), ExpressionSyntax)) CheckSymbolInfoOnly(model, DirectCast(names(24), ExpressionSyntax)) CheckSymbolInfoOnly(model, DirectCast(names(25), ExpressionSyntax)) CheckSymbolInfoOnly(model, DirectCast(names(26), ExpressionSyntax)) CheckSymbolInfoOnly(model, DirectCast(names(27), ExpressionSyntax)) CheckSymbolInfoOnly(model, DirectCast(names(28), ExpressionSyntax), "a As System.Int32") CheckSymbolInfoOnly(model, DirectCast(names(29), ExpressionSyntax), "a As System.Int32") CheckSymbolInfoOnly(model, DirectCast(names(30), ExpressionSyntax)) CheckSymbolInfoOnly(model, DirectCast(names(31), ExpressionSyntax)) End Sub <Fact()> Public Sub SemanticInfo_InsideParamRef() Dim compilation = CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System ''' <summary><paramref name="a" nested="true">@OuterClass(Of X)</paramref></summary> ''' <paramref name="a">@OuterClass(Of X)</paramref> Public MustInherit Class OuterClass(Of X) ''' <summary><paramref name="a" nested="true">@F</paramref></summary> ''' <paramref name="a">@F</paramref> Public F As String ''' <summary><paramref name="a" nested="true">@S(Of T)</paramref></summary> ''' <paramref name="a">@S(Of T)</paramref> Public Shared Sub S(Of T)(a As Integer) End Sub ''' <summary><paramref name="a" nested="true">@FUN(Of T)</paramref></summary> ''' <paramref name="a">@FUN(Of T)</paramref> Public MustOverride Function FUN(Of T)(a As T) As String ''' <summary><paramref name="a" nested="true">@Operator +</paramref></summary> ''' <paramref name="a">@Operator +</paramref> Public Shared Operator +(a As OuterClass(Of X), b As Integer) As Integer Return Nothing End Operator ''' <summary><paramref name="a" nested="true">@Operator CType</paramref></summary> ''' <paramref name="a">@Operator CType</paramref> Public Shared Narrowing Operator CType(a As Integer) As OuterClass(Of X) Return Nothing End Operator ''' <summary><paramref name="obj" nested="true">@E</paramref></summary> ''' <paramref name="obj">@E</paramref> Public Event E As Action(Of Integer) ''' <summary><paramref name="a" nested="true">@E2</paramref></summary> ''' <paramref name="a">@E2</paramref> Public Event E2(a As Integer) ''' <summary><paramref name="a" nested="true">@P</paramref></summary> ''' <paramref name="a">@P</paramref> Property P As String ''' <summary><paramref name="a" nested="true">@P(a As String)</paramref></summary> ''' <paramref name="a">@P(a As String)</paramref> ReadOnly Property P(a As String) As String Get Return Nothing End Get End Property ''' <summary><paramref name="a" nested="true">@D(a As Integer)</paramref></summary> ''' <paramref name="a">@D(a As Integer)</paramref> Public Delegate Function D(a As Integer) As String ''' <summary><paramref name="a" nested="true">@SD(a As Integer)</paramref></summary> ''' <paramref name="a">@SD(a As Integer)</paramref> Public Delegate Sub SD(a As Integer) ''' <summary><paramref name="a" nested="true">@ENM</paramref></summary> ''' <paramref name="a">@ENM</paramref> Public Enum ENM ''' <summary><paramref name="a" nested="true">@DefaultValue</paramref></summary> ''' <paramref name="a">@DefaultValue</paramref> DefaultValue End Enum ''' <summary><paramref name="a" nested="true">@INT(Of INTT)</paramref></summary> ''' <paramref name="a">@INT(Of INTT)</paramref> Public Interface INT(Of INTT) ''' <summary><paramref name="a" nested="true">@INTS(a As Integer)</paramref></summary> ''' <paramref name="a">@INTS(a As Integer)</paramref> Sub INTS(a As Integer) End Interface End Class ''' <paramref name="a" nested="true">@M0</paramref> ''' <summary><paramref name="a">@M0</paramref></summary> Public Module M0 Public a As Integer End Module ]]> </file> </compilation>, <errors> <![CDATA[ BC42306: XML comment tag 'paramref' is not permitted on a 'class' language element. ''' <summary><paramref name="a" nested="true">@OuterClass(Of X)</paramref></summary> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'paramref' is not permitted on a 'class' language element. ''' <paramref name="a">@OuterClass(Of X)</paramref> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'paramref' is not permitted on a 'variable' language element. ''' <summary><paramref name="a" nested="true">@F</paramref></summary> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'paramref' is not permitted on a 'variable' language element. ''' <paramref name="a">@F</paramref> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42307: XML comment parameter 'a' does not match a parameter on the corresponding 'property' statement. ''' <summary><paramref name="a" nested="true">@P</paramref></summary> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42307: XML comment parameter 'a' does not match a parameter on the corresponding 'property' statement. ''' <paramref name="a">@P</paramref> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'paramref' is not permitted on a 'enum' language element. ''' <summary><paramref name="a" nested="true">@ENM</paramref></summary> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'paramref' is not permitted on a 'enum' language element. ''' <paramref name="a">@ENM</paramref> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'paramref' is not permitted on a 'variable' language element. ''' <summary><paramref name="a" nested="true">@DefaultValue</paramref></summary> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'paramref' is not permitted on a 'variable' language element. ''' <paramref name="a">@DefaultValue</paramref> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'paramref' is not permitted on a 'interface' language element. ''' <summary><paramref name="a" nested="true">@INT(Of INTT)</paramref></summary> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'paramref' is not permitted on a 'interface' language element. ''' <paramref name="a">@INT(Of INTT)</paramref> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'paramref' is not permitted on a 'module' language element. ''' <paramref name="a" nested="true">@M0</paramref> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'paramref' is not permitted on a 'module' language element. ''' <summary><paramref name="a">@M0</paramref></summary> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]> </errors>) Dim tree As SyntaxTree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "obj") Assert.Equal(2, names.Length) CheckSymbolInfoOnly(model, DirectCast(names(0), ExpressionSyntax), "obj As System.Int32") CheckSymbolInfoOnly(model, DirectCast(names(0), ExpressionSyntax), "obj As System.Int32") names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "a") Assert.Equal(32, names.Length) CheckSymbolInfoOnly(model, DirectCast(names(0), ExpressionSyntax)) CheckSymbolInfoOnly(model, DirectCast(names(1), ExpressionSyntax)) CheckSymbolInfoOnly(model, DirectCast(names(2), ExpressionSyntax)) CheckSymbolInfoOnly(model, DirectCast(names(3), ExpressionSyntax)) CheckSymbolInfoOnly(model, DirectCast(names(4), ExpressionSyntax), "a As System.Int32") CheckSymbolInfoOnly(model, DirectCast(names(5), ExpressionSyntax), "a As System.Int32") CheckSymbolInfoOnly(model, DirectCast(names(6), ExpressionSyntax), "a As T") CheckSymbolInfoOnly(model, DirectCast(names(7), ExpressionSyntax), "a As T") CheckSymbolInfoOnly(model, DirectCast(names(8), ExpressionSyntax), "a As OuterClass(Of X)") CheckSymbolInfoOnly(model, DirectCast(names(9), ExpressionSyntax), "a As OuterClass(Of X)") CheckSymbolInfoOnly(model, DirectCast(names(10), ExpressionSyntax), "a As System.Int32") CheckSymbolInfoOnly(model, DirectCast(names(11), ExpressionSyntax), "a As System.Int32") CheckSymbolInfoOnly(model, DirectCast(names(12), ExpressionSyntax), "a As System.Int32") CheckSymbolInfoOnly(model, DirectCast(names(13), ExpressionSyntax), "a As System.Int32") CheckSymbolInfoOnly(model, DirectCast(names(14), ExpressionSyntax)) CheckSymbolInfoOnly(model, DirectCast(names(15), ExpressionSyntax)) CheckSymbolInfoOnly(model, DirectCast(names(16), ExpressionSyntax), "a As System.String") CheckSymbolInfoOnly(model, DirectCast(names(17), ExpressionSyntax), "a As System.String") CheckSymbolInfoOnly(model, DirectCast(names(18), ExpressionSyntax), "a As System.Int32") CheckSymbolInfoOnly(model, DirectCast(names(19), ExpressionSyntax), "a As System.Int32") CheckSymbolInfoOnly(model, DirectCast(names(20), ExpressionSyntax), "a As System.Int32") CheckSymbolInfoOnly(model, DirectCast(names(21), ExpressionSyntax), "a As System.Int32") CheckSymbolInfoOnly(model, DirectCast(names(22), ExpressionSyntax)) CheckSymbolInfoOnly(model, DirectCast(names(23), ExpressionSyntax)) CheckSymbolInfoOnly(model, DirectCast(names(24), ExpressionSyntax)) CheckSymbolInfoOnly(model, DirectCast(names(25), ExpressionSyntax)) CheckSymbolInfoOnly(model, DirectCast(names(26), ExpressionSyntax)) CheckSymbolInfoOnly(model, DirectCast(names(27), ExpressionSyntax)) CheckSymbolInfoOnly(model, DirectCast(names(28), ExpressionSyntax), "a As System.Int32") CheckSymbolInfoOnly(model, DirectCast(names(29), ExpressionSyntax), "a As System.Int32") CheckSymbolInfoOnly(model, DirectCast(names(30), ExpressionSyntax)) CheckSymbolInfoOnly(model, DirectCast(names(31), ExpressionSyntax)) End Sub <Fact()> Public Sub SemanticInfo_InsideTypeParam() Dim compilation = CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System ''' <summary><typeparam name="x" nested="true">@OuterClass(Of X)</typeparam></summary> ''' <typeparam name="x">@OuterClass(Of X)</typeparam> Public MustInherit Class OuterClass(Of X) ''' <summary><typeparam name="x" nested="true">@F</typeparam></summary> ''' <typeparam name="x">@F</typeparam> Public F As String ''' <summary><typeparam name="t" nested="true">@S(Of T)</typeparam></summary> ''' <typeparam name="t">@S(Of T)</typeparam> Public Shared Sub S(Of T)(a As Integer) End Sub ''' <summary><typeparam name="tt" nested="true">@FUN(Of T)</typeparam></summary> ''' <typeparam name="tt">@FUN(Of T)</typeparam> Public MustOverride Function FUN(Of TT)(a As Integer) As String ''' <summary><typeparam name="x" nested="true">@Operator +</typeparam></summary> ''' <typeparam name="x">@Operator +</typeparam> Public Shared Operator +(a As OuterClass(Of X), b As Integer) As Integer Return Nothing End Operator ''' <summary><typeparam name="x" nested="true">@Operator CType</typeparam></summary> ''' <typeparam name="x">@Operator CType</typeparam> Public Shared Narrowing Operator CType(a As Integer) As OuterClass(Of X) Return Nothing End Operator ''' <summary><typeparam name="t" nested="true">@E</typeparam></summary> ''' <typeparam name="t">@E</typeparam> Public Event E As Action(Of Integer) ''' <summary><typeparam name="x" nested="true">@E2</typeparam></summary> ''' <typeparam name="x">@E2</typeparam> Public Event E2(a As Integer) ''' <summary><typeparam name="x" nested="true">@P</typeparam></summary> ''' <typeparam name="x">@P</typeparam> Property P As String ''' <summary><typeparam name="x" nested="true">@P(a As String)</typeparam></summary> ''' <typeparam name="x">@P(a As String)</typeparam> ReadOnly Property P(a As String) As String Get Return Nothing End Get End Property ''' <summary><typeparam name="tt" nested="true">@D(a As Integer)</typeparam></summary> ''' <typeparam name="tt">@D(a As Integer)</typeparam> Public Delegate Function D(Of TT)(a As Integer) As String ''' <summary><typeparam name="t" nested="true">@SD(a As Integer)</typeparam></summary> ''' <typeparam name="t">@SD(a As Integer)</typeparam> Public Delegate Sub SD(Of T)(a As Integer) ''' <summary><typeparam name="x" nested="true">@ENM</typeparam></summary> ''' <typeparam name="x">@ENM</typeparam> Public Enum ENM ''' <summary><typeparam name="x" nested="true">@DefaultValue</typeparam></summary> ''' <typeparam name="x">@DefaultValue</typeparam> DefaultValue End Enum ''' <summary><typeparam name="tt" nested="true">@INT(Of TT)</typeparam></summary> ''' <typeparam name="tt">@INT(Of TT)</typeparam> Public Interface INT(Of TT) ''' <summary><typeparam name="t" nested="true">@INTS(a As Integer)</typeparam></summary> ''' <typeparam name="t">@INTS(a As Integer)</typeparam> Sub INTS(Of T)(a As Integer) End Interface End Class ''' <typeparam name="x" nested="true">@M0</typeparam> ''' <summary><typeparam name="x">@M0</typeparam></summary> Public Module M0 Public a As Integer End Module ]]> </file> </compilation>, <errors> <![CDATA[ BC42306: XML comment tag 'typeparam' is not permitted on a 'variable' language element. ''' <summary><typeparam name="x" nested="true">@F</typeparam></summary> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'typeparam' is not permitted on a 'variable' language element. ''' <typeparam name="x">@F</typeparam> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'typeparam' is not permitted on a 'operator' language element. ''' <summary><typeparam name="x" nested="true">@Operator +</typeparam></summary> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'typeparam' is not permitted on a 'operator' language element. ''' <typeparam name="x">@Operator +</typeparam> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42317: XML comment type parameter 'x' does not match a type parameter on the corresponding 'operator' statement. ''' <summary><typeparam name="x" nested="true">@Operator CType</typeparam></summary> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42317: XML comment type parameter 'x' does not match a type parameter on the corresponding 'operator' statement. ''' <typeparam name="x">@Operator CType</typeparam> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'typeparam' is not permitted on a 'event' language element. ''' <summary><typeparam name="t" nested="true">@E</typeparam></summary> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'typeparam' is not permitted on a 'event' language element. ''' <typeparam name="t">@E</typeparam> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'typeparam' is not permitted on a 'event' language element. ''' <summary><typeparam name="x" nested="true">@E2</typeparam></summary> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'typeparam' is not permitted on a 'event' language element. ''' <typeparam name="x">@E2</typeparam> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'typeparam' is not permitted on a 'property' language element. ''' <summary><typeparam name="x" nested="true">@P</typeparam></summary> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'typeparam' is not permitted on a 'property' language element. ''' <typeparam name="x">@P</typeparam> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'typeparam' is not permitted on a 'property' language element. ''' <summary><typeparam name="x" nested="true">@P(a As String)</typeparam></summary> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'typeparam' is not permitted on a 'property' language element. ''' <typeparam name="x">@P(a As String)</typeparam> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'typeparam' is not permitted on a 'enum' language element. ''' <summary><typeparam name="x" nested="true">@ENM</typeparam></summary> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'typeparam' is not permitted on a 'enum' language element. ''' <typeparam name="x">@ENM</typeparam> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'typeparam' is not permitted on a 'variable' language element. ''' <summary><typeparam name="x" nested="true">@DefaultValue</typeparam></summary> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'typeparam' is not permitted on a 'variable' language element. ''' <typeparam name="x">@DefaultValue</typeparam> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'typeparam' is not permitted on a 'module' language element. ''' <typeparam name="x" nested="true">@M0</typeparam> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'typeparam' is not permitted on a 'module' language element. ''' <summary><typeparam name="x">@M0</typeparam></summary> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]> </errors>) Dim tree As SyntaxTree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "t") Assert.Equal(8, names.Length) CheckSymbolInfoAndTypeInfo(model, DirectCast(names(0), ExpressionSyntax), "T") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(1), ExpressionSyntax), "T") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(2), ExpressionSyntax)) CheckSymbolInfoAndTypeInfo(model, DirectCast(names(3), ExpressionSyntax)) CheckSymbolInfoAndTypeInfo(model, DirectCast(names(4), ExpressionSyntax), "T") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(5), ExpressionSyntax), "T") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(6), ExpressionSyntax), "T") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(7), ExpressionSyntax), "T") names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "tt") Assert.Equal(6, names.Length) CheckSymbolInfoAndTypeInfo(model, DirectCast(names(0), ExpressionSyntax), "TT") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(1), ExpressionSyntax), "TT") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(2), ExpressionSyntax), "TT") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(3), ExpressionSyntax), "TT") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(4), ExpressionSyntax), "TT") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(5), ExpressionSyntax), "TT") names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "x") Assert.Equal(20, names.Length) CheckSymbolInfoAndTypeInfo(model, DirectCast(names(0), ExpressionSyntax), "X") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(1), ExpressionSyntax), "X") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(2), ExpressionSyntax)) CheckSymbolInfoAndTypeInfo(model, DirectCast(names(3), ExpressionSyntax)) CheckSymbolInfoAndTypeInfo(model, DirectCast(names(4), ExpressionSyntax)) CheckSymbolInfoAndTypeInfo(model, DirectCast(names(5), ExpressionSyntax)) CheckSymbolInfoAndTypeInfo(model, DirectCast(names(6), ExpressionSyntax)) CheckSymbolInfoAndTypeInfo(model, DirectCast(names(7), ExpressionSyntax)) CheckSymbolInfoAndTypeInfo(model, DirectCast(names(8), ExpressionSyntax)) CheckSymbolInfoAndTypeInfo(model, DirectCast(names(9), ExpressionSyntax)) CheckSymbolInfoAndTypeInfo(model, DirectCast(names(10), ExpressionSyntax)) CheckSymbolInfoAndTypeInfo(model, DirectCast(names(11), ExpressionSyntax)) CheckSymbolInfoAndTypeInfo(model, DirectCast(names(12), ExpressionSyntax)) CheckSymbolInfoAndTypeInfo(model, DirectCast(names(13), ExpressionSyntax)) CheckSymbolInfoAndTypeInfo(model, DirectCast(names(14), ExpressionSyntax)) CheckSymbolInfoAndTypeInfo(model, DirectCast(names(15), ExpressionSyntax)) CheckSymbolInfoAndTypeInfo(model, DirectCast(names(16), ExpressionSyntax)) CheckSymbolInfoAndTypeInfo(model, DirectCast(names(17), ExpressionSyntax)) CheckSymbolInfoAndTypeInfo(model, DirectCast(names(18), ExpressionSyntax)) CheckSymbolInfoAndTypeInfo(model, DirectCast(names(19), ExpressionSyntax)) End Sub <Fact()> Public Sub SemanticInfo_InsideTypeParamRef() Dim compilation = CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System ''' <summary><typeparamref name="x" nested="true">@OuterClass(Of X)</typeparamref></summary> ''' <typeparamref name="x">@OuterClass(Of X)</typeparamref> Public MustInherit Class OuterClass(Of X) ''' <summary><typeparamref name="x" nested="true">@F</typeparamref></summary> ''' <typeparamref name="x">@F</typeparamref> Public F As String ''' <summary><typeparamref name="t" nested="true">@S(Of T)</typeparamref></summary> ''' <typeparamref name="t">@S(Of T)</typeparamref> Public Shared Sub S(Of T)(a As Integer) End Sub ''' <summary><typeparamref name="tt" nested="true">@FUN(Of T)</typeparamref></summary> ''' <typeparamref name="tt">@FUN(Of T)</typeparamref> Public MustOverride Function FUN(Of TT)(a As Integer) As String ''' <summary><typeparamref name="x" nested="true">@Operator +</typeparamref></summary> ''' <typeparamref name="x">@Operator +</typeparamref> Public Shared Operator +(a As OuterClass(Of X), b As Integer) As Integer Return Nothing End Operator ''' <summary><typeparamref name="x" nested="true">@Operator CType</typeparamref></summary> ''' <typeparamref name="x">@Operator CType</typeparamref> Public Shared Narrowing Operator CType(a As Integer) As OuterClass(Of X) Return Nothing End Operator ''' <summary><typeparamref name="t" nested="true">@E</typeparamref></summary> ''' <typeparamref name="t">@E</typeparamref> Public Event E As Action(Of Integer) ''' <summary><typeparamref name="x" nested="true">@E2</typeparamref></summary> ''' <typeparamref name="x">@E2</typeparamref> Public Event E2(a As Integer) ''' <summary><typeparamref name="x" nested="true">@P</typeparamref></summary> ''' <typeparamref name="x">@P</typeparamref> Property P As String ''' <summary><typeparamref name="x" nested="true">@P(a As String)</typeparamref></summary> ''' <typeparamref name="x">@P(a As String)</typeparamref> ReadOnly Property P(a As String) As String Get Return Nothing End Get End Property ''' <summary><typeparamref name="tt" nested="true">@D(a As Integer)</typeparamref></summary> ''' <typeparamref name="tt">@D(a As Integer)</typeparamref> Public Delegate Function D(Of TT)(a As Integer) As String ''' <summary><typeparamref name="t" nested="true">@SD(a As Integer)</typeparamref></summary> ''' <typeparamref name="t">@SD(a As Integer)</typeparamref> Public Delegate Sub SD(Of T)(a As Integer) ''' <summary><typeparamref name="x" nested="true">@ENM</typeparamref></summary> ''' <typeparamref name="x">@ENM</typeparamref> Public Enum ENM ''' <summary><typeparamref name="x" nested="true">@DefaultValue</typeparamref></summary> ''' <typeparamref name="x">@DefaultValue</typeparamref> DefaultValue End Enum ''' <summary><typeparamref name="tt" nested="true">@INT(Of TT)</typeparamref></summary> ''' <typeparamref name="tt">@INT(Of TT)</typeparamref> Public Interface INT(Of TT) ''' <summary><typeparamref name="t" nested="true">@INTS(a As Integer)</typeparamref></summary> ''' <typeparamref name="t">@INTS(a As Integer)</typeparamref> Sub INTS(Of T)(a As Integer) End Interface End Class ''' <typeparamref name="x" nested="true">@M0</typeparamref> ''' <summary><typeparamref name="x">@M0</typeparamref></summary> Public Module M0 ''' <typeparamref name="x" nested="true">@M0.a</typeparamref> ''' <summary><typeparamref name="x">@M0.a</typeparamref></summary> ''' <typeparamref>@M0.a -- no-name</typeparamref> Public a As Integer End Module ]]> </file> </compilation>, <errors> <![CDATA[ BC42317: XML comment type parameter 't' does not match a type parameter on the corresponding 'event' statement. ''' <summary><typeparamref name="t" nested="true">@E</typeparamref></summary> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42317: XML comment type parameter 't' does not match a type parameter on the corresponding 'event' statement. ''' <typeparamref name="t">@E</typeparamref> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'typeparamref' is not permitted on a 'module' language element. ''' <typeparamref name="x" nested="true">@M0</typeparamref> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42306: XML comment tag 'typeparamref' is not permitted on a 'module' language element. ''' <summary><typeparamref name="x">@M0</typeparamref></summary> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42317: XML comment type parameter 'x' does not match a type parameter on the corresponding 'variable' statement. ''' <typeparamref name="x" nested="true">@M0.a</typeparamref> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42317: XML comment type parameter 'x' does not match a type parameter on the corresponding 'variable' statement. ''' <summary><typeparamref name="x">@M0.a</typeparamref></summary> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]> </errors>) Dim tree As SyntaxTree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "t") Assert.Equal(8, names.Length) CheckSymbolInfoAndTypeInfo(model, DirectCast(names(0), ExpressionSyntax), "T") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(1), ExpressionSyntax), "T") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(2), ExpressionSyntax)) CheckSymbolInfoAndTypeInfo(model, DirectCast(names(3), ExpressionSyntax)) CheckSymbolInfoAndTypeInfo(model, DirectCast(names(4), ExpressionSyntax), "T") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(5), ExpressionSyntax), "T") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(6), ExpressionSyntax), "T") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(7), ExpressionSyntax), "T") names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "tt") Assert.Equal(6, names.Length) CheckSymbolInfoAndTypeInfo(model, DirectCast(names(0), ExpressionSyntax), "TT") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(1), ExpressionSyntax), "TT") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(2), ExpressionSyntax), "TT") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(3), ExpressionSyntax), "TT") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(4), ExpressionSyntax), "TT") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(5), ExpressionSyntax), "TT") names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "x") Assert.Equal(22, names.Length) CheckSymbolInfoAndTypeInfo(model, DirectCast(names(0), ExpressionSyntax), "X") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(1), ExpressionSyntax), "X") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(2), ExpressionSyntax), "X") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(3), ExpressionSyntax), "X") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(4), ExpressionSyntax), "X") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(5), ExpressionSyntax), "X") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(6), ExpressionSyntax), "X") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(7), ExpressionSyntax), "X") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(8), ExpressionSyntax), "X") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(9), ExpressionSyntax), "X") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(10), ExpressionSyntax), "X") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(11), ExpressionSyntax), "X") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(12), ExpressionSyntax), "X") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(13), ExpressionSyntax), "X") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(14), ExpressionSyntax), "X") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(15), ExpressionSyntax), "X") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(16), ExpressionSyntax), "X") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(17), ExpressionSyntax), "X") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(18), ExpressionSyntax)) CheckSymbolInfoAndTypeInfo(model, DirectCast(names(19), ExpressionSyntax)) CheckSymbolInfoAndTypeInfo(model, DirectCast(names(20), ExpressionSyntax)) CheckSymbolInfoAndTypeInfo(model, DirectCast(names(21), ExpressionSyntax)) End Sub <Fact()> Public Sub SemanticInfo_RightBinderAndSymbol() Dim compilation = CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System ''' <see cref="X">@OuterClass</see> ' Failed in dev11. ''' <see cref="S">@OuterClass</see> ' Failed in dev11. Public MustInherit Class OuterClass(Of X) ''' <see cref="X">@F</see> ''' <see cref="S">@F</see> ''' <see cref="T">@F</see> Public F As String ''' <see cref="X">@S</see> ''' <see cref="F">@S</see> ''' <see cref="a">@S</see> ''' <see cref="T">@S</see> Public Shared Sub S(Of T)(a As Integer) End Sub ''' <see cref="X">@FUN</see> ''' <see cref="F">@FUN</see> ''' <see cref="a">@FUN</see> ''' <see cref="T">@FUN</see> Public MustOverride Function FUN(Of T)(a As Integer) As String ''' <see cref="X">@InnerClass</see> ''' <see cref="F">@InnerClass</see> ''' <see cref="T">@InnerClass</see> ''' <see cref="Y">@InnerClass</see> ' Failed in dev11. Public Class InnerClass(Of Y) End Class ''' <see cref="X">@E</see> ''' <see cref="F">@E</see> ''' <see cref="T">@E</see> ''' <see cref="obj">@E</see> Public Event E As Action(Of Integer) ''' <see cref="X">@E2</see> ''' <see cref="F">@E2</see> ''' <see cref="a">@E2</see> ''' <see cref="T">@E2</see> Public Event E2(a As Integer) ''' <see cref="X">@P</see> ''' <see cref="F">@P</see> ''' <see cref="T">@P</see> Property P As String ''' <see cref="X">@P(a)</see> ''' <see cref="F">@P(a)</see> ''' <see cref="a">@P(a)</see> ''' <see cref="T">@P(a)</see> ReadOnly Property P(a As String) As String Get Return Nothing End Get End Property ''' <see cref="X">@D</see> ''' <see cref="F">@D</see> ''' <see cref="a">@D</see> ''' <see cref="T">@D</see> Public Delegate Function D(a As Integer) As String ''' <see cref="X">@SD</see> ''' <see cref="F">@SD</see> ''' <see cref="a">@SD</see> ''' <see cref="T">@SD</see> Public Delegate Sub SD(a As Integer) ''' <see cref="X">@ENM</see> ''' <see cref="F">@ENM</see> ''' <see cref="DefaultValue">@ENM</see> ' Failed in dev11. Public Enum ENM ''' <see cref="F">@DefaultValue</see> DefaultValue End Enum ''' <see cref="X">@INT</see> ''' <see cref="F">@INT</see> ''' <see cref="INTT">@INT</see> ' Failed in dev11. ''' <see cref="INTS">@INT</see> ' Failed in dev11. Public Interface INT(Of INTT) ''' <see cref="F">@INTS</see> Sub INTS(a As Integer) End Interface End Class ''' <see cref="Fun02">@M0</see> Public Module M0 ''' <see cref="Fun02">@Fun02</see> Public Function Fun02() As Integer Return Nothing End Function End Module ]]> </file> </compilation>, <errors> <![CDATA[ BC42375: XML comment has a tag with a 'cref' attribute 'X' that bound to a type parameter. Use the <typeparamref> tag instead. ''' <see cref="X">@OuterClass</see> ' Failed in dev11. ~~~~~~~~ BC42375: XML comment has a tag with a 'cref' attribute 'X' that bound to a type parameter. Use the <typeparamref> tag instead. ''' <see cref="X">@F</see> ~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'T' that could not be resolved. ''' <see cref="T">@F</see> ~~~~~~~~ BC42375: XML comment has a tag with a 'cref' attribute 'X' that bound to a type parameter. Use the <typeparamref> tag instead. ''' <see cref="X">@S</see> ~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'a' that could not be resolved. ''' <see cref="a">@S</see> ~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'T' that could not be resolved. ''' <see cref="T">@S</see> ~~~~~~~~ BC42375: XML comment has a tag with a 'cref' attribute 'X' that bound to a type parameter. Use the <typeparamref> tag instead. ''' <see cref="X">@FUN</see> ~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'a' that could not be resolved. ''' <see cref="a">@FUN</see> ~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'T' that could not be resolved. ''' <see cref="T">@FUN</see> ~~~~~~~~ BC42375: XML comment has a tag with a 'cref' attribute 'X' that bound to a type parameter. Use the <typeparamref> tag instead. ''' <see cref="X">@InnerClass</see> ~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'T' that could not be resolved. ''' <see cref="T">@InnerClass</see> ~~~~~~~~ BC42375: XML comment has a tag with a 'cref' attribute 'Y' that bound to a type parameter. Use the <typeparamref> tag instead. ''' <see cref="Y">@InnerClass</see> ' Failed in dev11. ~~~~~~~~ BC42375: XML comment has a tag with a 'cref' attribute 'X' that bound to a type parameter. Use the <typeparamref> tag instead. ''' <see cref="X">@E</see> ~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'T' that could not be resolved. ''' <see cref="T">@E</see> ~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'obj' that could not be resolved. ''' <see cref="obj">@E</see> ~~~~~~~~~~ BC42375: XML comment has a tag with a 'cref' attribute 'X' that bound to a type parameter. Use the <typeparamref> tag instead. ''' <see cref="X">@E2</see> ~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'a' that could not be resolved. ''' <see cref="a">@E2</see> ~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'T' that could not be resolved. ''' <see cref="T">@E2</see> ~~~~~~~~ BC42375: XML comment has a tag with a 'cref' attribute 'X' that bound to a type parameter. Use the <typeparamref> tag instead. ''' <see cref="X">@P</see> ~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'T' that could not be resolved. ''' <see cref="T">@P</see> ~~~~~~~~ BC42375: XML comment has a tag with a 'cref' attribute 'X' that bound to a type parameter. Use the <typeparamref> tag instead. ''' <see cref="X">@P(a)</see> ~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'a' that could not be resolved. ''' <see cref="a">@P(a)</see> ~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'T' that could not be resolved. ''' <see cref="T">@P(a)</see> ~~~~~~~~ BC42375: XML comment has a tag with a 'cref' attribute 'X' that bound to a type parameter. Use the <typeparamref> tag instead. ''' <see cref="X">@D</see> ~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'a' that could not be resolved. ''' <see cref="a">@D</see> ~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'T' that could not be resolved. ''' <see cref="T">@D</see> ~~~~~~~~ BC42375: XML comment has a tag with a 'cref' attribute 'X' that bound to a type parameter. Use the <typeparamref> tag instead. ''' <see cref="X">@SD</see> ~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'a' that could not be resolved. ''' <see cref="a">@SD</see> ~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'T' that could not be resolved. ''' <see cref="T">@SD</see> ~~~~~~~~ BC42375: XML comment has a tag with a 'cref' attribute 'X' that bound to a type parameter. Use the <typeparamref> tag instead. ''' <see cref="X">@ENM</see> ~~~~~~~~ BC42375: XML comment has a tag with a 'cref' attribute 'X' that bound to a type parameter. Use the <typeparamref> tag instead. ''' <see cref="X">@INT</see> ~~~~~~~~ BC42375: XML comment has a tag with a 'cref' attribute 'INTT' that bound to a type parameter. Use the <typeparamref> tag instead. ''' <see cref="INTT">@INT</see> ' Failed in dev11. ~~~~~~~~~~~ ]]> </errors>) Dim tree As SyntaxTree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "X") Assert.Equal(13, names.Length) CheckTypeParameterCrefSymbolInfoAndTypeInfo(model, names(0), "X") CheckTypeParameterCrefSymbolInfoAndTypeInfo(model, names(1), "X") CheckTypeParameterCrefSymbolInfoAndTypeInfo(model, names(2), "X") CheckTypeParameterCrefSymbolInfoAndTypeInfo(model, names(3), "X") CheckTypeParameterCrefSymbolInfoAndTypeInfo(model, names(4), "X") CheckTypeParameterCrefSymbolInfoAndTypeInfo(model, names(5), "X") CheckTypeParameterCrefSymbolInfoAndTypeInfo(model, names(6), "X") CheckTypeParameterCrefSymbolInfoAndTypeInfo(model, names(7), "X") CheckTypeParameterCrefSymbolInfoAndTypeInfo(model, names(8), "X") CheckTypeParameterCrefSymbolInfoAndTypeInfo(model, names(9), "X") CheckTypeParameterCrefSymbolInfoAndTypeInfo(model, names(10), "X") CheckTypeParameterCrefSymbolInfoAndTypeInfo(model, names(11), "X") CheckTypeParameterCrefSymbolInfoAndTypeInfo(model, names(12), "X") names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "S") Assert.Equal(2, names.Length) CheckSymbolInfoOnly(model, names(0), "Sub OuterClass(Of X).S(Of T)(a As System.Int32)") CheckSymbolInfoOnly(model, names(1), "Sub OuterClass(Of X).S(Of T)(a As System.Int32)") names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "T") Assert.Equal(10, names.Length) CheckSymbolInfoOnly(model, names(0)) CheckSymbolInfoOnly(model, names(1)) CheckSymbolInfoOnly(model, names(2)) CheckSymbolInfoOnly(model, names(3)) CheckSymbolInfoOnly(model, names(4)) CheckSymbolInfoOnly(model, names(5)) CheckSymbolInfoOnly(model, names(6)) CheckSymbolInfoOnly(model, names(7)) CheckSymbolInfoOnly(model, names(8)) CheckSymbolInfoOnly(model, names(9)) names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "F") Assert.Equal(13, names.Length) CheckSymbolInfoOnly(model, names(0), "OuterClass(Of X).F As System.String") CheckSymbolInfoOnly(model, names(1), "OuterClass(Of X).F As System.String") CheckSymbolInfoOnly(model, names(2), "OuterClass(Of X).F As System.String") CheckSymbolInfoOnly(model, names(3), "OuterClass(Of X).F As System.String") CheckSymbolInfoOnly(model, names(4), "OuterClass(Of X).F As System.String") CheckSymbolInfoOnly(model, names(5), "OuterClass(Of X).F As System.String") CheckSymbolInfoOnly(model, names(6), "OuterClass(Of X).F As System.String") CheckSymbolInfoOnly(model, names(7), "OuterClass(Of X).F As System.String") CheckSymbolInfoOnly(model, names(8), "OuterClass(Of X).F As System.String") CheckSymbolInfoOnly(model, names(9), "OuterClass(Of X).F As System.String") CheckSymbolInfoOnly(model, names(10), "OuterClass(Of X).F As System.String") CheckSymbolInfoOnly(model, names(11), "OuterClass(Of X).F As System.String") CheckSymbolInfoOnly(model, names(12), "OuterClass(Of X).F As System.String") names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "a") Assert.Equal(6, names.Length) CheckSymbolInfoOnly(model, names(0)) CheckSymbolInfoOnly(model, names(1)) CheckSymbolInfoOnly(model, names(2)) CheckSymbolInfoOnly(model, names(3)) CheckSymbolInfoOnly(model, names(4)) CheckSymbolInfoOnly(model, names(5)) names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "obj") Assert.Equal(1, names.Length) CheckSymbolInfoOnly(model, names(0)) names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "DefaultValue") Assert.Equal(1, names.Length) CheckSymbolInfoOnly(model, names(0), "OuterClass(Of X).ENM.DefaultValue") ' Did not bind in dev11. names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "Fun02") Assert.Equal(2, names.Length) CheckSymbolInfoOnly(model, names(0), "Function M0.Fun02() As System.Int32") CheckSymbolInfoOnly(model, names(0), "Function M0.Fun02() As System.Int32") names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "INTT") Assert.Equal(1, names.Length) CheckTypeParameterCrefSymbolInfoAndTypeInfo(model, names(0), "INTT") names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "INTS") Assert.Equal(1, names.Length) CheckSymbolInfoOnly(model, names(0), "Sub OuterClass(Of X).INT(Of INTT).INTS(a As System.Int32)") End Sub <Fact()> Public Sub SemanticInfo_SquareBrackets() Dim compilation = CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System ''' <typeparam name="X"></typeparam> ''' <typeparam name="[X]"></typeparam> ''' <typeparamref name="X"></typeparamref> ''' <typeparamref name="[X]"></typeparamref> Public MustInherit Class OuterClass(Of X) ''' <typeparamref name="X"></typeparamref> ''' <typeparamref name="[X]"></typeparamref> ''' <typeparam name="t"></typeparam> ''' <typeparam name="[t]"></typeparam> ''' <typeparamref name="t"></typeparamref> ''' <typeparamref name="[t]"></typeparamref> ''' <param name="a"></param> ''' <param name="[a]"></param> ''' <paramref name="A"></paramref> ''' <paramref name="[A]"></paramref> Public Shared Sub S(Of T)(a As Integer) End Sub End Class ]]> </file> </compilation>, <errors></errors>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:OuterClass`1"> <typeparam name="X"></typeparam> <typeparam name="[X]"></typeparam> <typeparamref name="X"></typeparamref> <typeparamref name="[X]"></typeparamref> </member> <member name="M:OuterClass`1.S``1(System.Int32)"> <typeparamref name="X"></typeparamref> <typeparamref name="[X]"></typeparamref> <typeparam name="t"></typeparam> <typeparam name="[t]"></typeparam> <typeparamref name="t"></typeparamref> <typeparamref name="[t]"></typeparamref> <param name="a"></param> <param name="[a]"></param> <paramref name="A"></paramref> <paramref name="[A]"></paramref> </member> </members> </doc> ]]> </xml>) Dim tree As SyntaxTree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "X") Assert.Equal(6, names.Length) CheckSymbolInfoAndTypeInfo(model, DirectCast(names(0), ExpressionSyntax), "X") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(1), ExpressionSyntax), "X") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(2), ExpressionSyntax), "X") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(3), ExpressionSyntax), "X") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(4), ExpressionSyntax), "X") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(5), ExpressionSyntax), "X") names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "t") Assert.Equal(4, names.Length) CheckSymbolInfoAndTypeInfo(model, DirectCast(names(0), ExpressionSyntax), "T") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(1), ExpressionSyntax), "T") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(2), ExpressionSyntax), "T") CheckSymbolInfoAndTypeInfo(model, DirectCast(names(3), ExpressionSyntax), "T") names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "a") Assert.Equal(2, names.Length) CheckSymbolInfoOnly(model, DirectCast(names(0), ExpressionSyntax), "a As System.Int32") CheckSymbolInfoOnly(model, DirectCast(names(1), ExpressionSyntax), "a As System.Int32") names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "A") Assert.Equal(2, names.Length) CheckSymbolInfoOnly(model, DirectCast(names(0), ExpressionSyntax), "a As System.Int32") CheckSymbolInfoOnly(model, DirectCast(names(1), ExpressionSyntax), "a As System.Int32") End Sub <Fact()> Public Sub SemanticModel_Accessibility() Dim compilation = CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Public Class OuterClass ''' <see cref="Other.S" /> ''' <see cref="c.n1.n2.t.C.c" /> Public Shared Sub Su(Of T)(a As Integer) End Sub End Class Public Class Other(Of OT) Private Shared Sub S(a As Integer) End Sub End Class Public Class C(Of T) Private Class N1 Private Class N2 Public Class T Public Class C ''' <see cref="t" /> Private C As T ''' <typeparamref name="t"/> Public Shared Sub XYZ(Of T)(a As Integer) End Sub End Class End Class End Class End Class End Class ]]> </file> </compilation>, Nothing) Dim tree As SyntaxTree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim text = tree.ToString() ' Other.S Dim names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "Other") Assert.Equal(1, names.Length) Dim symbols = CheckSymbolInfoAndTypeInfo(model, DirectCast(names(0), ExpressionSyntax), "Other(Of OT)") ' BREAK: dev11 includes "Sub Other(Of OT).S(a As System.Int32)" AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(text.IndexOf("Other.S""", StringComparison.Ordinal) + 5, container:=DirectCast(symbols(0), NamedTypeSymbol)), SymbolKind.Method), "Function System.Object.Equals(obj As System.Object) As System.Boolean", "Function System.Object.Equals(objA As System.Object, objB As System.Object) As System.Boolean", "Function System.Object.GetHashCode() As System.Int32", "Function System.Object.GetType() As System.Type", "Function System.Object.MemberwiseClone() As System.Object", "Function System.Object.ReferenceEquals(objA As System.Object, objB As System.Object) As System.Boolean", "Function System.Object.ToString() As System.String", "Sub System.Object.Finalize()") AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(text.IndexOf("Other.S""", StringComparison.Ordinal) + 5, container:=DirectCast(symbols(0), NamedTypeSymbol), name:="S"), SymbolKind.Method)) AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(text.IndexOf("Other.S""", StringComparison.Ordinal) + 5, container:=DirectCast(symbols(0), NamedTypeSymbol), name:="GetHashCode"), SymbolKind.Method), "Function System.Object.GetHashCode() As System.Int32") ' c.n1.n2.t.C names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "C") Assert.Equal(1, names.Length) ' BREAK: works in dev11. symbols = CheckSymbolInfoAndTypeInfo(model, DirectCast(names(0), ExpressionSyntax), "C(Of T).N1.N2.T.C") Assert.Equal(1, symbols.Length) ' "t" names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "t") Assert.Equal(3, names.Length) ' cref="t" symbols = CheckSymbolInfoAndTypeInfo(model, DirectCast(names(1), ExpressionSyntax), "C(Of T).N1.N2.T") Dim firstIndex = text.IndexOf("""t""", StringComparison.Ordinal) + 1 AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(firstIndex, name:="T"), SymbolKind.NamedType, SymbolKind.TypeParameter), "C(Of T).N1.N2.T") AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(firstIndex, name:="T", container:=symbols(0).ContainingType), SymbolKind.NamedType, SymbolKind.TypeParameter), "C(Of T).N1.N2.T") AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(firstIndex, name:="T", container:=symbols(0).ContainingType.ContainingType), SymbolKind.NamedType, SymbolKind.TypeParameter)) ' name="t" Dim secondSymbols = CheckSymbolInfoAndTypeInfo(model, DirectCast(names(2), ExpressionSyntax), "T") Dim secondIndex = text.IndexOf("""t""", firstIndex + 5, StringComparison.Ordinal) + 1 AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(secondIndex, name:="T"), SymbolKind.NamedType, SymbolKind.TypeParameter), "T") AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(secondIndex, name:="T", container:=symbols(0).ContainingType), SymbolKind.NamedType, SymbolKind.TypeParameter), "C(Of T).N1.N2.T") AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(secondIndex, name:="T", container:=secondSymbols(0).ContainingType), SymbolKind.NamedType, SymbolKind.TypeParameter)) End Sub <Fact> <WorkItem(4719, "https://github.com/dotnet/roslyn/issues/4719")> Public Sub CrefLookup() Dim source = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ ''' <summary> ''' See <see cref="C(Of U)" /> ''' </summary> Class C(Of T) Sub M() End Sub End Class Class Outer Private Class Inner End Class End Class ]]> </file> </compilation> Dim comp = CompileCheckDiagnosticsAndXmlDocument(source, <errors/>) Dim syntaxTree = comp.SyntaxTrees(0) Dim model = comp.GetSemanticModel(syntaxTree) Dim outer = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("Outer") Dim inner = outer.GetMember(Of NamedTypeSymbol)("Inner") Dim position = syntaxTree.ToString().IndexOf("(Of U)", StringComparison.Ordinal) Const bug4719IsFixed = False If bug4719IsFixed Then Assert.Equal(inner, model.LookupSymbols(position, outer, inner.Name).Single()) Else Assert.False(model.LookupSymbols(position, outer, inner.Name).Any()) End If End Sub <Fact()> Public Sub SemanticInfo_ErrorsInXmlGenerating_NoneInSemanticMode() Dim compilation = CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System ''' <summary> ''' <a>sss ''' </summary> Public Class TestClass Dim x As TestClass End Class ]]> </file> </compilation>, <errors> <![CDATA[ BC42304: XML documentation parse error: Element is missing an end tag. XML comment will be ignored. ''' <a>sss ~~~ BC42304: XML documentation parse error: '>' expected. XML comment will be ignored. ''' </summary> ~ BC42304: XML documentation parse error: Expected beginning '<' for an XML tag. XML comment will be ignored. ''' </summary> ~ BC42304: XML documentation parse error: XML name expected. XML comment will be ignored. ''' </summary> ~ ]]> </errors>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> </members> </doc> ]]> </xml>) Dim tree As SyntaxTree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "TestClass") Assert.Equal(1, names.Length) Dim symbols = CheckSymbolInfoAndTypeInfo(model, DirectCast(names(0), ExpressionSyntax), "TestClass") Assert.Equal(1, symbols.Length) Dim type = symbols(0) Assert.Equal(SymbolKind.NamedType, type.Kind) Dim docComment = type.GetDocumentationCommentXml() Assert.False(String.IsNullOrWhiteSpace(docComment)) Assert.Equal( <![CDATA[ <member name="T:TestClass"> <summary> <a>sss </summary> </member> ]]>.Value.Trim().Replace(vbLf, "").Replace(vbCr, ""), docComment.Trim().Replace(vbLf, "").Replace(vbCr, "")) End Sub <Fact()> Public Sub SemanticInfo_ErrorsInXmlGenerating_NoneInSemanticMode_PartialMethod() Dim compilation = CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Partial Public Class TestClass ''' <summary> Declaration </summary> Partial Private Sub PS() End Sub End Class Partial Public Class TestClass ''' <summary> Implementation Private Sub PS() PS() End Sub End Class ]]> </file> </compilation>, <errors> <![CDATA[ BC42304: XML documentation parse error: Element is missing an end tag. XML comment will be ignored. ''' <summary> Implementation ~~~~~~~~~ BC42304: XML documentation parse error: '>' expected. XML comment will be ignored. ''' <summary> Implementation ~ BC42304: XML documentation parse error: Expected beginning '<' for an XML tag. XML comment will be ignored. ''' <summary> Implementation ~ ]]> </errors>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="M:TestClass.PS"> <summary> Declaration </summary> </member> </members> </doc> ]]> </xml>) Dim tree As SyntaxTree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "PS") Assert.Equal(1, names.Length) Dim symbols = CheckSymbolInfoOnly(model, DirectCast(names(0), ExpressionSyntax), "Sub TestClass.PS()") Assert.Equal(1, symbols.Length) Dim method = symbols(0) Assert.Equal(SymbolKind.Method, method.Kind) Dim docComment = method.GetDocumentationCommentXml() Assert.False(String.IsNullOrWhiteSpace(docComment)) Assert.Equal("<member name=""M:TestClass.PS""> <summary> Implementation</member>".Trim(), docComment.Trim().Replace(vbLf, "").Replace(vbCr, "")) End Sub <Fact()> Public Sub Lookup_InsideParam() Dim compilation = CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Public Class OuterClass ''' <param name="a."/> ''' <param name="a"/> ''' <param name="[a]"/> ''' <typeparam name="[b]"/> ''' <see name="b"/> ''' <see cref="c"/> Public Shared Sub S(Of T)(a As Integer) End Sub End Class ]]> </file> </compilation>, Nothing) Dim tree As SyntaxTree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim text = tree.ToString() AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(text.IndexOf("""a.""", StringComparison.Ordinal) + 2), SymbolKind.Parameter), "a As System.Int32") AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(text.IndexOf("""a""", StringComparison.Ordinal) + 1), SymbolKind.Parameter), "a As System.Int32") AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(text.IndexOf("""[a]""", StringComparison.Ordinal) + 1), SymbolKind.Parameter), "a As System.Int32") AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(text.IndexOf("""[a]""", StringComparison.Ordinal) + 1), SymbolKind.TypeParameter)) AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(text.IndexOf("""[b]""", StringComparison.Ordinal) + 1), SymbolKind.Parameter)) AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(text.IndexOf("""b""", StringComparison.Ordinal) + 1), SymbolKind.Parameter)) AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(text.IndexOf("""c""", StringComparison.Ordinal) + 1), SymbolKind.Parameter)) End Sub <Fact()> Public Sub Lookup_InsideParamRef() Dim compilation = CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Public Class OuterClass ''' <paramref name="a."></paramref> ''' <paramref name="a"></paramref> ''' <paramref name="[a]"></paramref> ''' <typeparam name="[b]"/> ''' <see name="b"/> ''' <see cref="c"/> Public Shared Sub S(Of T)(a As Integer) End Sub End Class ]]> </file> </compilation>, Nothing) Dim tree As SyntaxTree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim text = tree.ToString() AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(text.IndexOf("""a.""", StringComparison.Ordinal) + 2), SymbolKind.Parameter), "a As System.Int32") AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(text.IndexOf("""a""", StringComparison.Ordinal) + 1), SymbolKind.Parameter), "a As System.Int32") AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(text.IndexOf("""[a]""", StringComparison.Ordinal) + 1), SymbolKind.Parameter), "a As System.Int32") AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(text.IndexOf("""[a]""", StringComparison.Ordinal) + 1), SymbolKind.TypeParameter)) AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(text.IndexOf("""[b]""", StringComparison.Ordinal) + 1), SymbolKind.Parameter)) AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(text.IndexOf("""b""", StringComparison.Ordinal) + 1), SymbolKind.Parameter)) AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(text.IndexOf("""c""", StringComparison.Ordinal) + 1), SymbolKind.Parameter)) End Sub <Fact()> Public Sub Lookup_InsideTypeParam() Dim compilation = CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Public Class OuterClass(Of X) ''' <typeparam name="a."></typeparam> ''' <typeparam name="a"></typeparam> ''' <typeparam name="[a]"></typeparam> ''' <param name="[b]"/> ''' <see name="b"/> ''' <see cref="c"/> Public Shared Sub S(Of T)(a As Integer) End Sub End Class ]]> </file> </compilation>, Nothing) Dim tree As SyntaxTree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim text = tree.ToString() AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(text.IndexOf("""a.""", StringComparison.Ordinal) + 2), SymbolKind.TypeParameter), "T", "X") AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(text.IndexOf("""a""", StringComparison.Ordinal) + 1), SymbolKind.TypeParameter), "T", "X") AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(text.IndexOf("""[a]""", StringComparison.Ordinal) + 1), SymbolKind.TypeParameter), "T", "X") AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(text.IndexOf("""[a]""", StringComparison.Ordinal) + 1), SymbolKind.Parameter)) AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(text.IndexOf("""[b]""", StringComparison.Ordinal) + 1), SymbolKind.TypeParameter), "X") AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(text.IndexOf("""b""", StringComparison.Ordinal) + 1), SymbolKind.TypeParameter), "X") AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(text.IndexOf("""b""", StringComparison.Ordinal) + 1), SymbolKind.TypeParameter), "X") End Sub <Fact()> Public Sub Lookup_InsideTypeParamRef() Dim compilation = CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Public Class OuterClass(Of X) ''' <typeparamref name="a."/> ''' <typeparamref name="a"/> ''' <typeparamref name="[a]"/> ''' <param name="[b]"/> ''' <see name="b"/> ''' <see cref="c"/> Public Shared Sub S(Of T)(a As Integer) End Sub End Class ]]> </file> </compilation>, Nothing) Dim tree As SyntaxTree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim text = tree.ToString() AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(text.IndexOf("""a.""", StringComparison.Ordinal) + 2), SymbolKind.TypeParameter), "T", "X") AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(text.IndexOf("""a""", StringComparison.Ordinal) + 1), SymbolKind.TypeParameter), "T", "X") AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(text.IndexOf("""[a]""", StringComparison.Ordinal) + 1), SymbolKind.TypeParameter), "T", "X") AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(text.IndexOf("""[a]""", StringComparison.Ordinal) + 1), SymbolKind.Parameter)) AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(text.IndexOf("""[b]""", StringComparison.Ordinal) + 1), SymbolKind.TypeParameter), "X") AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(text.IndexOf("""b""", StringComparison.Ordinal) + 1), SymbolKind.TypeParameter), "X") AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(text.IndexOf("""b""", StringComparison.Ordinal) + 1), SymbolKind.TypeParameter), "X") End Sub <Fact()> Public Sub Lookup_Cref() Dim compilation = CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System ''' <see cref="d"/> ''' <see cref="d."/> Public Class OuterClass(Of X) ''' <param name="[b]"/> ''' <see name="b"/> ''' <see cref="c"/> ''' <see cref="c."/> Public Shared Sub S(Of T)(a As Integer) End Sub End Class ]]> </file> </compilation>, Nothing) Dim tree As SyntaxTree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim text = tree.ToString() AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(text.IndexOf("""d.""", StringComparison.Ordinal) + 2), SymbolKind.TypeParameter, SymbolKind.Parameter), "X") AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(text.IndexOf("""d""", StringComparison.Ordinal) + 1), SymbolKind.TypeParameter, SymbolKind.Parameter), "X") AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(text.IndexOf("""[b]""", StringComparison.Ordinal) + 1), SymbolKind.TypeParameter, SymbolKind.Parameter), "a As System.Int32", "X") AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(text.IndexOf("""b""", StringComparison.Ordinal) + 1), SymbolKind.TypeParameter, SymbolKind.Parameter), "X") AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(text.IndexOf("""c""", StringComparison.Ordinal) + 1), SymbolKind.TypeParameter, SymbolKind.Parameter), "X") AssertLookupResult(FilterOfSymbolKindOnly( model.LookupSymbols(text.IndexOf("""c.""", StringComparison.Ordinal) + 1), SymbolKind.TypeParameter, SymbolKind.Parameter), "X") End Sub <Fact()> Public Sub Lookup_ParameterAndFieldConflict() Dim compilation = CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Public Class OuterClass Public X As String ''' <param name="X" cref="X"></param> Public Sub SSS(x As Integer) End Sub End Class ]]> </file> </compilation>, Nothing) Dim tree As SyntaxTree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim text = tree.ToString() ' X Dim names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "X") Assert.Equal(2, names.Length) CheckSymbolInfoOnly(model, DirectCast(names(0), ExpressionSyntax), "x As System.Int32") CheckSymbolInfoOnly(model, DirectCast(names(1), ExpressionSyntax), "OuterClass.X As System.String") AssertLookupResult( FilterOfSymbolKindOnly( model.LookupSymbols( text.IndexOf("name=""X""", StringComparison.Ordinal) + 6), SymbolKind.Field, SymbolKind.Parameter), "x As System.Int32") AssertLookupResult( FilterOfSymbolKindOnly( model.LookupSymbols( text.IndexOf("cref=""X""", StringComparison.Ordinal) + 6), SymbolKind.Field, SymbolKind.Parameter), "OuterClass.X As System.String") End Sub <Fact()> Public Sub Lookup_TypeParameterAndFieldConflict() Dim compilation = CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Public Class OuterClass Public X As String ''' <typeparamref name="X" cref="X"/> Public Sub SSS(Of X)() End Sub End Class ]]> </file> </compilation>, Nothing) Dim tree As SyntaxTree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim text = tree.ToString() ' X Dim names = FindNodesOfTypeFromText(Of NameSyntax)(tree, "X") Assert.Equal(2, names.Length) CheckSymbolInfoAndTypeInfo(model, DirectCast(names(0), ExpressionSyntax), "X") CheckSymbolInfoOnly(model, DirectCast(names(1), ExpressionSyntax), "OuterClass.X As System.String") AssertLookupResult( FilterOfSymbolKindOnly( model.LookupSymbols( text.IndexOf("name=""X""", StringComparison.Ordinal) + 6), SymbolKind.Field, SymbolKind.TypeParameter), "X") AssertLookupResult( FilterOfSymbolKindOnly( model.LookupSymbols( text.IndexOf("cref=""X""", StringComparison.Ordinal) + 6), SymbolKind.Field, SymbolKind.TypeParameter), "OuterClass.X As System.String") End Sub <Fact()> Public Sub Lookup_DoesNotDependOnContext() ' This test just proves that lookup result does not depend on ' context and returns, for example, fields in places where only ' type is expected Dim compilation = CompileCheckDiagnosticsAndXmlDocument( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Public Class OuterClass(Of W) Public X As String Public Sub SSS() Dim a As OuterClass(Of Integer) = Nothing End Sub End Class ]]> </file> </compilation>, Nothing) Dim tree As SyntaxTree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim text = tree.ToString() AssertLookupResult( FilterOfSymbolKindOnly( model.LookupSymbols( text.IndexOf("Of Integer", StringComparison.Ordinal) + 3), SymbolKind.Field), "OuterClass(Of W).X As System.String") Dim symInteger = FilterOfSymbolKindOnly( model.LookupSymbols( text.IndexOf("Of Integer", StringComparison.Ordinal) + 3, name:="Int32"), SymbolKind.NamedType) AssertLookupResult(symInteger, "System.Int32") AssertLookupResult( FilterOfSymbolKindOnly( model.LookupSymbols( text.IndexOf("Of Integer", StringComparison.Ordinal) + 3, name:="Parse", container:=DirectCast(symInteger(0), NamedTypeSymbol)), SymbolKind.Method), "Function System.Int32.Parse(s As System.String) As System.Int32", "Function System.Int32.Parse(s As System.String, provider As System.IFormatProvider) As System.Int32", "Function System.Int32.Parse(s As System.String, style As System.Globalization.NumberStyles) As System.Int32", "Function System.Int32.Parse(s As System.String, style As System.Globalization.NumberStyles, provider As System.IFormatProvider) As System.Int32") End Sub <Fact(Skip:="https://github.com/dotnet/roslyn/issues/8807")> Public Sub Include_XPathNotFound_WRN_XMLDocInvalidXMLFragment() Dim xmlText = <root/> Dim xmlFile = Temp.CreateFile(extension:=".xml").WriteAllText(xmlText.ToString) Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Imports System.Collections.Generic ''' <summary> ''' <include file='{0}' path='//target' /> ''' </summary> Class C End Class ]]> </file> </compilation> CompileCheckDiagnosticsAndXmlDocument(FormatSourceXml(xmlSource, xmlFile), <error></error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:C"> <summary> <!--warning BC42320: Unable to include XML fragment '//target' of file '**FILE**'.--> </summary> </member> </members> </doc> ]]> </xml>, stringMapper:=Function(o) StringReplace(o, AsXmlCommentText(xmlFile), "**FILE**"), ensureEnglishUICulture:=True) End Sub <WorkItem(684184, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/684184")> <Fact(Skip:="https://github.com/dotnet/roslyn/issues/8807")> Public Sub Bug684184() Dim xmlText = <docs> <doc for="DataRepeaterLayoutStyles"> <summary></summary> </doc> </docs> Dim xmlFile = Temp.CreateFile(extension:=".xml").WriteAllText(xmlText.ToString) Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System ''' <include file='{0}' path='docs2/doc[@for="DataRepeater"]/*' /> Public Class Clazz End Class ]]> </file> </compilation> CompileCheckDiagnosticsAndXmlDocument(FormatSourceXml(xmlSource, xmlFile), <error></error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:Clazz"> <!--warning BC42320: Unable to include XML fragment 'docs2/doc[@for="DataRepeater"]/*' of file '**FILE**'.--> </member> </members> </doc> ]]> </xml>, stringMapper:=Function(o) StringReplace(o, AsXmlCommentText(xmlFile), "**FILE**"), ensureEnglishUICulture:=True) End Sub <Fact(Skip:="https://github.com/dotnet/roslyn/issues/8807")> Public Sub Include_FileNotFound_WRN_XMLDocBadFormedXML() Dim xmlText = <root/> Dim xmlFile = Temp.CreateFile(extension:=".xml").WriteAllText(xmlText.ToString) Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Imports System.Collections.Generic ''' <summary> ''' <include file='{0}5' path='//target' /> ''' </summary> Class C End Class ]]> </file> </compilation> CompileCheckDiagnosticsAndXmlDocument(FormatSourceXml(xmlSource, xmlFile), <error></error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:C"> <summary> <!--warning BC42321: Unable to include XML fragment '//target' of file '**FILE**5'. File not found.--> </summary> </member> </members> </doc> ]]> </xml>, stringMapper:=Function(o) StringReplace(o, AsXmlCommentText(xmlFile), "**FILE**"), ensureEnglishUICulture:=True) End Sub <Fact(Skip:="https://github.com/dotnet/roslyn/issues/8807")> Public Sub Include_IOError_WRN_XMLDocBadFormedXML() Dim xmlText = <root> <target>Included</target> </root> Dim xmlFile = Temp.CreateFile(extension:=".xml").WriteAllText(xmlText.ToString) Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Imports System.Collections.Generic ''' <summary> ''' <include file='{0}' path='//target' /> ''' </summary> Class C End Class ]]> </file> </compilation> Using _stream = New FileStream(xmlFile.Path, FileMode.Open, FileAccess.ReadWrite) CompileCheckDiagnosticsAndXmlDocument(FormatSourceXml(xmlSource, xmlFile), <error></error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:C"> <summary> <!--warning BC42321: Unable to include XML fragment '//target' of file '**FILE**'. The process cannot access the file '**FILE**' because it is being used by another process.--> </summary> </member> </members> </doc> ]]> </xml>, stringMapper:=Function(o) StringReplace(o, AsXmlCommentText(xmlFile), "**FILE**"), ensureEnglishUICulture:=True) End Using End Sub <Fact(Skip:="https://github.com/dotnet/roslyn/issues/8807")> Public Sub Include_XmlError_WRN_XMLDocBadFormedXML() Dim xmlText = <![CDATA[ <root> <target>Included<target> </root> ]]> Dim xmlFile = Temp.CreateFile(extension:=".xml").WriteAllText(xmlText.Value.ToString) Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Imports System.Collections.Generic ''' <summary> ''' <include file='{0}' path='//target' /> ''' </summary> Class C End Class ]]> </file> </compilation> CompileCheckDiagnosticsAndXmlDocument(FormatSourceXml(xmlSource, xmlFile), <error></error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:C"> <summary> <!--warning BC42320: Unable to include XML fragment '//target' of file '**FILE**'.--> </summary> </member> </members> </doc> ]]> </xml>, stringMapper:=Function(o) StringReplace(o, AsXmlCommentText(xmlFile), "**FILE**"), ensureEnglishUICulture:=True) End Sub <Fact(Skip:="https://github.com/dotnet/roslyn/issues/8807")> Public Sub Include_XDocument_WRN_XMLDocInvalidXMLFragment() Dim xmlText = <![CDATA[ <root> <target>Included</target> </root> ]]> Dim xmlFile = Temp.CreateFile(extension:=".xml").WriteAllText(xmlText.Value.ToString) Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Imports System.Collections.Generic ''' <summary> ''' <include file='{0}' path='//target/../..' /> ''' </summary> Class C End Class ]]> </file> </compilation> CompileCheckDiagnosticsAndXmlDocument(FormatSourceXml(xmlSource, xmlFile), <error></error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:C"> <summary> <!--warning BC42320: Unable to include XML fragment '//target/../..' of file '**FILE**'.--> </summary> </member> </members> </doc> ]]> </xml>, stringMapper:=Function(o) StringReplace(o, AsXmlCommentText(xmlFile), "**FILE**"), ensureEnglishUICulture:=True) End Sub <Fact> Public Sub Include_Cycle_WRN_XMLDocInvalidXMLFragment() Dim xmlText = <root> <target> <nested> <include file='{0}' path='//target'/> </nested> </target> </root> Dim xmlFile = Temp.CreateFile(extension:=".xml") xmlFile.WriteAllText(String.Format(xmlText.ToString, xmlFile.ToString)) Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Imports System.Collections.Generic ''' <summary> ''' <include file='{0}' path='//target' /> ''' </summary> Class C End Class ]]> </file> </compilation> CompileCheckDiagnosticsAndXmlDocument(FormatSourceXml(xmlSource, xmlFile), <error><%= $"BC42320: Unable to include XML fragment '{xmlFile.ToString()}' of file '//target'." %></error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:C"> <summary> <target> <nested> <target> <nested> <!--warning BC42320: Unable to include XML fragment '**FILE**' of file '//target'.--> </nested> </target> </nested> </target> </summary> </member> </members> </doc> ]]> </xml>, stringMapper:=Function(o) StringReplace(o, AsXmlCommentText(xmlFile), "**FILE**"), ensureEnglishUICulture:=True) End Sub <Fact(Skip:="https://github.com/dotnet/roslyn/issues/8807")> Public Sub Include_XPathError_WRN_XMLDocBadFormedXML() Dim xmlText = <![CDATA[ <root> <target>Included</target> </root> ]]> Dim xmlFile = Temp.CreateFile(extension:=".xml").WriteAllText(xmlText.Value.ToString) Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Imports System.Collections.Generic ''' <summary> ''' <include file='{0}' path='//target/%^' /> ''' </summary> Class C End Class ]]> </file> </compilation> CompileCheckDiagnosticsAndXmlDocument(FormatSourceXml(xmlSource, xmlFile), <error></error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:C"> <summary> <!--warning BC42320: Unable to include XML fragment '//target/%^' of file '**FILE**'.--> </summary> </member> </members> </doc> ]]> </xml>, stringMapper:=Function(o) StringReplace(o, AsXmlCommentText(xmlFile), "**FILE**"), ensureEnglishUICulture:=True) End Sub <Fact> Public Sub Include_CrefHandling() Dim xmlText = <![CDATA[ <root> <target> Included section <summary> See <see cref="Module0"/>. See <see cref="Module0."/>. See <see cref="Module0. "/>. See <see cref="Module0 "/>. </summary> <remarks></remarks> </target> <target> Included section <summary> See <see cref="T:A.B.C"/>. See <see cref="Module1"/>. See <see cref="Module0.' "/>. See <see cref="Module0. _ "/>. </summary> <remarks></remarks> </target> </root> ]]> Dim xmlFile = Temp.CreateFile(extension:=".xml").WriteAllText(xmlText.Value.ToString) Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Imports System.Collections.Generic ''' <summary> ''' <include file='{0}' path='//target' /> ''' </summary> Class Module0 End Class ]]> </file> </compilation> CompileCheckDiagnosticsAndXmlDocument(FormatSourceXml(xmlSource, xmlFile), <error> <![CDATA[ BC42309: XML comment has a tag with a 'cref' attribute 'Module0. _' that could not be resolved. BC42309: XML comment has a tag with a 'cref' attribute 'Module0.' that could not be resolved. BC42309: XML comment has a tag with a 'cref' attribute 'Module0.' that could not be resolved. BC42309: XML comment has a tag with a 'cref' attribute 'Module0.'' that could not be resolved. BC42309: XML comment has a tag with a 'cref' attribute 'Module1' that could not be resolved. ]]> </error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:Module0"> <summary> <target> Included section <summary> See <see cref="T:Module0" />. See <see cref="?:Module0." />. See <see cref="?:Module0. " />. See <see cref="T:Module0" />. </summary> <remarks /> </target><target> Included section <summary> See <see cref="T:A.B.C" />. See <see cref="?:Module1" />. See <see cref="?:Module0.' " />. See <see cref="?:Module0. _ " />. </summary> <remarks /> </target> </summary> </member> </members> </doc> ]]> </xml>) End Sub <Fact> Public Sub Include_ParamAndParamRefHandling() Dim xmlText = <![CDATA[ <root> <target> Included section <summary> See <param/>. See <param name="PARAMA"/>. See <param name="PARAMb"/>. See <param name="b"/>. See <param name="B' comment "/>. See <param name="Parama "/>. </summary> <remarks></remarks> </target> <target> Included section <summary> See <paramref/>. See <paramref name="PARAMA"/>. See <paramref name="PARAMb"/>. See <paramref name="b"/>. See <paramref name="B' comment "/>. See <paramref name="Parama "/>. </summary> <remarks></remarks> </target> </root> ]]> Dim xmlFile = Temp.CreateFile(extension:=".xml").WriteAllText(xmlText.Value.ToString) Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Imports System.Collections.Generic Class Module0 ''' <summary> ''' <include file='{0}' path='//target' /> ''' </summary> Sub S(paramA As String, B As Integer) End Sub End Class ]]> </file> </compilation> CompileCheckDiagnosticsAndXmlDocument(FormatSourceXml(xmlSource, xmlFile), <error> <![CDATA[ BC42307: XML comment parameter 'B' comment' does not match a parameter on the corresponding 'sub' statement. BC42307: XML comment parameter 'B' comment' does not match a parameter on the corresponding 'sub' statement. BC42307: XML comment parameter 'PARAMb' does not match a parameter on the corresponding 'sub' statement. BC42307: XML comment parameter 'PARAMb' does not match a parameter on the corresponding 'sub' statement. BC42308: XML comment parameter must have a 'name' attribute. BC42308: XML comment parameter must have a 'name' attribute. ]]> </error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="M:Module0.S(System.String,System.Int32)"> <summary> <target> Included section <summary> See <!--warning BC42308: XML comment parameter must have a 'name' attribute.--><param />. See <param name="PARAMA" />. See <!--warning BC42307: XML comment parameter 'PARAMb' does not match a parameter on the corresponding 'sub' statement.--><param name="PARAMb" />. See <param name="b" />. See <!--warning BC42307: XML comment parameter 'B' comment' does not match a parameter on the corresponding 'sub' statement.--><param name="B' comment " />. See <param name="Parama " />. </summary> <remarks /> </target><target> Included section <summary> See <!--warning BC42308: XML comment parameter must have a 'name' attribute.--><paramref />. See <paramref name="PARAMA" />. See <!--warning BC42307: XML comment parameter 'PARAMb' does not match a parameter on the corresponding 'sub' statement.--><paramref name="PARAMb" />. See <paramref name="b" />. See <!--warning BC42307: XML comment parameter 'B' comment' does not match a parameter on the corresponding 'sub' statement.--><paramref name="B' comment " />. See <paramref name="Parama " />. </summary> <remarks /> </target> </summary> </member> </members> </doc> ]]> </xml>, ensureEnglishUICulture:=True) End Sub <Fact> Public Sub Include_TypeParamAndTypeParamRefHandling() Dim xmlText = <![CDATA[ <root> <target> Included section <summary> See <typeparam/>. See <typeparam name="X"/>. See <typeparam name="Y"/>. See <typeparam name="XY"/>. See <typeparam name="Y' comment "/>. See <typeparam name="Y "/>. </summary> <remarks></remarks> </target> <target> Included section <summary> See <typeparamref/>. See <typeparamref name="X"/>. See <typeparamref name="Y"/>. See <typeparamref name="XY"/>. See <typeparamref name="Y' comment "/>. See <typeparamref name="Y "/>. </summary> <remarks></remarks> </target> </root> ]]> Dim xmlFile = Temp.CreateFile(extension:=".xml").WriteAllText(xmlText.Value.ToString) Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Imports System.Collections.Generic Class OuterClass(Of X) ''' <summary> ''' <include file='{0}' path='//target' /> ''' </summary> Class InnerClass(Of Y) End Class End Class ]]> </file> </compilation> CompileCheckDiagnosticsAndXmlDocument(FormatSourceXml(xmlSource, xmlFile), <error> <![CDATA[ BC42317: XML comment type parameter 'X' does not match a type parameter on the corresponding 'class' statement. BC42317: XML comment type parameter 'XY' does not match a type parameter on the corresponding 'class' statement. BC42317: XML comment type parameter 'XY' does not match a type parameter on the corresponding 'class' statement. BC42317: XML comment type parameter 'Y' comment' does not match a type parameter on the corresponding 'class' statement. BC42317: XML comment type parameter 'Y' comment' does not match a type parameter on the corresponding 'class' statement. BC42318: XML comment type parameter must have a 'name' attribute. BC42318: XML comment type parameter must have a 'name' attribute. ]]> </error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:OuterClass`1.InnerClass`1"> <summary> <target> Included section <summary> See <!--warning BC42318: XML comment type parameter must have a 'name' attribute.--><typeparam />. See <!--warning BC42317: XML comment type parameter 'X' does not match a type parameter on the corresponding 'class' statement.--><typeparam name="X" />. See <typeparam name="Y" />. See <!--warning BC42317: XML comment type parameter 'XY' does not match a type parameter on the corresponding 'class' statement.--><typeparam name="XY" />. See <!--warning BC42317: XML comment type parameter 'Y' comment' does not match a type parameter on the corresponding 'class' statement.--><typeparam name="Y' comment " />. See <typeparam name="Y " />. </summary> <remarks /> </target><target> Included section <summary> See <!--warning BC42318: XML comment type parameter must have a 'name' attribute.--><typeparamref />. See <typeparamref name="X" />. See <typeparamref name="Y" />. See <!--warning BC42317: XML comment type parameter 'XY' does not match a type parameter on the corresponding 'class' statement.--><typeparamref name="XY" />. See <!--warning BC42317: XML comment type parameter 'Y' comment' does not match a type parameter on the corresponding 'class' statement.--><typeparamref name="Y' comment " />. See <typeparamref name="Y " />. </summary> <remarks /> </target> </summary> </member> </members> </doc> ]]> </xml>, ensureEnglishUICulture:=True) End Sub <Fact> Public Sub Include_Exception() Dim xmlText = <![CDATA[ <root> <target> <exception cref="Exception"/> <exception cref=""/> <exception/> </target> <targeterror> <exception cref="Exception"/> </targeterror> </root> ]]> Dim xmlFile = Temp.CreateFile(extension:=".xml").WriteAllText(xmlText.Value.ToString) Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Imports System.Collections.Generic ''' <include file='{0}' path='//targeterror' /> Public Module Module0 End Module ''' <include file='{0}' path='//targeterror' /> Public Class Clazz(Of X) ''' <include file='{0}' path='//target' /> Public Sub X1() End Sub ''' <include file='{0}' path='//target' /> Public Event E As Action ''' <include file='{0}' path='//targeterror' /> Public F As Integer ''' <include file='{0}' path='//target' /> Public Property P As Integer ''' <include file='{0}' path='//targeterror' /> Public Delegate Function FDelegate(a As Integer) As String ''' <include file='{0}' path='//targeterror' /> Public Enum En : A : End Enum ''' <include file='{0}' path='//targeterror' /> Public Structure STR : End Structure ''' <include file='{0}' path='//target' /> Public ReadOnly Property A(x As String) As String Get Return x End Get End Property End Class ]]> </file> </compilation> CompileCheckDiagnosticsAndXmlDocument(FormatSourceXml(xmlSource, xmlFile), <error> <![CDATA[ BC42306: XML comment tag 'exception' is not permitted on a 'class' language element. BC42306: XML comment tag 'exception' is not permitted on a 'delegate' language element. BC42306: XML comment tag 'exception' is not permitted on a 'enum' language element. BC42306: XML comment tag 'exception' is not permitted on a 'module' language element. BC42306: XML comment tag 'exception' is not permitted on a 'structure' language element. BC42306: XML comment tag 'exception' is not permitted on a 'variable' language element. BC42309: XML comment has a tag with a 'cref' attribute '' that could not be resolved. BC42309: XML comment has a tag with a 'cref' attribute '' that could not be resolved. BC42309: XML comment has a tag with a 'cref' attribute '' that could not be resolved. BC42309: XML comment has a tag with a 'cref' attribute '' that could not be resolved. BC42319: XML comment exception must have a 'cref' attribute. BC42319: XML comment exception must have a 'cref' attribute. BC42319: XML comment exception must have a 'cref' attribute. BC42319: XML comment exception must have a 'cref' attribute. ]]> </error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:Module0"> <targeterror> <!--warning BC42306: XML comment tag 'exception' is not permitted on a 'module' language element.--><exception cref="Exception" /> </targeterror> </member> <member name="T:Clazz`1"> <targeterror> <!--warning BC42306: XML comment tag 'exception' is not permitted on a 'class' language element.--><exception cref="Exception" /> </targeterror> </member> <member name="M:Clazz`1.X1"> <target> <exception cref="T:System.Exception" /> <exception cref="?:" /> <!--warning BC42319: XML comment exception must have a 'cref' attribute.--><exception /> </target> </member> <member name="E:Clazz`1.E"> <target> <exception cref="T:System.Exception" /> <exception cref="?:" /> <!--warning BC42319: XML comment exception must have a 'cref' attribute.--><exception /> </target> </member> <member name="F:Clazz`1.F"> <targeterror> <!--warning BC42306: XML comment tag 'exception' is not permitted on a 'variable' language element.--><exception cref="Exception" /> </targeterror> </member> <member name="P:Clazz`1.P"> <target> <exception cref="T:System.Exception" /> <exception cref="?:" /> <!--warning BC42319: XML comment exception must have a 'cref' attribute.--><exception /> </target> </member> <member name="T:Clazz`1.FDelegate"> <targeterror> <!--warning BC42306: XML comment tag 'exception' is not permitted on a 'delegate' language element.--><exception cref="Exception" /> </targeterror> </member> <member name="T:Clazz`1.En"> <targeterror> <!--warning BC42306: XML comment tag 'exception' is not permitted on a 'enum' language element.--><exception cref="Exception" /> </targeterror> </member> <member name="T:Clazz`1.STR"> <targeterror> <!--warning BC42306: XML comment tag 'exception' is not permitted on a 'structure' language element.--><exception cref="Exception" /> </targeterror> </member> <member name="P:Clazz`1.A(System.String)"> <target> <exception cref="T:System.Exception" /> <exception cref="?:" /> <!--warning BC42319: XML comment exception must have a 'cref' attribute.--><exception /> </target> </member> </members> </doc> ]]> </xml>, ensureEnglishUICulture:=True) End Sub <Fact> Public Sub Include_Returns() Dim xmlText = <![CDATA[ <root> <target> <returns/> </target> </root> ]]> Dim xmlFile = Temp.CreateFile(extension:=".xml").WriteAllText(xmlText.Value.ToString) Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Imports System.Collections.Generic ''' <include file='{0}' path='//target' /> Public Class TestClass ''' <include file='{0}' path='//target' /> Public Enum EN : A : End Enum ''' <include file='{0}' path='//target' /> Public Delegate Sub DelSub(a As Integer) ''' <include file='{0}' path='//target' /> Public Delegate Function DelFunc(a As Integer) As Integer ''' <include file='{0}' path='//target' /> Public Shared Sub MSub(p3 As Integer, p4 As String) End Sub ''' <include file='{0}' path='//target' /> Public Shared Function MFunc(p3 As Integer, p4 As String) As Integer Return Nothing End Function ''' <include file='{0}' path='//target' /> Public Field As Integer ''' <include file='{0}' path='//target' /> WithEvents FieldWE As TestClass ''' <include file='{0}' path='//target' /> Public Declare Function DeclareFtn Lib "bar" () As Integer ''' <include file='{0}' path='//target' /> Public Declare Sub DeclareSub Lib "bar" () ''' <include file='{0}' path='//target' /> Public ReadOnly Property PReadOnly As Integer Get Return Nothing End Get End Property ''' <include file='{0}' path='//target' /> Public Property PReadWrite As Integer Get Return Nothing End Get Set(value As Integer) End Set End Property ''' <include file='{0}' path='//target' /> Public WriteOnly Property PWriteOnly As Integer Set(value As Integer) End Set End Property ''' <include file='{0}' path='//target' /> Public Event EE(p11 As String) End Class ]]> </file> </compilation> CompileCheckDiagnosticsAndXmlDocument(FormatSourceXml(xmlSource, xmlFile), <error> <![CDATA[ BC42306: XML comment tag 'returns' is not permitted on a 'WithEvents variable' language element. BC42306: XML comment tag 'returns' is not permitted on a 'class' language element. BC42306: XML comment tag 'returns' is not permitted on a 'delegate sub' language element. BC42306: XML comment tag 'returns' is not permitted on a 'enum' language element. BC42306: XML comment tag 'returns' is not permitted on a 'event' language element. BC42306: XML comment tag 'returns' is not permitted on a 'sub' language element. BC42306: XML comment tag 'returns' is not permitted on a 'variable' language element. BC42313: XML comment tag 'returns' is not permitted on a 'WriteOnly' Property. BC42315: XML comment tag 'returns' is not permitted on a 'declare sub' language element. ]]> </error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:TestClass"> <target> <!--warning BC42306: XML comment tag 'returns' is not permitted on a 'class' language element.--><returns /> </target> </member> <member name="T:TestClass.EN"> <target> <!--warning BC42306: XML comment tag 'returns' is not permitted on a 'enum' language element.--><returns /> </target> </member> <member name="T:TestClass.DelSub"> <target> <!--warning BC42306: XML comment tag 'returns' is not permitted on a 'delegate sub' language element.--><returns /> </target> </member> <member name="T:TestClass.DelFunc"> <target> <returns /> </target> </member> <member name="M:TestClass.MSub(System.Int32,System.String)"> <target> <!--warning BC42306: XML comment tag 'returns' is not permitted on a 'sub' language element.--><returns /> </target> </member> <member name="M:TestClass.MFunc(System.Int32,System.String)"> <target> <returns /> </target> </member> <member name="F:TestClass.Field"> <target> <!--warning BC42306: XML comment tag 'returns' is not permitted on a 'variable' language element.--><returns /> </target> </member> <member name="F:TestClass._FieldWE"> <target> <!--warning BC42306: XML comment tag 'returns' is not permitted on a 'WithEvents variable' language element.--><returns /> </target> </member> <member name="M:TestClass.DeclareFtn"> <target> <returns /> </target> </member> <member name="M:TestClass.DeclareSub"> <target> <!--warning BC42315: XML comment tag 'returns' is not permitted on a 'declare sub' language element.--><returns /> </target> </member> <member name="P:TestClass.PReadOnly"> <target> <returns /> </target> </member> <member name="P:TestClass.PReadWrite"> <target> <returns /> </target> </member> <member name="P:TestClass.PWriteOnly"> <target> <!--warning BC42313: XML comment tag 'returns' is not permitted on a 'WriteOnly' Property.--><returns /> </target> </member> <member name="E:TestClass.EE"> <target> <!--warning BC42306: XML comment tag 'returns' is not permitted on a 'event' language element.--><returns /> </target> </member> </members> </doc> ]]> </xml>, ensureEnglishUICulture:=True) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:="https://github.com/dotnet/roslyn/issues/29531")> Public Sub Include_Value() Dim xmlText = <![CDATA[ <root> <target> <value/> </target> </root> ]]> Dim xmlFile = Temp.CreateFile(extension:=".xml").WriteAllText(xmlText.Value.ToString) Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Imports System.Collections.Generic ''' <include file='{0}' path='//target' /> Public Class TestClass ''' <include file='{0}' path='//target' /> Public Enum EN : A : End Enum ''' <include file='{0}' path='//target' /> Public Structure STR : End Structure ''' <include file='{0}' path='//target' /> Public Interface INTERF : End Interface ''' <include file='{0}' path='//target' /> Public Delegate Sub DelSub(a As Integer) ''' <include file='{0}' path='//target' /> Public Delegate Function DelFunc(a As Integer) As Integer ''' <include file='{0}' path='//target' /> Public Shared Sub MSub(p3 As Integer, p4 As String) End Sub ''' <include file='{0}' path='//target' /> Public Shared Function MFunc(p3 As Integer, p4 As String) As Integer Return Nothing End Function ''' <include file='{0}' path='//target' /> Public Declare Function DeclareFtn Lib "bar" (p3 As Integer) As Integer ''' <include file='{0}' path='//target' /> Public Field As Integer ''' <include file='{0}' path='//target' /> Public WriteOnly Property PWriteOnly(p As Integer) As Integer Set(value As Integer) End Set End Property ''' <include file='{0}' path='//target' /> Public Property PReadWrite As Integer ''' <include file='{0}' path='//target' /> Public Event EVE(ppp As Integer) End Class ]]> </file> </compilation> CompileCheckDiagnosticsAndXmlDocument(FormatSourceXml(xmlSource, xmlFile), <error> <![CDATA[ BC42306: XML comment tag 'value' is not permitted on a 'class' language element. BC42306: XML comment tag 'value' is not permitted on a 'declare' language element. BC42306: XML comment tag 'value' is not permitted on a 'delegate sub' language element. BC42306: XML comment tag 'value' is not permitted on a 'delegate' language element. BC42306: XML comment tag 'value' is not permitted on a 'enum' language element. BC42306: XML comment tag 'value' is not permitted on a 'event' language element. BC42306: XML comment tag 'value' is not permitted on a 'function' language element. BC42306: XML comment tag 'value' is not permitted on a 'interface' language element. BC42306: XML comment tag 'value' is not permitted on a 'structure' language element. BC42306: XML comment tag 'value' is not permitted on a 'sub' language element. BC42306: XML comment tag 'value' is not permitted on a 'variable' language element. ]]> </error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:TestClass"> <target> <!--warning BC42306: XML comment tag 'value' is not permitted on a 'class' language element.--><value /> </target> </member> <member name="T:TestClass.EN"> <target> <!--warning BC42306: XML comment tag 'value' is not permitted on a 'enum' language element.--><value /> </target> </member> <member name="T:TestClass.STR"> <target> <!--warning BC42306: XML comment tag 'value' is not permitted on a 'structure' language element.--><value /> </target> </member> <member name="T:TestClass.INTERF"> <target> <!--warning BC42306: XML comment tag 'value' is not permitted on a 'interface' language element.--><value /> </target> </member> <member name="T:TestClass.DelSub"> <target> <!--warning BC42306: XML comment tag 'value' is not permitted on a 'delegate sub' language element.--><value /> </target> </member> <member name="T:TestClass.DelFunc"> <target> <!--warning BC42306: XML comment tag 'value' is not permitted on a 'delegate' language element.--><value /> </target> </member> <member name="M:TestClass.MSub(System.Int32,System.String)"> <target> <!--warning BC42306: XML comment tag 'value' is not permitted on a 'sub' language element.--><value /> </target> </member> <member name="M:TestClass.MFunc(System.Int32,System.String)"> <target> <!--warning BC42306: XML comment tag 'value' is not permitted on a 'function' language element.--><value /> </target> </member> <member name="M:TestClass.DeclareFtn(System.Int32)"> <target> <!--warning BC42306: XML comment tag 'value' is not permitted on a 'declare' language element.--><value /> </target> </member> <member name="F:TestClass.Field"> <target> <!--warning BC42306: XML comment tag 'value' is not permitted on a 'variable' language element.--><value /> </target> </member> <member name="P:TestClass.PWriteOnly(System.Int32)"> <target> <value /> </target> </member> <member name="P:TestClass.PReadWrite"> <target> <value /> </target> </member> <member name="E:TestClass.EVE"> <target> <!--warning BC42306: XML comment tag 'value' is not permitted on a 'event' language element.--><value /> </target> </member> </members> </doc> ]]> </xml>, ensureEnglishUICulture:=True) End Sub <Fact> Public Sub Include_ParamAndParamRef() Dim xmlText = <![CDATA[ <root> <target> <param name="P9"/> <paramref name="P9"/> </target> </root> ]]> Dim xmlFile = Temp.CreateFile(extension:=".xml").WriteAllText(xmlText.Value.ToString) Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Imports System.Collections.Generic ''' <include file='{0}' path='//target' /> Public Class TestClass ''' <include file='{0}' path='//target' /> Public Shared Sub M(P9 As Integer, p4 As String) Dim a As TestClass = Nothing End Sub ''' <include file='{0}' path='//target' /> Public F As Integer ''' <include file='{0}' path='//target' /> Public Property P As Integer ''' <include file='{0}' path='//target' /> Public ReadOnly Property P(P9 As String) As Integer Get Return Nothing End Get End Property ''' <include file='{0}' path='//target' /> Public Event EE(P9 As String) End Class ]]> </file> </compilation> CompileCheckDiagnosticsAndXmlDocument(FormatSourceXml(xmlSource, xmlFile), <error> <![CDATA[ BC42306: XML comment tag 'param' is not permitted on a 'class' language element. BC42306: XML comment tag 'param' is not permitted on a 'variable' language element. BC42306: XML comment tag 'paramref' is not permitted on a 'class' language element. BC42306: XML comment tag 'paramref' is not permitted on a 'variable' language element. BC42307: XML comment parameter 'P9' does not match a parameter on the corresponding 'property' statement. BC42307: XML comment parameter 'P9' does not match a parameter on the corresponding 'property' statement. ]]> </error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:TestClass"> <target> <!--warning BC42306: XML comment tag 'param' is not permitted on a 'class' language element.--><param name="P9" /> <!--warning BC42306: XML comment tag 'paramref' is not permitted on a 'class' language element.--><paramref name="P9" /> </target> </member> <member name="M:TestClass.M(System.Int32,System.String)"> <target> <param name="P9" /> <paramref name="P9" /> </target> </member> <member name="F:TestClass.F"> <target> <!--warning BC42306: XML comment tag 'param' is not permitted on a 'variable' language element.--><param name="P9" /> <!--warning BC42306: XML comment tag 'paramref' is not permitted on a 'variable' language element.--><paramref name="P9" /> </target> </member> <member name="P:TestClass.P"> <target> <!--warning BC42307: XML comment parameter 'P9' does not match a parameter on the corresponding 'property' statement.--><param name="P9" /> <!--warning BC42307: XML comment parameter 'P9' does not match a parameter on the corresponding 'property' statement.--><paramref name="P9" /> </target> </member> <member name="P:TestClass.P(System.String)"> <target> <param name="P9" /> <paramref name="P9" /> </target> </member> <member name="E:TestClass.EE"> <target> <param name="P9" /> <paramref name="P9" /> </target> </member> </members> </doc> ]]> </xml>, ensureEnglishUICulture:=True) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:="https://github.com/dotnet/roslyn/issues/29531")> Public Sub Include_TypeParamAndTypeParamRef() Dim xmlText = <![CDATA[ <root> <target> <typeparam name="P9"/> <typeparamref name="P9"/> </target> </root> ]]> Dim xmlFile = Temp.CreateFile(extension:=".xml").WriteAllText(xmlText.Value.ToString) Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Imports System.Collections.Generic ''' <include file='{0}' path='//target' /> Public Module Module0 ''' <include file='{0}' path='//target' /> Public Declare Function DeclareFtn Lib "bar" (p3 As Integer) As Integer End Module ''' <include file='{0}' path='//target' /> Public Class TestClass(Of P9) ''' <include file='{0}' path='//target' /> Public Enum EN : A : End Enum ''' <include file='{0}' path='//target' /> Public Structure STR(Of X) : End Structure ''' <include file='{0}' path='//target' /> Public Interface INTERF(Of X, Y) : End Interface ''' <include file='{0}' path='//target' /> Public Delegate Sub DelSub(Of W)(a As Integer) ''' <include file='{0}' path='//target' /> Public Delegate Function DelFunc(Of W)(a As Integer) As Integer ''' <include file='{0}' path='//target' /> Public Shared Sub MSub(Of TT)(p3 As Integer, p4 As String) End Sub ''' <include file='{0}' path='//target' /> Public Shared Function MFunc(p3 As Integer, p4 As String) As Integer Return Nothing End Function ''' <include file='{0}' path='//target' /> Public Field As Integer ''' <include file='{0}' path='//target' /> Public WriteOnly Property PWriteOnly(p As Integer) As Integer Set(value As Integer) End Set End Property ''' <include file='{0}' path='//target' /> Public Property PReadWrite As Integer ''' <include file='{0}' path='//target' /> Public Event EVE(ppp As Integer) End Class ]]> </file> </compilation> CompileCheckDiagnosticsAndXmlDocument(FormatSourceXml(xmlSource, xmlFile), <error> <![CDATA[ BC42306: XML comment tag 'typeparam' is not permitted on a 'declare' language element. BC42306: XML comment tag 'typeparam' is not permitted on a 'enum' language element. BC42306: XML comment tag 'typeparam' is not permitted on a 'event' language element. BC42306: XML comment tag 'typeparam' is not permitted on a 'module' language element. BC42306: XML comment tag 'typeparam' is not permitted on a 'property' language element. BC42306: XML comment tag 'typeparam' is not permitted on a 'property' language element. BC42306: XML comment tag 'typeparam' is not permitted on a 'variable' language element. BC42306: XML comment tag 'typeparamref' is not permitted on a 'module' language element. BC42317: XML comment type parameter 'P9' does not match a type parameter on the corresponding 'declare' statement. BC42317: XML comment type parameter 'P9' does not match a type parameter on the corresponding 'delegate sub' statement. BC42317: XML comment type parameter 'P9' does not match a type parameter on the corresponding 'delegate' statement. BC42317: XML comment type parameter 'P9' does not match a type parameter on the corresponding 'function' statement. BC42317: XML comment type parameter 'P9' does not match a type parameter on the corresponding 'interface' statement. BC42317: XML comment type parameter 'P9' does not match a type parameter on the corresponding 'structure' statement. BC42317: XML comment type parameter 'P9' does not match a type parameter on the corresponding 'sub' statement. ]]> </error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:Module0"> <target> <!--warning BC42306: XML comment tag 'typeparam' is not permitted on a 'module' language element.--><typeparam name="P9" /> <!--warning BC42306: XML comment tag 'typeparamref' is not permitted on a 'module' language element.--><typeparamref name="P9" /> </target> </member> <member name="M:Module0.DeclareFtn(System.Int32)"> <target> <!--warning BC42306: XML comment tag 'typeparam' is not permitted on a 'declare' language element.--><typeparam name="P9" /> <!--warning BC42317: XML comment type parameter 'P9' does not match a type parameter on the corresponding 'declare' statement.--><typeparamref name="P9" /> </target> </member> <member name="T:TestClass`1"> <target> <typeparam name="P9" /> <typeparamref name="P9" /> </target> </member> <member name="T:TestClass`1.EN"> <target> <!--warning BC42306: XML comment tag 'typeparam' is not permitted on a 'enum' language element.--><typeparam name="P9" /> <typeparamref name="P9" /> </target> </member> <member name="T:TestClass`1.STR`1"> <target> <!--warning BC42317: XML comment type parameter 'P9' does not match a type parameter on the corresponding 'structure' statement.--><typeparam name="P9" /> <typeparamref name="P9" /> </target> </member> <member name="T:TestClass`1.INTERF`2"> <target> <!--warning BC42317: XML comment type parameter 'P9' does not match a type parameter on the corresponding 'interface' statement.--><typeparam name="P9" /> <typeparamref name="P9" /> </target> </member> <member name="T:TestClass`1.DelSub`1"> <target> <!--warning BC42317: XML comment type parameter 'P9' does not match a type parameter on the corresponding 'delegate sub' statement.--><typeparam name="P9" /> <typeparamref name="P9" /> </target> </member> <member name="T:TestClass`1.DelFunc`1"> <target> <!--warning BC42317: XML comment type parameter 'P9' does not match a type parameter on the corresponding 'delegate' statement.--><typeparam name="P9" /> <typeparamref name="P9" /> </target> </member> <member name="M:TestClass`1.MSub``1(System.Int32,System.String)"> <target> <!--warning BC42317: XML comment type parameter 'P9' does not match a type parameter on the corresponding 'sub' statement.--><typeparam name="P9" /> <typeparamref name="P9" /> </target> </member> <member name="M:TestClass`1.MFunc(System.Int32,System.String)"> <target> <!--warning BC42317: XML comment type parameter 'P9' does not match a type parameter on the corresponding 'function' statement.--><typeparam name="P9" /> <typeparamref name="P9" /> </target> </member> <member name="F:TestClass`1.Field"> <target> <!--warning BC42306: XML comment tag 'typeparam' is not permitted on a 'variable' language element.--><typeparam name="P9" /> <typeparamref name="P9" /> </target> </member> <member name="P:TestClass`1.PWriteOnly(System.Int32)"> <target> <!--warning BC42306: XML comment tag 'typeparam' is not permitted on a 'property' language element.--><typeparam name="P9" /> <typeparamref name="P9" /> </target> </member> <member name="P:TestClass`1.PReadWrite"> <target> <!--warning BC42306: XML comment tag 'typeparam' is not permitted on a 'property' language element.--><typeparam name="P9" /> <typeparamref name="P9" /> </target> </member> <member name="E:TestClass`1.EVE"> <target> <!--warning BC42306: XML comment tag 'typeparam' is not permitted on a 'event' language element.--><typeparam name="P9" /> <typeparamref name="P9" /> </target> </member> </members> </doc> ]]> </xml>, ensureEnglishUICulture:=True) End Sub <Fact> Public Sub Include_TypeParameterCref() Dim xmlText = <![CDATA[ <root> <target> <see cref="P9"/> </target> </root> ]]> Dim xmlFile = Temp.CreateFile(extension:=".xml").WriteAllText(xmlText.Value.ToString) Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Imports System.Collections.Generic ''' <include file='{0}' path='//target' /> Public Module Module0 ''' <include file='{0}' path='//target' /> Public Declare Function DeclareFtn Lib "bar" (p3 As Integer) As Integer End Module ''' <include file='{0}' path='//target' /> Public Class TestClass(Of P9) ''' <include file='{0}' path='//target' /> Public Enum EN : A : End Enum ''' <include file='{0}' path='//target' /> Public Structure STR(Of X) : End Structure ''' <include file='{0}' path='//target' /> Public Interface INTERF(Of X, Y) : End Interface ''' <include file='{0}' path='//target' /> Public Delegate Sub DelSub(Of W)(a As Integer) ''' <include file='{0}' path='//target' /> Public Delegate Function DelFunc(Of W)(a As Integer) As Integer ''' <include file='{0}' path='//target' /> Public Shared Sub MSub(Of TT)(p3 As Integer, p4 As String) End Sub ''' <include file='{0}' path='//target' /> Public Shared Function MFunc(p3 As Integer, p4 As String) As Integer Return Nothing End Function ''' <include file='{0}' path='//target' /> Public Field As Integer ''' <include file='{0}' path='//target' /> Public WriteOnly Property PWriteOnly(p As Integer) As Integer Set(value As Integer) End Set End Property ''' <include file='{0}' path='//target' /> Public Property PReadWrite As Integer ''' <include file='{0}' path='//target' /> Public Event EVE(ppp As Integer) End Class ]]> </file> </compilation> CompileCheckDiagnosticsAndXmlDocument(FormatSourceXml(xmlSource, xmlFile), <error> <![CDATA[ BC42309: XML comment has a tag with a 'cref' attribute 'P9' that could not be resolved. BC42309: XML comment has a tag with a 'cref' attribute 'P9' that could not be resolved. BC42375: XML comment has a tag with a 'cref' attribute 'P9' that bound to a type parameter. Use the <typeparamref> tag instead. BC42375: XML comment has a tag with a 'cref' attribute 'P9' that bound to a type parameter. Use the <typeparamref> tag instead. BC42375: XML comment has a tag with a 'cref' attribute 'P9' that bound to a type parameter. Use the <typeparamref> tag instead. BC42375: XML comment has a tag with a 'cref' attribute 'P9' that bound to a type parameter. Use the <typeparamref> tag instead. BC42375: XML comment has a tag with a 'cref' attribute 'P9' that bound to a type parameter. Use the <typeparamref> tag instead. BC42375: XML comment has a tag with a 'cref' attribute 'P9' that bound to a type parameter. Use the <typeparamref> tag instead. BC42375: XML comment has a tag with a 'cref' attribute 'P9' that bound to a type parameter. Use the <typeparamref> tag instead. BC42375: XML comment has a tag with a 'cref' attribute 'P9' that bound to a type parameter. Use the <typeparamref> tag instead. BC42375: XML comment has a tag with a 'cref' attribute 'P9' that bound to a type parameter. Use the <typeparamref> tag instead. BC42375: XML comment has a tag with a 'cref' attribute 'P9' that bound to a type parameter. Use the <typeparamref> tag instead. BC42375: XML comment has a tag with a 'cref' attribute 'P9' that bound to a type parameter. Use the <typeparamref> tag instead. BC42375: XML comment has a tag with a 'cref' attribute 'P9' that bound to a type parameter. Use the <typeparamref> tag instead. ]]> </error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:Module0"> <target> <see cref="?:P9" /> </target> </member> <member name="M:Module0.DeclareFtn(System.Int32)"> <target> <see cref="?:P9" /> </target> </member> <member name="T:TestClass`1"> <target> <see cref="?:P9" /> </target> </member> <member name="T:TestClass`1.EN"> <target> <see cref="?:P9" /> </target> </member> <member name="T:TestClass`1.STR`1"> <target> <see cref="?:P9" /> </target> </member> <member name="T:TestClass`1.INTERF`2"> <target> <see cref="?:P9" /> </target> </member> <member name="T:TestClass`1.DelSub`1"> <target> <see cref="?:P9" /> </target> </member> <member name="T:TestClass`1.DelFunc`1"> <target> <see cref="?:P9" /> </target> </member> <member name="M:TestClass`1.MSub``1(System.Int32,System.String)"> <target> <see cref="?:P9" /> </target> </member> <member name="M:TestClass`1.MFunc(System.Int32,System.String)"> <target> <see cref="?:P9" /> </target> </member> <member name="F:TestClass`1.Field"> <target> <see cref="?:P9" /> </target> </member> <member name="P:TestClass`1.PWriteOnly(System.Int32)"> <target> <see cref="?:P9" /> </target> </member> <member name="P:TestClass`1.PReadWrite"> <target> <see cref="?:P9" /> </target> </member> <member name="E:TestClass`1.EVE"> <target> <see cref="?:P9" /> </target> </member> </members> </doc> ]]> </xml>) End Sub <Fact> Private Sub ExtendedCref_IdentifierInName_IdentifierAndGenericInSignature() Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Imports System.Collections.Generic Public Structure TestStruct ''' <see cref="T(List(Of Int32), TestStruct)"/> Public Shared field As Integer Sub T(p As List(Of Int32), i as TestStruct) End Sub End Structure ]]> </file> </compilation> Dim xmlDoc = <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="F:TestStruct.field"> <see cref="M:TestStruct.T(System.Collections.Generic.List{System.Int32},TestStruct)"/> </member> </members> </doc> ]]> </xml> Dim compilation = CompileCheckDiagnosticsAndXmlDocument(xmlSource, <errors></errors>, xmlDoc) Dim model = compilation.GetSemanticModel(compilation.SyntaxTrees(0)) Dim crefNodes = CrefFinder.FindAllCrefs(compilation.SyntaxTrees(0)) Assert.Equal(1, crefNodes.Count) Dim info = model.GetSymbolInfo(crefNodes(0)) Assert.NotNull(info.Symbol) Assert.Equal("Sub TestStruct.T(p As System.Collections.Generic.List(Of System.Int32), i As TestStruct)", info.Symbol.ToTestDisplayString()) CheckAllNames(model, crefNodes(0), New NameSyntaxInfo("T", {"Sub TestStruct.T(p As System.Collections.Generic.List(Of System.Int32), i As TestStruct)"}, {}), New NameSyntaxInfo("List(Of Int32)", {"System.Collections.Generic.List(Of System.Int32)"}, {"System.Collections.Generic.List(Of System.Int32)"}), New NameSyntaxInfo("Int32", {"System.Int32"}, {"System.Int32"}), New NameSyntaxInfo("TestStruct", {"TestStruct"}, {"TestStruct"})) End Sub <WorkItem(703587, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/703587")> <Fact()> Private Sub ObjectMemberViaInterfaceA() Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System ''' Comment Public Class C Implements IEquatable(Of C) ''' Implements <see cref="IEquatable(Of T).Equals"/>. ''' Implements <see cref="IEquatable(Of T).GetHashCode"/>. ''' Implements <see cref="IEquatable(Of T).Equals(T)"/>. ''' Implements <see cref="IEquatable(Of T).GetHashCode()"/>. Public Function IEquals(c As C) As Boolean Implements IEquatable(Of C).Equals Return False End Function End Class ]]> </file> </compilation> Dim xmlDoc = <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:C"> Comment </member> <member name="M:C.IEquals(C)"> Implements <see cref="M:System.IEquatable`1.Equals(`0)"/>. Implements <see cref="!:IEquatable(Of T).GetHashCode"/>. Implements <see cref="M:System.IEquatable`1.Equals(`0)"/>. Implements <see cref="!:IEquatable(Of T).GetHashCode()"/>. </member> </members> </doc> ]]> </xml> CompileCheckDiagnosticsAndXmlDocument(xmlSource, <errors> <![CDATA[ BC42309: XML comment has a tag with a 'cref' attribute 'IEquatable(Of T).GetHashCode' that could not be resolved. ''' Implements <see cref="IEquatable(Of T).GetHashCode"/>. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'IEquatable(Of T).GetHashCode()' that could not be resolved. ''' Implements <see cref="IEquatable(Of T).GetHashCode()"/>. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]> </errors>, xmlDoc) End Sub <WorkItem(703587, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/703587")> <Fact()> Private Sub ObjectMemberViaInterfaceB() Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System ''' Comment Public Interface INT Inherits IEquatable(Of Integer) ''' Implements <see cref="Equals"/>. ''' Implements <see cref="IEquals(Integer)"/>. ''' Implements <see cref="Equals(Object)"/>. ''' Implements <see cref="Equals(Integer)"/>. ''' Implements <see cref="GetHashCode"/>. ''' Implements <see cref="GetHashCode()"/>. Function IEquals(c As Integer) As Boolean End Interface ]]> </file> </compilation> Dim xmlDoc = <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:INT"> Comment </member> <member name="M:INT.IEquals(System.Int32)"> Implements <see cref="M:System.IEquatable`1.Equals(`0)"/>. Implements <see cref="M:INT.IEquals(System.Int32)"/>. Implements <see cref="!:Equals(Object)"/>. Implements <see cref="M:System.IEquatable`1.Equals(`0)"/>. Implements <see cref="!:GetHashCode"/>. Implements <see cref="!:GetHashCode()"/>. </member> </members> </doc> ]]> </xml> CompileCheckDiagnosticsAndXmlDocument(xmlSource, <errors> <![CDATA[ BC42309: XML comment has a tag with a 'cref' attribute 'Equals(Object)' that could not be resolved. ''' Implements <see cref="Equals(Object)"/>. ~~~~~~~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'GetHashCode' that could not be resolved. ''' Implements <see cref="GetHashCode"/>. ~~~~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'GetHashCode()' that could not be resolved. ''' Implements <see cref="GetHashCode()"/>. ~~~~~~~~~~~~~~~~~~~~ ]]> </errors>, xmlDoc) End Sub <Fact> Private Sub ExtendedCref_GenericInName_IdentifierInSignature() Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Public Structure TestStruct ''' <see cref="T(Of T)(T, TestStruct)"/> Public Shared field As Integer Sub T(Of T)(p As T, i as TestStruct) End Sub End Structure ]]> </file> </compilation> Dim xmlDoc = <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="F:TestStruct.field"> <see cref="M:TestStruct.T``1(``0,TestStruct)"/> </member> </members> </doc> ]]> </xml> Dim compilation = CompileCheckDiagnosticsAndXmlDocument(xmlSource, <errors></errors>, xmlDoc) Dim model = compilation.GetSemanticModel(compilation.SyntaxTrees(0)) Dim crefNodes = CrefFinder.FindAllCrefs(compilation.SyntaxTrees(0)) Assert.Equal(1, crefNodes.Count) Dim info = model.GetSymbolInfo(crefNodes(0)) Assert.NotNull(info.Symbol) Assert.Equal("Sub TestStruct.T(Of T)(p As T, i As TestStruct)", info.Symbol.ToTestDisplayString()) CheckAllNames(model, crefNodes(0), New NameSyntaxInfo("T(Of T)", {"Sub TestStruct.T(Of T)(p As T, i As TestStruct)"}, {}), New NameSyntaxInfo("T", {"T"}, {"T"}), New NameSyntaxInfo("T", {"T"}, {"T"}), New NameSyntaxInfo("TestStruct", {"TestStruct"}, {"TestStruct"})) End Sub <Fact> Private Sub ExtendedCref_GenericInName_GlobalInSignature() Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Public Structure TestStruct ''' <see cref="T(Of T)(T, Global.TestStruct)"/> Public Shared field As Integer Sub T(Of T)(p As T, i as TestStruct) End Sub End Structure ]]> </file> </compilation> Dim xmlDoc = <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="F:TestStruct.field"> <see cref="M:TestStruct.T``1(``0,TestStruct)"/> </member> </members> </doc> ]]> </xml> Dim compilation = CompileCheckDiagnosticsAndXmlDocument(xmlSource, <errors></errors>, xmlDoc) Dim model = compilation.GetSemanticModel(compilation.SyntaxTrees(0)) Dim crefNodes = CrefFinder.FindAllCrefs(compilation.SyntaxTrees(0)) Assert.Equal(1, crefNodes.Count) Dim info = model.GetSymbolInfo(crefNodes(0)) Assert.NotNull(info.Symbol) Assert.Equal("Sub TestStruct.T(Of T)(p As T, i As TestStruct)", info.Symbol.ToTestDisplayString()) CheckAllNames(model, crefNodes(0), New NameSyntaxInfo("T(Of T)", {"Sub TestStruct.T(Of T)(p As T, i As TestStruct)"}, {}), New NameSyntaxInfo("T", {"T"}, {"T"}), New NameSyntaxInfo("T", {"T"}, {"T"}), New NameSyntaxInfo("Global.TestStruct", {"TestStruct"}, {"TestStruct"}), New NameSyntaxInfo("Global", {"Global"}, {}), New NameSyntaxInfo("TestStruct", {"TestStruct"}, {"TestStruct"})) End Sub <Fact> Private Sub ExtendedCref_GlobalAndQualifiedInName_TypeParamInSignature() Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Public Structure TestStruct ''' <see cref="Global.TestStruct.T(Of T)(T, TestStruct)"/> Public Shared field As Integer Sub T(Of T)(p As T, i as TestStruct) End Sub End Structure ]]> </file> </compilation> Dim xmlDoc = <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="F:TestStruct.field"> <see cref="M:TestStruct.T``1(``0,TestStruct)"/> </member> </members> </doc> ]]> </xml> Dim compilation = CompileCheckDiagnosticsAndXmlDocument(xmlSource, <errors></errors>, xmlDoc) Dim model = compilation.GetSemanticModel(compilation.SyntaxTrees(0)) Dim crefNodes = CrefFinder.FindAllCrefs(compilation.SyntaxTrees(0)) Assert.Equal(1, crefNodes.Count) Dim info = model.GetSymbolInfo(crefNodes(0)) Assert.NotNull(info.Symbol) Assert.Equal("Sub TestStruct.T(Of T)(p As T, i As TestStruct)", info.Symbol.ToTestDisplayString()) CheckAllNames(model, crefNodes(0), New NameSyntaxInfo("Global.TestStruct.T(Of T)", {"Sub TestStruct.T(Of T)(p As T, i As TestStruct)"}, {}), New NameSyntaxInfo("Global.TestStruct", {"TestStruct"}, {"TestStruct"}), New NameSyntaxInfo("Global", {"Global"}, {}), New NameSyntaxInfo("TestStruct", {"TestStruct"}, {"TestStruct"}), New NameSyntaxInfo("T(Of T)", {"Sub TestStruct.T(Of T)(p As T, i As TestStruct)"}, {}), New NameSyntaxInfo("T", {"T"}, {"T"}), New NameSyntaxInfo("T", {"T"}, {"T"}), New NameSyntaxInfo("TestStruct", {"TestStruct"}, {"TestStruct"})) End Sub <Fact> Private Sub ExtendedCref_QualifiedOperatorReference() Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Public Structure TestStruct(Of X) ''' <see cref="Global.TestStruct(Of ZZZ). operator+(integer, TestStruct(Of zzz))"/> Public Shared field As Integer Public Shared Operator +(a As Integer, b As TestStruct(Of X)) As String Return Nothing End Operator End Structure]]> </file> </compilation> Dim xmlDoc = <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="F:TestStruct`1.field"> <see cref="M:TestStruct`1.op_Addition(System.Int32,TestStruct{`0})"/> </member> </members> </doc> ]]> </xml> Dim compilation = CompileCheckDiagnosticsAndXmlDocument(xmlSource, <errors></errors>, xmlDoc) Dim model = compilation.GetSemanticModel(compilation.SyntaxTrees(0)) Dim crefNodes = CrefFinder.FindAllCrefs(compilation.SyntaxTrees(0)) Assert.Equal(1, crefNodes.Count) Dim info = model.GetSymbolInfo(crefNodes(0)) Assert.NotNull(info.Symbol) Assert.Equal("Function TestStruct(Of ZZZ).op_Addition(a As System.Int32, b As TestStruct(Of ZZZ)) As System.String", info.Symbol.ToTestDisplayString()) CheckAllNames(model, crefNodes(0), New NameSyntaxInfo("Global.TestStruct(Of ZZZ). operator+", {"Function TestStruct(Of ZZZ).op_Addition(a As System.Int32, b As TestStruct(Of ZZZ)) As System.String"}, {}), New NameSyntaxInfo("Global.TestStruct(Of ZZZ)", {"TestStruct(Of ZZZ)"}, {"TestStruct(Of ZZZ)"}), New NameSyntaxInfo("Global", {"Global"}, {}), New NameSyntaxInfo("TestStruct(Of ZZZ)", {"TestStruct(Of ZZZ)"}, {"TestStruct(Of ZZZ)"}), New NameSyntaxInfo("ZZZ", {"ZZZ"}, {"ZZZ"}), New NameSyntaxInfo("operator+", {"Function TestStruct(Of ZZZ).op_Addition(a As System.Int32, b As TestStruct(Of ZZZ)) As System.String"}, {}), New NameSyntaxInfo("TestStruct(Of zzz)", {"TestStruct(Of ZZZ)"}, {"TestStruct(Of ZZZ)"}), New NameSyntaxInfo("zzz", {"ZZZ"}, {"ZZZ"})) End Sub <Fact> Private Sub ExtendedCref_OperatorReference() Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Public Class Clazz Public Structure TestStruct ''' <see cref="operator+(integer, Global.Clazz.TestStruct)"/> Public Shared field As Integer Public Shared Operator +(a As Integer, b As TestStruct) As String Return Nothing End Operator End Structure End Class ]]> </file> </compilation> Dim xmlDoc = <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="F:Clazz.TestStruct.field"> <see cref="M:Clazz.TestStruct.op_Addition(System.Int32,Clazz.TestStruct)"/> </member> </members> </doc> ]]> </xml> Dim compilation = CompileCheckDiagnosticsAndXmlDocument(xmlSource, <errors></errors>, xmlDoc) Dim model = compilation.GetSemanticModel(compilation.SyntaxTrees(0)) Dim crefNodes = CrefFinder.FindAllCrefs(compilation.SyntaxTrees(0)) Assert.Equal(1, crefNodes.Count) Dim info = model.GetSymbolInfo(crefNodes(0)) Assert.NotNull(info.Symbol) Assert.Equal("Function Clazz.TestStruct.op_Addition(a As System.Int32, b As Clazz.TestStruct) As System.String", info.Symbol.ToTestDisplayString()) CheckAllNames(model, crefNodes(0), New NameSyntaxInfo("operator+", {"Function Clazz.TestStruct.op_Addition(a As System.Int32, b As Clazz.TestStruct) As System.String"}, {}), New NameSyntaxInfo("Global.Clazz.TestStruct", {"Clazz.TestStruct"}, {"Clazz.TestStruct"}), New NameSyntaxInfo("Global.Clazz", {"Clazz"}, {"Clazz"}), New NameSyntaxInfo("Global", {"Global"}, {}), New NameSyntaxInfo("Clazz", {"Clazz"}, {"Clazz"}), New NameSyntaxInfo("TestStruct", {"Clazz.TestStruct"}, {"Clazz.TestStruct"})) End Sub <Fact> Private Sub ExtendedCref_ReturnType() Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Public Class GenericClazz(Of T) End Class Public Class Clazz(Of X) Public Structure TestStruct ''' <see cref="operator ctype(Integer)"/> ''' <see cref="operator ctype(Integer) As TestStruct"/> ''' <see cref="Global.Clazz(Of A) . TestStruct. operator ctype(Clazz(Of A).TestStruct) As A"/> ''' <see cref="Global.Clazz(Of B) . TestStruct. operator ctype(B)"/> ''' <see cref="operator ctype(TestStruct) As Global.Clazz(Of Integer)"/> ''' <see cref="Clazz(Of C).TestStruct.operator ctype(Clazz(Of C). TestStruct) As GenericClazz(Of C)"/> Public Shared field As Integer Public Shared Narrowing Operator CType(a As Integer) As TestStruct Return Nothing End Operator Public Shared Narrowing Operator CType(a As TestStruct) As X Return Nothing End Operator Public Shared Narrowing Operator CType(a As TestStruct) As GenericClazz(Of X) Return Nothing End Operator Public Shared Narrowing Operator CType(a As X) As TestStruct Return Nothing End Operator Public Shared Narrowing Operator CType(a As TestStruct) As Global.Clazz(Of Integer) Return Nothing End Operator End Structure End Class ]]> </file> </compilation> Dim xmlDoc = <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="F:Clazz`1.TestStruct.field"> <see cref="M:Clazz`1.TestStruct.op_Explicit(System.Int32)~Clazz{`0}.TestStruct"/> <see cref="M:Clazz`1.TestStruct.op_Explicit(System.Int32)~Clazz{`0}.TestStruct"/> <see cref="M:Clazz`1.TestStruct.op_Explicit(Clazz{`0}.TestStruct)~`0"/> <see cref="M:Clazz`1.TestStruct.op_Explicit(`0)~Clazz{`0}.TestStruct"/> <see cref="M:Clazz`1.TestStruct.op_Explicit(Clazz{`0}.TestStruct)~Clazz{System.Int32}"/> <see cref="M:Clazz`1.TestStruct.op_Explicit(Clazz{`0}.TestStruct)~GenericClazz{`0}"/> </member> </members> </doc> ]]> </xml> Dim compilation = CompileCheckDiagnosticsAndXmlDocument(xmlSource, <errors></errors>, xmlDoc) Dim model = compilation.GetSemanticModel(compilation.SyntaxTrees(0)) Dim crefNodes = CrefFinder.FindAllCrefs(compilation.SyntaxTrees(0)) Assert.Equal(6, crefNodes.Count) Dim index As Integer = 0 For Each name In {"Function Clazz(Of X).TestStruct.op_Explicit(a As System.Int32) As Clazz(Of X).TestStruct", "Function Clazz(Of X).TestStruct.op_Explicit(a As System.Int32) As Clazz(Of X).TestStruct", "Function Clazz(Of A).TestStruct.op_Explicit(a As Clazz(Of A).TestStruct) As A", "Function Clazz(Of B).TestStruct.op_Explicit(a As B) As Clazz(Of B).TestStruct", "Function Clazz(Of X).TestStruct.op_Explicit(a As Clazz(Of X).TestStruct) As Clazz(Of System.Int32)", "Function Clazz(Of C).TestStruct.op_Explicit(a As Clazz(Of C).TestStruct) As GenericClazz(Of C)"} Dim info = model.GetSymbolInfo(crefNodes(index)) If name Is Nothing Then Assert.True(info.IsEmpty) Else Assert.NotNull(info.Symbol) Assert.Equal(name, info.Symbol.ToTestDisplayString()) End If index += 1 Next CheckAllNames(model, crefNodes(0), New NameSyntaxInfo("operator ctype", {"Function Clazz(Of X).TestStruct.op_Explicit(a As Clazz(Of X).TestStruct) As Clazz(Of System.Int32)", "Function Clazz(Of X).TestStruct.op_Explicit(a As Clazz(Of X).TestStruct) As GenericClazz(Of X)", "Function Clazz(Of X).TestStruct.op_Explicit(a As Clazz(Of X).TestStruct) As X", "Function Clazz(Of X).TestStruct.op_Explicit(a As System.Int32) As Clazz(Of X).TestStruct", "Function Clazz(Of X).TestStruct.op_Explicit(a As X) As Clazz(Of X).TestStruct"}, {})) CheckAllNames(model, crefNodes(1), New NameSyntaxInfo("operator ctype", {"Function Clazz(Of X).TestStruct.op_Explicit(a As Clazz(Of X).TestStruct) As Clazz(Of System.Int32)", "Function Clazz(Of X).TestStruct.op_Explicit(a As Clazz(Of X).TestStruct) As GenericClazz(Of X)", "Function Clazz(Of X).TestStruct.op_Explicit(a As Clazz(Of X).TestStruct) As X", "Function Clazz(Of X).TestStruct.op_Explicit(a As System.Int32) As Clazz(Of X).TestStruct", "Function Clazz(Of X).TestStruct.op_Explicit(a As X) As Clazz(Of X).TestStruct"}, {}), New NameSyntaxInfo("TestStruct", {"Clazz(Of X).TestStruct"}, {"Clazz(Of X).TestStruct"})) CheckAllNames(model, crefNodes(2), New NameSyntaxInfo("Global.Clazz(Of A) . TestStruct. operator ctype", {"Function Clazz(Of A).TestStruct.op_Explicit(a As Clazz(Of A).TestStruct) As Clazz(Of System.Int32)", "Function Clazz(Of A).TestStruct.op_Explicit(a As Clazz(Of A).TestStruct) As GenericClazz(Of A)", "Function Clazz(Of A).TestStruct.op_Explicit(a As Clazz(Of A).TestStruct) As A", "Function Clazz(Of A).TestStruct.op_Explicit(a As System.Int32) As Clazz(Of A).TestStruct", "Function Clazz(Of A).TestStruct.op_Explicit(a As A) As Clazz(Of A).TestStruct"}, {}), New NameSyntaxInfo("Global.Clazz(Of A) . TestStruct", {"Clazz(Of A).TestStruct"}, {"Clazz(Of A).TestStruct"}), New NameSyntaxInfo("Global.Clazz(Of A)", {"Clazz(Of A)"}, {"Clazz(Of A)"}), New NameSyntaxInfo("Global", {"Global"}, {}), New NameSyntaxInfo("Clazz(Of A)", {"Clazz(Of A)"}, {"Clazz(Of A)"}), New NameSyntaxInfo("A", {"A"}, {"A"}), New NameSyntaxInfo("TestStruct", {"Clazz(Of A).TestStruct"}, {"Clazz(Of A).TestStruct"}), New NameSyntaxInfo("operator ctype", {"Function Clazz(Of A).TestStruct.op_Explicit(a As Clazz(Of A).TestStruct) As Clazz(Of System.Int32)", "Function Clazz(Of A).TestStruct.op_Explicit(a As Clazz(Of A).TestStruct) As GenericClazz(Of A)", "Function Clazz(Of A).TestStruct.op_Explicit(a As Clazz(Of A).TestStruct) As A", "Function Clazz(Of A).TestStruct.op_Explicit(a As System.Int32) As Clazz(Of A).TestStruct", "Function Clazz(Of A).TestStruct.op_Explicit(a As A) As Clazz(Of A).TestStruct"}, {}), New NameSyntaxInfo("Clazz(Of A).TestStruct", {"Clazz(Of A).TestStruct"}, {"Clazz(Of A).TestStruct"}), New NameSyntaxInfo("Clazz(Of A)", {"Clazz(Of A)"}, {"Clazz(Of A)"}), New NameSyntaxInfo("A", {"A"}, {"A"}), New NameSyntaxInfo("TestStruct", {"Clazz(Of A).TestStruct"}, {"Clazz(Of A).TestStruct"}), New NameSyntaxInfo("A", {"A"}, {"A"})) CheckAllNames(model, crefNodes(3), New NameSyntaxInfo("Global.Clazz(Of B) . TestStruct. operator ctype", {"Function Clazz(Of B).TestStruct.op_Explicit(a As Clazz(Of B).TestStruct) As Clazz(Of System.Int32)", "Function Clazz(Of B).TestStruct.op_Explicit(a As Clazz(Of B).TestStruct) As GenericClazz(Of B)", "Function Clazz(Of B).TestStruct.op_Explicit(a As Clazz(Of B).TestStruct) As B", "Function Clazz(Of B).TestStruct.op_Explicit(a As System.Int32) As Clazz(Of B).TestStruct", "Function Clazz(Of B).TestStruct.op_Explicit(a As B) As Clazz(Of B).TestStruct"}, {}), New NameSyntaxInfo("Global.Clazz(Of B) . TestStruct", {"Clazz(Of B).TestStruct"}, {"Clazz(Of B).TestStruct"}), New NameSyntaxInfo("Global.Clazz(Of B)", {"Clazz(Of B)"}, {"Clazz(Of B)"}), New NameSyntaxInfo("Global", {"Global"}, {}), New NameSyntaxInfo("Clazz(Of B)", {"Clazz(Of B)"}, {"Clazz(Of B)"}), New NameSyntaxInfo("B", {"B"}, {"B"}), New NameSyntaxInfo("TestStruct", {"Clazz(Of B).TestStruct"}, {"Clazz(Of B).TestStruct"}), New NameSyntaxInfo("operator ctype", {"Function Clazz(Of B).TestStruct.op_Explicit(a As Clazz(Of B).TestStruct) As Clazz(Of System.Int32)", "Function Clazz(Of B).TestStruct.op_Explicit(a As Clazz(Of B).TestStruct) As GenericClazz(Of B)", "Function Clazz(Of B).TestStruct.op_Explicit(a As Clazz(Of B).TestStruct) As B", "Function Clazz(Of B).TestStruct.op_Explicit(a As System.Int32) As Clazz(Of B).TestStruct", "Function Clazz(Of B).TestStruct.op_Explicit(a As B) As Clazz(Of B).TestStruct"}, {}), New NameSyntaxInfo("B", {"B"}, {"B"})) CheckAllNames(model, crefNodes(4), New NameSyntaxInfo("operator ctype", {"Function Clazz(Of X).TestStruct.op_Explicit(a As Clazz(Of X).TestStruct) As Clazz(Of System.Int32)", "Function Clazz(Of X).TestStruct.op_Explicit(a As Clazz(Of X).TestStruct) As GenericClazz(Of X)", "Function Clazz(Of X).TestStruct.op_Explicit(a As Clazz(Of X).TestStruct) As X", "Function Clazz(Of X).TestStruct.op_Explicit(a As System.Int32) As Clazz(Of X).TestStruct", "Function Clazz(Of X).TestStruct.op_Explicit(a As X) As Clazz(Of X).TestStruct"}, {}), New NameSyntaxInfo("TestStruct", {"Clazz(Of X).TestStruct"}, {"Clazz(Of X).TestStruct"}), New NameSyntaxInfo("Global.Clazz(Of Integer)", {"Clazz(Of System.Int32)"}, {"Clazz(Of System.Int32)"}), New NameSyntaxInfo("Global", {"Global"}, {}), New NameSyntaxInfo("Clazz(Of Integer)", {"Clazz(Of System.Int32)"}, {"Clazz(Of System.Int32)"})) CheckAllNames(model, crefNodes(5), New NameSyntaxInfo("Clazz(Of C).TestStruct.operator ctype", {"Function Clazz(Of C).TestStruct.op_Explicit(a As Clazz(Of C).TestStruct) As Clazz(Of System.Int32)", "Function Clazz(Of C).TestStruct.op_Explicit(a As Clazz(Of C).TestStruct) As GenericClazz(Of C)", "Function Clazz(Of C).TestStruct.op_Explicit(a As Clazz(Of C).TestStruct) As C", "Function Clazz(Of C).TestStruct.op_Explicit(a As System.Int32) As Clazz(Of C).TestStruct", "Function Clazz(Of C).TestStruct.op_Explicit(a As C) As Clazz(Of C).TestStruct"}, {}), New NameSyntaxInfo("Clazz(Of C).TestStruct", {"Clazz(Of C).TestStruct"}, {"Clazz(Of C).TestStruct"}), New NameSyntaxInfo("Clazz(Of C)", {"Clazz(Of C)"}, {"Clazz(Of C)"}), New NameSyntaxInfo("C", {"C"}, {"C"}), New NameSyntaxInfo("TestStruct", {"Clazz(Of C).TestStruct"}, {"Clazz(Of C).TestStruct"}), New NameSyntaxInfo("operator ctype", {"Function Clazz(Of C).TestStruct.op_Explicit(a As Clazz(Of C).TestStruct) As Clazz(Of System.Int32)", "Function Clazz(Of C).TestStruct.op_Explicit(a As Clazz(Of C).TestStruct) As GenericClazz(Of C)", "Function Clazz(Of C).TestStruct.op_Explicit(a As Clazz(Of C).TestStruct) As C", "Function Clazz(Of C).TestStruct.op_Explicit(a As System.Int32) As Clazz(Of C).TestStruct", "Function Clazz(Of C).TestStruct.op_Explicit(a As C) As Clazz(Of C).TestStruct"}, {}), New NameSyntaxInfo("Clazz(Of C). TestStruct", {"Clazz(Of C).TestStruct"}, {"Clazz(Of C).TestStruct"}), New NameSyntaxInfo("Clazz(Of C)", {"Clazz(Of C)"}, {"Clazz(Of C)"}), New NameSyntaxInfo("C", {"C"}, {"C"}), New NameSyntaxInfo("TestStruct", {"Clazz(Of C).TestStruct"}, {"Clazz(Of C).TestStruct"}), New NameSyntaxInfo("GenericClazz(Of C)", {"GenericClazz(Of C)"}, {"GenericClazz(Of C)"}), New NameSyntaxInfo("C", {"C"}, {"C"})) End Sub <Fact> Private Sub ExtendedCref_ColorColor() Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Public Class SomeClass Public Sub SB() End Sub End Class Public Class Clazz Public someClass As SomeClass Public Structure TestStruct ''' <see cref="someclass.sb()"/> ''' <see cref="operator ctype(SomeClass) As TestStruct"/> ''' <see cref="operator ctype(TestStruct) As SomeClass"/> Public Shared field As Integer Public Shared Narrowing Operator CType(a As TestStruct) As SomeClass Return Nothing End Operator Public Shared Narrowing Operator CType(a As SomeClass) As TestStruct Return Nothing End Operator End Structure End Class ]]> </file> </compilation> Dim xmlDoc = <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="F:Clazz.TestStruct.field"> <see cref="M:SomeClass.SB"/> <see cref="M:Clazz.TestStruct.op_Explicit(SomeClass)~Clazz.TestStruct"/> <see cref="M:Clazz.TestStruct.op_Explicit(Clazz.TestStruct)~SomeClass"/> </member> </members> </doc> ]]> </xml> Dim compilation = CompileCheckDiagnosticsAndXmlDocument(xmlSource, <errors></errors>, xmlDoc) Dim model = compilation.GetSemanticModel(compilation.SyntaxTrees(0)) Dim crefNodes = CrefFinder.FindAllCrefs(compilation.SyntaxTrees(0)) Assert.Equal(3, crefNodes.Count) Dim index As Integer = 0 For Each name In {"Sub SomeClass.SB()", "Function Clazz.TestStruct.op_Explicit(a As SomeClass) As Clazz.TestStruct", "Function Clazz.TestStruct.op_Explicit(a As Clazz.TestStruct) As SomeClass"} Dim info = model.GetSymbolInfo(crefNodes(index)) If name Is Nothing Then Assert.True(info.IsEmpty) Else Assert.NotNull(info.Symbol) Assert.Equal(name, info.Symbol.ToTestDisplayString()) End If index += 1 Next CheckAllNames(model, crefNodes(0), New NameSyntaxInfo("someclass.sb", {"Sub SomeClass.SB()"}, {}), New NameSyntaxInfo("someclass", {"SomeClass"}, {"SomeClass"}), New NameSyntaxInfo("sb", {"Sub SomeClass.SB()"}, {})) CheckAllNames(model, crefNodes(1), New NameSyntaxInfo("operator ctype", {"Function Clazz.TestStruct.op_Explicit(a As SomeClass) As Clazz.TestStruct", "Function Clazz.TestStruct.op_Explicit(a As Clazz.TestStruct) As SomeClass"}, {}), New NameSyntaxInfo("SomeClass", {"SomeClass"}, {"SomeClass"}), New NameSyntaxInfo("TestStruct", {"Clazz.TestStruct"}, {"Clazz.TestStruct"})) CheckAllNames(model, crefNodes(2), New NameSyntaxInfo("operator ctype", {"Function Clazz.TestStruct.op_Explicit(a As SomeClass) As Clazz.TestStruct", "Function Clazz.TestStruct.op_Explicit(a As Clazz.TestStruct) As SomeClass"}, {}), New NameSyntaxInfo("TestStruct", {"Clazz.TestStruct"}, {"Clazz.TestStruct"}), New NameSyntaxInfo("SomeClass", {"SomeClass"}, {"SomeClass"})) End Sub <Fact> Private Sub ExtendedCref_ReferencingConversionByMethodName() Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Public Class SomeClass End Class Public Structure TestStruct ''' <see cref="op_Implicit(SomeClass)"/> ''' <see cref="op_Explicit(TestStruct)"/> Public Shared field As Integer Public Shared Narrowing Operator CType(a As TestStruct) As SomeClass Return Nothing End Operator Public Shared Widening Operator CType(a As SomeClass) As TestStruct Return Nothing End Operator End Structure ]]> </file> </compilation> Dim xmlDoc = <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="F:TestStruct.field"> <see cref="M:TestStruct.op_Implicit(SomeClass)~TestStruct"/> <see cref="M:TestStruct.op_Explicit(TestStruct)~SomeClass"/> </member> </members> </doc> ]]> </xml> Dim compilation = CompileCheckDiagnosticsAndXmlDocument(xmlSource, <errors></errors>, xmlDoc) Dim model = compilation.GetSemanticModel(compilation.SyntaxTrees(0)) Dim crefNodes = CrefFinder.FindAllCrefs(compilation.SyntaxTrees(0)) Assert.Equal(2, crefNodes.Count) Dim index As Integer = 0 For Each name In {"Function TestStruct.op_Implicit(a As SomeClass) As TestStruct", "Function TestStruct.op_Explicit(a As TestStruct) As SomeClass"} Dim info = model.GetSymbolInfo(crefNodes(index)) If name Is Nothing Then Assert.True(info.IsEmpty) Else Assert.NotNull(info.Symbol) Assert.Equal(name, info.Symbol.ToTestDisplayString()) End If index += 1 Next End Sub <Fact> Private Sub ExtendedCref_ReferencingConversionByMethodName_ReturnTypeOverloading() Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Public Class SomeClass End Class Public Structure TestStruct ''' <see cref="op_Implicit(TestStruct) As SomeClass"/> ''' <see cref="op_Implicit(TestStruct) As String"/> Public Shared field As Integer Public Shared Widening Operator CType(a As TestStruct) As SomeClass Return Nothing End Operator Public Shared Widening Operator CType(a As TestStruct) As String Return Nothing End Operator End Structure ]]> </file> </compilation> Dim xmlDoc = <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="F:TestStruct.field"> <see cref="M:TestStruct.op_Implicit(TestStruct)~SomeClass"/> <see cref="M:TestStruct.op_Implicit(TestStruct)~System.String"/> </member> </members> </doc> ]]> </xml> Dim compilation = CompileCheckDiagnosticsAndXmlDocument(xmlSource, <errors></errors>, xmlDoc) Dim model = compilation.GetSemanticModel(compilation.SyntaxTrees(0)) Dim crefNodes = CrefFinder.FindAllCrefs(compilation.SyntaxTrees(0)) Assert.Equal(2, crefNodes.Count) Dim index As Integer = 0 For Each name In {"Function TestStruct.op_Implicit(a As TestStruct) As SomeClass", "Function TestStruct.op_Implicit(a As TestStruct) As System.String"} Dim info = model.GetSymbolInfo(crefNodes(index)) If name Is Nothing Then Assert.True(info.IsEmpty) Else Assert.NotNull(info.Symbol) Assert.Equal(name, info.Symbol.ToTestDisplayString()) End If index += 1 Next End Sub <Fact> Private Sub ExtendedCref_MemberAndTypeParamConflict() Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Public Structure T(Of X) Class T(Of Y) Sub T(Of T)(p As T, i as TestStruct) End Sub End Class End Structure Public Structure TestStruct ''' <see cref="Global.T(Of T).T(Of T).T(Of T)(T, TestStruct)"/> Public Shared field As Integer End Structure ]]> </file> </compilation> Dim xmlDoc = <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="F:TestStruct.field"> <see cref="M:T`1.T`1.T``1(``0,TestStruct)"/> </member> </members> </doc> ]]> </xml> Dim compilation = CompileCheckDiagnosticsAndXmlDocument(xmlSource, <errors></errors>, xmlDoc) Dim model = compilation.GetSemanticModel(compilation.SyntaxTrees(0)) Dim crefNodes = CrefFinder.FindAllCrefs(compilation.SyntaxTrees(0)) Assert.Equal(1, crefNodes.Count) Dim info = model.GetSymbolInfo(crefNodes(0)) Assert.NotNull(info.Symbol) Assert.Equal("Sub T(Of T).T(Of T).T(Of T)(p As T, i As TestStruct)", info.Symbol.ToTestDisplayString()) CheckAllNames(model, crefNodes(0), New NameSyntaxInfo("Global.T(Of T).T(Of T).T(Of T)", {"Sub T(Of T).T(Of T).T(Of T)(p As T, i As TestStruct)"}, {}), New NameSyntaxInfo("Global.T(Of T).T(Of T)", {"T(Of T).T(Of T)"}, {"T(Of T).T(Of T)"}), New NameSyntaxInfo("Global.T(Of T)", {"T(Of T)"}, {"T(Of T)"}), New NameSyntaxInfo("Global", {"Global"}, {}), New NameSyntaxInfo("T(Of T)", {"T(Of T)"}, {"T(Of T)"}), New NameSyntaxInfo("T", {"T"}, {"T"}), New NameSyntaxInfo("T(Of T)", {"T(Of T).T(Of T)"}, {"T(Of T).T(Of T)"}), New NameSyntaxInfo("T", {"T"}, {"T"}), New NameSyntaxInfo("T(Of T)", {"Sub T(Of T).T(Of T).T(Of T)(p As T, i As TestStruct)"}, {}), New NameSyntaxInfo("T", {"T"}, {"T"}), New NameSyntaxInfo("T", {"T"}, {"T"}), New NameSyntaxInfo("TestStruct", {"TestStruct"}, {"TestStruct"})) End Sub Private Structure NameSyntaxInfo Public ReadOnly Syntax As String Public ReadOnly Symbols As String() Public ReadOnly Types As String() Public Sub New(syntax As String, symbols As String(), types As String()) Me.Syntax = syntax Me.Symbols = symbols Me.Types = types End Sub End Structure Private Sub CheckAllNames(model As SemanticModel, cref As CrefReferenceSyntax, ParamArray expected As NameSyntaxInfo()) Dim names = NameSyntaxFinder.FindNames(cref) Assert.Equal(expected.Length, names.Count) For i = 0 To names.Count - 1 Dim e = expected(i) Dim sym = names(i) Assert.Equal(e.Syntax, sym.ToString().Trim()) Dim actual = model.GetSymbolInfo(sym) If e.Symbols.Length = 0 Then Assert.True(actual.IsEmpty) ElseIf e.Symbols.Length = 1 Then Assert.NotNull(actual.Symbol) Assert.Equal(e.Symbols(0), actual.Symbol.ToTestDisplayString) Else Assert.Equal(CandidateReason.Ambiguous, actual.CandidateReason) AssertStringArraysEqual(e.Symbols, (From s In actual.CandidateSymbols Select s.ToTestDisplayString()).ToArray) End If Dim typeInfo = model.GetTypeInfo(sym) If e.Types.Length = 0 Then Assert.Null(typeInfo.Type) ElseIf e.Types.Length = 1 Then Assert.NotNull(typeInfo.Type) Assert.Equal(e.Types(0), typeInfo.Type.ToTestDisplayString()) Else Assert.Null(typeInfo.Type) End If Next End Sub <Fact> Private Sub ExtendedCref_UnaryOperatorsAndConversion() Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Public Class Clazz Public Shared Operator Like(a As Clazz, b As Integer) As Clazz Return Nothing End Operator Public Shared Operator And(a As Clazz, b As Integer) As Clazz Return Nothing End Operator Public Shared Operator Or(a As Clazz, b As Integer) As Clazz Return Nothing End Operator Public Shared Operator Xor(a As Clazz, b As Integer) As Clazz Return Nothing End Operator Public Shared Operator Mod(a As Clazz, b As Integer) As Clazz Return Nothing End Operator Public Shared Operator Not(a As Clazz) As Boolean Return Nothing End Operator Public Shared Operator IsTrue(a As Clazz) As Boolean Return Nothing End Operator Public Shared Operator IsFalse(a As Clazz) As Boolean Return Nothing End Operator Public Shared Narrowing Operator CType(a As Clazz) As String Return Nothing End Operator Public Shared Widening Operator CType(a As Clazz) As Integer? Return Nothing End Operator Public Shared Widening Operator CType(a As Integer?) As Clazz Return Nothing End Operator Public Shared Narrowing Operator CType(a As Integer) As Clazz Return Nothing End Operator ''' <see cref="operator Like (Clazz, Int32)"/> ''' <see cref="Clazz. operator And (Clazz, Int32)"/> ''' <see cref="operator Or (Clazz, Int32)"/> ''' <see cref=" Clazz. operator Xor (Clazz, Int32)"/> ''' <see cref="operator Mod (Clazz, Int32)"/> ''' <see cref="Global . Clazz. operator Not (Clazz)"/> ''' <see cref=" operator istrue (Clazz)"/> ''' <see cref=" Clazz. operator isfalse (Clazz)"/> ''' <see cref=" operator ctype (Clazz) as string"/> ''' <see cref=" Clazz. operator ctype (Clazz) as integer?"/> ''' <see cref=" operator ctype (integer?) as clazz"/> ''' <see cref=" operator ctype (integer) as clazz"/> ''' <see cref=" Global . Clazz. operator ctype (integer) as clazz"/> Public Shared field As Integer End Class ]]> </file> </compilation> Dim xmlDoc = <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="F:Clazz.field"> <see cref="M:Clazz.op_Like(Clazz,System.Int32)"/> <see cref="M:Clazz.op_BitwiseAnd(Clazz,System.Int32)"/> <see cref="M:Clazz.op_BitwiseOr(Clazz,System.Int32)"/> <see cref="M:Clazz.op_ExclusiveOr(Clazz,System.Int32)"/> <see cref="M:Clazz.op_Modulus(Clazz,System.Int32)"/> <see cref="M:Clazz.op_OnesComplement(Clazz)"/> <see cref="M:Clazz.op_True(Clazz)"/> <see cref="M:Clazz.op_False(Clazz)"/> <see cref="M:Clazz.op_Explicit(Clazz)~System.String"/> <see cref="M:Clazz.op_Implicit(Clazz)~System.Nullable{System.Int32}"/> <see cref="M:Clazz.op_Implicit(System.Nullable{System.Int32})~Clazz"/> <see cref="M:Clazz.op_Explicit(System.Int32)~Clazz"/> <see cref="M:Clazz.op_Explicit(System.Int32)~Clazz"/> </member> </members> </doc> ]]> </xml> Dim compilation = CompileCheckDiagnosticsAndXmlDocument(xmlSource, <errors></errors>, xmlDoc) Dim model = compilation.GetSemanticModel(compilation.SyntaxTrees(0)) Dim crefNodes = CrefFinder.FindAllCrefs(compilation.SyntaxTrees(0)) Assert.Equal(13, crefNodes.Count) Dim index As Integer = 0 For Each name In {"Function Clazz.op_Like(a As Clazz, b As System.Int32) As Clazz", "Function Clazz.op_BitwiseAnd(a As Clazz, b As System.Int32) As Clazz", "Function Clazz.op_BitwiseOr(a As Clazz, b As System.Int32) As Clazz", "Function Clazz.op_ExclusiveOr(a As Clazz, b As System.Int32) As Clazz", "Function Clazz.op_Modulus(a As Clazz, b As System.Int32) As Clazz", "Function Clazz.op_OnesComplement(a As Clazz) As System.Boolean", "Function Clazz.op_True(a As Clazz) As System.Boolean", "Function Clazz.op_False(a As Clazz) As System.Boolean", "Function Clazz.op_Explicit(a As Clazz) As System.String", "Function Clazz.op_Implicit(a As Clazz) As System.Nullable(Of System.Int32)", "Function Clazz.op_Implicit(a As System.Nullable(Of System.Int32)) As Clazz", "Function Clazz.op_Explicit(a As System.Int32) As Clazz", "Function Clazz.op_Explicit(a As System.Int32) As Clazz"} Dim info = model.GetSymbolInfo(crefNodes(index)) Assert.NotNull(info.Symbol) Assert.Equal(name, info.Symbol.ToTestDisplayString()) index += 1 Next End Sub <Fact> Private Sub ExtendedCref_StandaloneSimpleName() Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Public Class Clazz Public Structure STR End Structure Public Sub New() End Sub Public Sub New(s As Integer) End Sub Public Sub New(s As Clazz) End Sub Public Sub [New](Of T)(s As Integer) End Sub Public Sub [New](Of T)(s As Clazz) End Sub Public Sub [New](Of T)(s As T) End Sub Public Sub S0(s As Integer) End Sub Public Sub S0(s As String) End Sub Public Sub S0(s As STR) End Sub ''' <see cref="New(Clazz)"/> ''' <see cref="New(Int32)"/> ''' <see cref="New()"/> ''' <see cref="New(STR)"/> ''' <see cref="[New](Clazz)"/> ''' <see cref="[New](Of T)(Clazz)"/> ''' <see cref="[New](Of T)(T)"/> ''' <see cref="[New](Of T, W)(T)"/> ''' <see cref="S0(Of T)(T)"/> ''' <see cref="S0(STR)"/> Public Shared field As Integer End Class ]]> </file> </compilation> Dim xmlDoc = <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="F:Clazz.field"> <see cref="M:Clazz.#ctor(Clazz)"/> <see cref="M:Clazz.#ctor(System.Int32)"/> <see cref="M:Clazz.#ctor"/> <see cref="!:New(STR)"/> <see cref="!:[New](Clazz)"/> <see cref="M:Clazz.New``1(Clazz)"/> <see cref="M:Clazz.New``1(``0)"/> <see cref="!:[New](Of T, W)(T)"/> <see cref="!:S0(Of T)(T)"/> <see cref="M:Clazz.S0(Clazz.STR)"/> </member> </members> </doc> ]]> </xml> Dim compilation = CompileCheckDiagnosticsAndXmlDocument(xmlSource, <errors> <![CDATA[ BC42309: XML comment has a tag with a 'cref' attribute 'New(STR)' that could not be resolved. ''' <see cref="New(STR)"/> ~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute '[New](Clazz)' that could not be resolved. ''' <see cref="[New](Clazz)"/> ~~~~~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute '[New](Of T, W)(T)' that could not be resolved. ''' <see cref="[New](Of T, W)(T)"/> ~~~~~~~~~~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'S0(Of T)(T)' that could not be resolved. ''' <see cref="S0(Of T)(T)"/> ~~~~~~~~~~~~~~~~~~ ]]> </errors>, xmlDoc) Dim model = compilation.GetSemanticModel(compilation.SyntaxTrees(0)) Dim crefNodes = CrefFinder.FindAllCrefs(compilation.SyntaxTrees(0)) Assert.Equal(10, crefNodes.Count) Dim index As Integer = 0 For Each name In {"Sub Clazz..ctor(s As Clazz)", "Sub Clazz..ctor(s As System.Int32)", "Sub Clazz..ctor()", Nothing, Nothing, "Sub Clazz.[New](Of T)(s As Clazz)", "Sub Clazz.[New](Of T)(s As T)", Nothing, Nothing, "Sub Clazz.S0(s As Clazz.STR)"} Dim info = model.GetSymbolInfo(crefNodes(index)) If name Is Nothing Then Assert.True(info.IsEmpty) Else Assert.NotNull(info.Symbol) Assert.Equal(name, info.Symbol.ToTestDisplayString()) End If index += 1 Next End Sub <Fact> Private Sub ExtendedCref_QualifiedName_A() Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Public Class Clazz Public Structure STR End Structure Public Sub New() End Sub Public Sub New(s As Integer) End Sub Public Sub New(s As Clazz) End Sub Public Sub [New](Of T)(s As Integer) End Sub Public Sub [New](Of T)(s As Clazz) End Sub Public Sub [New](Of T)(s As T) End Sub Public Sub S0(s As Integer) End Sub Public Sub S0(s As String) End Sub Public Sub S0(s As STR) End Sub End Class Public Structure TestStruct ''' <see cref="Clazz.New(Clazz)"/> ''' <see cref="Global.Clazz.New(Int32)"/> ''' <see cref="Clazz.New()"/> ''' <see cref="Clazz.New(Clazz.STR)"/> ''' <see cref="Clazz.[New](Clazz)"/> ''' <see cref="Clazz.[New](Of T)(Clazz)"/> ''' <see cref="Global.Clazz.[New](Of T)(T)"/> ''' <see cref="Clazz.[New](Of T, W)(T)"/> ''' <see cref="Clazz.S0(Of T)(T)"/> ''' <see cref="Global.Clazz.S0(Clazz.STR)"/> Public Shared field As Integer End Structure ]]> </file> </compilation> Dim xmlDoc = <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="F:TestStruct.field"> <see cref="M:Clazz.#ctor(Clazz)"/> <see cref="M:Clazz.#ctor(System.Int32)"/> <see cref="M:Clazz.#ctor"/> <see cref="!:Clazz.New(Clazz.STR)"/> <see cref="!:Clazz.[New](Clazz)"/> <see cref="M:Clazz.New``1(Clazz)"/> <see cref="M:Clazz.New``1(``0)"/> <see cref="!:Clazz.[New](Of T, W)(T)"/> <see cref="!:Clazz.S0(Of T)(T)"/> <see cref="M:Clazz.S0(Clazz.STR)"/> </member> </members> </doc> ]]> </xml> Dim compilation = CompileCheckDiagnosticsAndXmlDocument(xmlSource, <errors> <![CDATA[ BC42309: XML comment has a tag with a 'cref' attribute 'Clazz.New(Clazz.STR)' that could not be resolved. ''' <see cref="Clazz.New(Clazz.STR)"/> ~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'Clazz.[New](Clazz)' that could not be resolved. ''' <see cref="Clazz.[New](Clazz)"/> ~~~~~~~~~~~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'Clazz.[New](Of T, W)(T)' that could not be resolved. ''' <see cref="Clazz.[New](Of T, W)(T)"/> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'Clazz.S0(Of T)(T)' that could not be resolved. ''' <see cref="Clazz.S0(Of T)(T)"/> ~~~~~~~~~~~~~~~~~~~~~~~~ ]]> </errors>, xmlDoc) Dim model = compilation.GetSemanticModel(compilation.SyntaxTrees(0)) Dim crefNodes = CrefFinder.FindAllCrefs(compilation.SyntaxTrees(0)) Assert.Equal(10, crefNodes.Count) Dim index As Integer = 0 For Each name In {"Sub Clazz..ctor(s As Clazz)", "Sub Clazz..ctor(s As System.Int32)", "Sub Clazz..ctor()", Nothing, Nothing, "Sub Clazz.[New](Of T)(s As Clazz)", "Sub Clazz.[New](Of T)(s As T)", Nothing, Nothing, "Sub Clazz.S0(s As Clazz.STR)"} Dim info = model.GetSymbolInfo(crefNodes(index)) If name Is Nothing Then Assert.True(info.IsEmpty) Else Assert.NotNull(info.Symbol) Assert.Equal(name, info.Symbol.ToTestDisplayString()) End If index += 1 Next End Sub <Fact> Private Sub ExtendedCref_QualifiedName_B() Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Public Structure Struct End Structure Public Class Clazz(Of A, B) Public Sub New() End Sub Public Sub New(s As Integer) End Sub Public Sub New(s As Clazz(Of Integer, Struct)) End Sub Public Sub New(s As Clazz(Of A, B)) End Sub Public Sub [New](Of T)(s As Integer) End Sub Public Sub [New](Of T)(s As Clazz(Of T, T)) End Sub Public Sub [New](Of T)(s As Clazz(Of T, B)) End Sub Public Sub [New](Of T)(s As T) End Sub Public Sub S0(s As Integer) End Sub Public Sub S0(s As String) End Sub Public Sub S0(Of X, Y)(a As A, b As B, c As X, d As Y) End Sub End Class Public Structure TestStruct ''' <see cref="Clazz.New(Integer)"/> ''' <see cref="Global.Clazz(Of X, Y).New(Int32)"/> ''' <see cref="Global.Clazz(Of X, Y).New(Clazz(Of X, Y))"/> ''' <see cref="Global.Clazz(Of X, Y).New(Clazz(Of Int32, Y))"/> ''' <see cref="Global.Clazz(Of X, Y).New(Clazz(Of Int32, Struct))"/> ''' <see cref="Clazz(Of X, Y).New()"/> ''' <see cref="Clazz(Of [Integer], Y).New([Integer])"/> ''' <see cref="Clazz(Of X, Y).[New](Clazz)"/> ''' <see cref="Clazz(Of X(Of D), Y).[New](Of T)(Int32)"/> ''' <see cref="Clazz(Of X, Y).[New](Of X)(X)"/> ''' <see cref="Clazz(Of X, Y).[New](Of X)(Y)"/> ''' <see cref="Clazz(Of X, Y).[New](Of T)(T)"/> ''' <see cref="Clazz(Of X, Y).[New](Of X)(Clazz(Of X, X))"/> ''' <see cref="Clazz(Of X, Y).[New](Of X)(Clazz(Of X, Y))"/> ''' <see cref="Clazz(Of X, Y).S0(Of T, U)(X, Y, T, U)"/> ''' <see cref="Global.Clazz(Of X, Y).S0(Of X, Y)(X, Y, X, Y)"/> Public Shared field As Integer End Structure ]]> </file> </compilation> Dim xmlDoc = <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="F:TestStruct.field"> <see cref="!:Clazz.New(Integer)"/> <see cref="M:Clazz`2.#ctor(System.Int32)"/> <see cref="M:Clazz`2.#ctor(Clazz{`0,`1})"/> <see cref="!:Global.Clazz(Of X, Y).New(Clazz(Of Int32, Y))"/> <see cref="M:Clazz`2.#ctor(Clazz{System.Int32,Struct})"/> <see cref="M:Clazz`2.#ctor"/> <see cref="!:Clazz(Of [Integer], Y).New([Integer])"/> <see cref="!:Clazz(Of X, Y).[New](Clazz)"/> <see cref="!:Clazz(Of X(Of D), Y).[New](Of T)(Int32)"/> <see cref="M:Clazz`2.New``1(``0)"/> <see cref="!:Clazz(Of X, Y).[New](Of X)(Y)"/> <see cref="M:Clazz`2.New``1(``0)"/> <see cref="M:Clazz`2.New``1(Clazz{``0,``0})"/> <see cref="M:Clazz`2.New``1(Clazz{``0,`1})"/> <see cref="M:Clazz`2.S0``2(`0,`1,``0,``1)"/> <see cref="!:Global.Clazz(Of X, Y).S0(Of X, Y)(X, Y, X, Y)"/> </member> </members> </doc> ]]> </xml> Dim compilation = CompileCheckDiagnosticsAndXmlDocument(xmlSource, <errors> <![CDATA[ BC42309: XML comment has a tag with a 'cref' attribute 'Clazz.New(Integer)' that could not be resolved. ''' <see cref="Clazz.New(Integer)"/> ~~~~~~~~~~~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'Global.Clazz(Of X, Y).New(Clazz(Of Int32, Y))' that could not be resolved. ''' <see cref="Global.Clazz(Of X, Y).New(Clazz(Of Int32, Y))"/> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'Clazz(Of [Integer], Y).New([Integer])' that could not be resolved. ''' <see cref="Clazz(Of [Integer], Y).New([Integer])"/> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'Clazz(Of X, Y).[New](Clazz)' that could not be resolved. ''' <see cref="Clazz(Of X, Y).[New](Clazz)"/> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'Clazz(Of X(Of D), Y).[New](Of T)(Int32)' that could not be resolved. ''' <see cref="Clazz(Of X(Of D), Y).[New](Of T)(Int32)"/> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'Clazz(Of X, Y).[New](Of X)(Y)' that could not be resolved. ''' <see cref="Clazz(Of X, Y).[New](Of X)(Y)"/> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'Global.Clazz(Of X, Y).S0(Of X, Y)(X, Y, X, Y)' that could not be resolved. ''' <see cref="Global.Clazz(Of X, Y).S0(Of X, Y)(X, Y, X, Y)"/> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]> </errors>, xmlDoc) Dim model = compilation.GetSemanticModel(compilation.SyntaxTrees(0)) Dim crefNodes = CrefFinder.FindAllCrefs(compilation.SyntaxTrees(0)) Assert.Equal(16, crefNodes.Count) Dim index As Integer = 0 For Each name In {Nothing, "Sub Clazz(Of X, Y)..ctor(s As System.Int32)", "Sub Clazz(Of X, Y)..ctor(s As Clazz(Of X, Y))", Nothing, "Sub Clazz(Of X, Y)..ctor(s As Clazz(Of System.Int32, Struct))", "Sub Clazz(Of X, Y)..ctor()", Nothing, Nothing, Nothing, "Sub Clazz(Of X, Y).[New](Of X)(s As X)", Nothing, "Sub Clazz(Of X, Y).[New](Of T)(s As T)", "Sub Clazz(Of X, Y).[New](Of X)(s As Clazz(Of X, X))", "Sub Clazz(Of X, Y).[New](Of X)(s As Clazz(Of X, Y))", "Sub Clazz(Of X, Y).S0(Of T, U)(a As X, b As Y, c As T, d As U)", Nothing} Dim info = model.GetSymbolInfo(crefNodes(index)) If name Is Nothing Then Assert.True(info.IsEmpty) Else Assert.NotNull(info.Symbol) Assert.Equal(name, info.Symbol.ToTestDisplayString()) End If index += 1 Next End Sub <Fact> Public Sub Include_AttrMissing_XMLMissingFileOrPathAttribute1() Dim xmlText = <root><target>Included</target></root> Dim xmlFile = Temp.CreateFile(extension:=".xml").WriteAllText(xmlText.Value.ToString) Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Imports System.Collections.Generic ''' <summary> ''' <include file='**FILE**' /> ''' <include path='//target' /> ''' <include/> ''' </summary> Class C End Class ]]> </file> </compilation> CompileCheckDiagnosticsAndXmlDocument(FormatSourceXml(xmlSource, xmlFile), <error> <![CDATA[ BC42310: XML comment tag 'include' must have a 'path' attribute. XML comment will be ignored. ''' <include file='**FILE**' /> ~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42310: XML comment tag 'include' must have a 'file' attribute. XML comment will be ignored. ''' <include path='//target' /> ~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42310: XML comment tag 'include' must have a 'file' attribute. XML comment will be ignored. ''' <include/> ~~~~~~~~~~ BC42310: XML comment tag 'include' must have a 'path' attribute. XML comment will be ignored. ''' <include/> ~~~~~~~~~~ ]]> </error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:C"> <summary> <!--warning BC42310: XML comment tag 'include' must have a 'path' attribute. XML comment will be ignored.--> <!--warning BC42310: XML comment tag 'include' must have a 'file' attribute. XML comment will be ignored.--> <!--warning BC42310: XML comment tag 'include' must have a 'file' attribute. XML comment will be ignored. warning BC42310: XML comment tag 'include' must have a 'path' attribute. XML comment will be ignored.--> </summary> </member> </members> </doc> ]]> </xml>, ensureEnglishUICulture:=True) End Sub <Fact> Public Sub ExtendedCref_BinaryOperator() ExtendedCref_BinaryOperatorCore(" &", "op_Concatenate", <errors></errors>) ExtendedCref_BinaryOperatorCore("+", "op_Addition", <errors> <![CDATA[ BC42309: XML comment has a tag with a 'cref' attribute 'Operator+(Clazz, String)' that could not be resolved. ''' <see cref="Operator+(Clazz, String)"/> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'Operator+(Clazz)' that could not be resolved. ''' <see cref="Operator+(Clazz)"/> ~~~~~~~~~~~~~~~~~~~~~~~ ]]> </errors>) ExtendedCref_BinaryOperatorCore("-", "op_Subtraction", <errors> <![CDATA[ BC42309: XML comment has a tag with a 'cref' attribute 'Operator-(Clazz, String)' that could not be resolved. ''' <see cref="Operator-(Clazz, String)"/> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'Operator-(Clazz)' that could not be resolved. ''' <see cref="Operator-(Clazz)"/> ~~~~~~~~~~~~~~~~~~~~~~~ ]]> </errors>) ExtendedCref_BinaryOperatorCore("*", "op_Multiply", <errors> <![CDATA[ BC42309: XML comment has a tag with a 'cref' attribute 'Operator*(Clazz, String)' that could not be resolved. ''' <see cref="Operator*(Clazz, String)"/> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'Operator*(Clazz)' that could not be resolved. ''' <see cref="Operator*(Clazz)"/> ~~~~~~~~~~~~~~~~~~~~~~~ ]]> </errors>) ExtendedCref_BinaryOperatorCore("/", "op_Division", <errors> <![CDATA[ BC42309: XML comment has a tag with a 'cref' attribute 'Operator/(Clazz, String)' that could not be resolved. ''' <see cref="Operator/(Clazz, String)"/> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'Operator/(Clazz)' that could not be resolved. ''' <see cref="Operator/(Clazz)"/> ~~~~~~~~~~~~~~~~~~~~~~~ ]]> </errors>) ExtendedCref_BinaryOperatorCore("\", "op_IntegerDivision", <errors> <![CDATA[ BC42309: XML comment has a tag with a 'cref' attribute 'Operator\(Clazz, String)' that could not be resolved. ''' <see cref="Operator\(Clazz, String)"/> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'Operator\(Clazz)' that could not be resolved. ''' <see cref="Operator\(Clazz)"/> ~~~~~~~~~~~~~~~~~~~~~~~ ]]> </errors>) ExtendedCref_BinaryOperatorCore("^", "op_Exponent", <errors> <![CDATA[ BC42309: XML comment has a tag with a 'cref' attribute 'Operator^(Clazz, String)' that could not be resolved. ''' <see cref="Operator^(Clazz, String)"/> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'Operator^(Clazz)' that could not be resolved. ''' <see cref="Operator^(Clazz)"/> ~~~~~~~~~~~~~~~~~~~~~~~ ]]> </errors>) ExtendedCref_BinaryOperatorCore("<<", "op_LeftShift", <errors></errors>) ExtendedCref_BinaryOperatorCore(">>", "op_RightShift", <errors></errors>) ExtendedCref_BinaryOperatorCore("=", "op_Equality", <errors> <![CDATA[ BC33033: Matching '<>' operator is required for 'Public Shared Operator =(a As Clazz, b As Integer) As Clazz'. Public Shared Operator =(a As Clazz, b As Integer) As Clazz ~ BC33033: Matching '<>' operator is required for 'Public Shared Operator =(a As Clazz, b As Integer?) As Clazz'. Public Shared Operator =(a As Clazz, b As Integer?) As Clazz ~ BC42309: XML comment has a tag with a 'cref' attribute 'Operator=(Clazz, String)' that could not be resolved. ''' <see cref="Operator=(Clazz, String)"/> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'Operator=(Clazz)' that could not be resolved. ''' <see cref="Operator=(Clazz)"/> ~~~~~~~~~~~~~~~~~~~~~~~ ]]> </errors>) ExtendedCref_BinaryOperatorCore("<>", "op_Inequality", <errors> <![CDATA[ BC33033: Matching '=' operator is required for 'Public Shared Operator <>(a As Clazz, b As Integer) As Clazz'. Public Shared Operator <>(a As Clazz, b As Integer) As Clazz ~~ BC33033: Matching '=' operator is required for 'Public Shared Operator <>(a As Clazz, b As Integer?) As Clazz'. Public Shared Operator <>(a As Clazz, b As Integer?) As Clazz ~~ ]]> </errors>) ExtendedCref_BinaryOperatorCore("<", "op_LessThan", <errors> <![CDATA[ BC33033: Matching '>' operator is required for 'Public Shared Operator <(a As Clazz, b As Integer) As Clazz'. Public Shared Operator <(a As Clazz, b As Integer) As Clazz ~ BC33033: Matching '>' operator is required for 'Public Shared Operator <(a As Clazz, b As Integer?) As Clazz'. Public Shared Operator <(a As Clazz, b As Integer?) As Clazz ~ ]]> </errors>) ExtendedCref_BinaryOperatorCore(">", "op_GreaterThan", <errors> <![CDATA[ BC33033: Matching '<' operator is required for 'Public Shared Operator >(a As Clazz, b As Integer) As Clazz'. Public Shared Operator >(a As Clazz, b As Integer) As Clazz ~ BC33033: Matching '<' operator is required for 'Public Shared Operator >(a As Clazz, b As Integer?) As Clazz'. Public Shared Operator >(a As Clazz, b As Integer?) As Clazz ~ ]]> </errors>) ExtendedCref_BinaryOperatorCore("<=", "op_LessThanOrEqual", <errors> <![CDATA[ BC33033: Matching '>=' operator is required for 'Public Shared Operator <=(a As Clazz, b As Integer) As Clazz'. Public Shared Operator <=(a As Clazz, b As Integer) As Clazz ~~ BC33033: Matching '>=' operator is required for 'Public Shared Operator <=(a As Clazz, b As Integer?) As Clazz'. Public Shared Operator <=(a As Clazz, b As Integer?) As Clazz ~~ ]]> </errors>) ExtendedCref_BinaryOperatorCore(">=", "op_GreaterThanOrEqual", <errors> <![CDATA[ BC33033: Matching '<=' operator is required for 'Public Shared Operator >=(a As Clazz, b As Integer) As Clazz'. Public Shared Operator >=(a As Clazz, b As Integer) As Clazz ~~ BC33033: Matching '<=' operator is required for 'Public Shared Operator >=(a As Clazz, b As Integer?) As Clazz'. Public Shared Operator >=(a As Clazz, b As Integer?) As Clazz ~~ ]]> </errors>) End Sub Private Sub ExtendedCref_BinaryOperatorCore(op As String, opName As String, errors As XElement) Dim invalidChars = op.Contains("<") OrElse op.Contains(">") OrElse op.Contains("&") Dim xmlSource = If(Not invalidChars, <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Public Class Clazz Public Shared Operator {0}(a As Clazz, b As Integer) As Clazz Return Nothing End Operator Public Shared Operator {0}(a As Clazz, b As Integer?) As Clazz Return Nothing End Operator ''' <see cref="{1}(Clazz, Integer) As Clazz"/> ''' <see cref="Operator{0}(Clazz, Integer)"/> ''' <see cref="Operator{0}(Clazz, String)"/> ''' <see cref="Operator{0}(Clazz, Int32?)"/> ''' <see cref="Operator{0}(Clazz)"/> ''' <see cref="Clazz.Operator{0}(Clazz, Integer)"/> ''' <see cref="Global.Clazz.Operator{0}(Clazz, Integer?)"/> Public Shared field As Integer End Class ]]> </file> </compilation>, <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Public Class Clazz Public Shared Operator {0}(a As Clazz, b As Integer) As Clazz Return Nothing End Operator Public Shared Operator {0}(a As Clazz, b As Integer?) As Clazz Return Nothing End Operator ''' <see cref="{1}(Clazz, Integer) As Clazz"/> ''' <see cref="Operator{0}(Clazz, Integer)"/> ''' <see cref="Operator{0}(Clazz, Int32?)"/> ''' <see cref="Clazz.Operator{0}(Clazz, Integer)"/> ''' <see cref="Global.Clazz.Operator{0}(Clazz, Integer?)"/> Public Shared field As Integer End Class ]]> </file> </compilation>) Dim xmlDoc = If(Not invalidChars, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="F:Clazz.field"> <see cref="M:Clazz.{0}(Clazz,System.Int32)"/> <see cref="M:Clazz.{0}(Clazz,System.Int32)"/> <see cref="!:Operator{1}(Clazz, String)"/> <see cref="M:Clazz.{0}(Clazz,System.Nullable{{System.Int32}})"/> <see cref="!:Operator{1}(Clazz)"/> <see cref="M:Clazz.{0}(Clazz,System.Int32)"/> <see cref="M:Clazz.{0}(Clazz,System.Nullable{{System.Int32}})"/> </member> </members> </doc> ]]> </xml>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="F:Clazz.field"> <see cref="M:Clazz.{0}(Clazz,System.Int32)"/> <see cref="M:Clazz.{0}(Clazz,System.Int32)"/> <see cref="M:Clazz.{0}(Clazz,System.Nullable{{System.Int32}})"/> <see cref="M:Clazz.{0}(Clazz,System.Int32)"/> <see cref="M:Clazz.{0}(Clazz,System.Nullable{{System.Int32}})"/> </member> </members> </doc> ]]> </xml>) Dim compilation = CompileCheckDiagnosticsAndXmlDocument( FormatSourceXml(xmlSource, op, opName), FormatXmlSimple(errors, op, If(op.Length = 1, "~", "~~")), FormatXmlSimple(xmlDoc, opName, op)) Dim crefNode = CrefFinder.FindCref(compilation.SyntaxTrees(0)) Dim model = compilation.GetSemanticModel(compilation.SyntaxTrees(0)) Assert.NotNull(crefNode) Dim info = model.GetSymbolInfo(crefNode) Assert.NotNull(info.Symbol) Assert.Equal(String.Format("Function Clazz.{0}(a As Clazz, b As System.Int32) As Clazz", opName), info.Symbol.ToTestDisplayString()) End Sub <Fact> Public Sub ExtendedCrefParsingTest() ParseExtendedCref("Int32.ToString", forceNoErrors:=True) ParseExtendedCref("Int32.ToString()", forceNoErrors:=False) ParseExtendedCref("Int32.ToString(String, Integer)", forceNoErrors:=False) ParseExtendedCref("Int32.ToString(ByVal String, ByRef Integer)", forceNoErrors:=False) ParseExtendedCref("Int32.ToString(ByVal ByRef String, Integer) As Integer", checkErrors:= <error> <![CDATA[ BC42309: XML comment has a tag with a 'cref' attribute 'Int32.ToString(ByVal ByRef String, Integer) As Integer' that could not be resolved. ''' <see cref="Int32.ToString(ByVal ByRef String, Integer) As Integer"/> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]> </error>) ParseExtendedCref("Int32.ToString(String, Integer) As Integer", checkErrors:= <error> <![CDATA[ BC42309: XML comment has a tag with a 'cref' attribute 'Int32.ToString(String, Integer) As Integer' that could not be resolved. ''' <see cref="Int32.ToString(String, Integer) As Integer"/> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]> </error>) ParseExtendedCref("Operator IsTrue(String)", forceNoErrors:=False) ParseExtendedCref("Operator IsFalse(String)", forceNoErrors:=False) ParseExtendedCref("Operator Not(String)", forceNoErrors:=False) ParseExtendedCref("Operator+(String, Integer)", forceNoErrors:=False) ParseExtendedCref("Operator -(String, Integer)", forceNoErrors:=False) ParseExtendedCref("Operator*(String, Integer)", forceNoErrors:=False) ParseExtendedCref("Operator /(String, Integer)", forceNoErrors:=False) ParseExtendedCref("Operator^(String, Integer)", forceNoErrors:=False) ParseExtendedCref("Operator \(String, Integer)", forceNoErrors:=False) ParseExtendedCref("Operator&(String, Integer)", forceNoErrors:=False) ParseExtendedCref("Operator<<(String, Integer)", forceNoErrors:=False) ParseExtendedCref("Operator >> (String, Integer)", forceNoErrors:=False) ParseExtendedCref("Operator Mod(String, Integer)", forceNoErrors:=False) ParseExtendedCref("Operator Or(String, Integer)", forceNoErrors:=False) ParseExtendedCref("Operator Xor(String, Integer)", forceNoErrors:=False) ParseExtendedCref("Operator And(String, Integer)", forceNoErrors:=False) ParseExtendedCref("Operator Like(String, Integer)", forceNoErrors:=False) ParseExtendedCref("Operator =(String, Integer)", forceNoErrors:=False) ParseExtendedCref("Operator <>(String, Integer)", forceNoErrors:=False) ParseExtendedCref("Operator <(String, Integer)", forceNoErrors:=False) ParseExtendedCref("Operator <=(String, Integer)", forceNoErrors:=False) ParseExtendedCref("Operator >(String, Integer)", forceNoErrors:=False) ParseExtendedCref("Operator >=(String, Integer)", forceNoErrors:=False) ParseExtendedCref("Operator \(String, Integer) As Integer", checkErrors:= <error> <![CDATA[ BC42309: XML comment has a tag with a 'cref' attribute 'Operator \(String, Integer) As Integer' that could not be resolved. ''' <see cref="Operator \(String, Integer) As Integer"/> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]> </error>) ParseExtendedCref("Operator Or(String, Integer).Name", checkErrors:= <error> <![CDATA[ BC42309: XML comment has a tag with a 'cref' attribute 'Operator Or(String, Integer).Name' that could not be resolved. ''' <see cref="Operator Or(String, Integer).Name"/> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]> </error>, overrideCrefText:="Operator Or(String, Integer)") ParseExtendedCref("Clazz.Operator >=(String, Integer)", forceNoErrors:=False) ParseExtendedCref("Clazz.Operator ctype(String)", forceNoErrors:=False) ParseExtendedCref("Clazz.Operator ctype(String) as Integer", forceNoErrors:=False) ParseExtendedCref("New", forceNoErrors:=False) ParseExtendedCref("[new]", forceNoErrors:=False) ParseExtendedCref("New()", forceNoErrors:=False) ParseExtendedCref("[new]()", forceNoErrors:=False) ParseExtendedCref("Clazz.New", forceNoErrors:=False) ParseExtendedCref("Clazz.[new]", forceNoErrors:=False) ParseExtendedCref("Clazz.New()", forceNoErrors:=False) ParseExtendedCref("Clazz.[new]()", forceNoErrors:=False) ParseExtendedCref("Clazz.[new]() As Integer", forceNoErrors:=False) ParseExtendedCref("String.ToString", overrideCrefText:="String", forceNoErrors:=True) ParseExtendedCref("String.ToString()", overrideCrefText:="String", forceNoErrors:=True) ParseExtendedCref("String.ToString(String, Integer)", overrideCrefText:="String", forceNoErrors:=True) ParseExtendedCref("sYSTEM.String") ParseExtendedCref("sYSTEM.String.", checkErrors:= <error> <![CDATA[ BC42309: XML comment has a tag with a 'cref' attribute 'sYSTEM.String.' that could not be resolved. ''' <see cref="sYSTEM.String."/> ~~~~~~~~~~~~~~~~~~~~~ ]]> </error>) ParseExtendedCref("Global.sYSTEM.String") ParseExtendedCref("Global", checkErrors:= <error> <![CDATA[ BC42309: XML comment has a tag with a 'cref' attribute 'Global' that could not be resolved. ''' <see cref="Global"/> ~~~~~~~~~~~~~ ]]> </error>) End Sub Private Sub ParseExtendedCref(cref As String, Optional checkErrors As XElement = Nothing, Optional overrideCrefText As String = Nothing, Optional forceNoErrors As Boolean = False) Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System ''' <see cref="{0}"/> Module Program End Module ]]> </file> </compilation> Dim compilation = CompileCheckDiagnosticsAndXmlDocument(FormatSourceXml(xmlSource, cref), If(forceNoErrors, <errors></errors>, checkErrors)) Dim crefNode = CrefFinder.FindCref(compilation.SyntaxTrees(0)) Assert.NotNull(crefNode) Assert.Equal(If(overrideCrefText, cref.Trim).Trim, crefNode.ToString()) End Sub <Fact> Private Sub GetAliasInfo_Namespace() Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Imports aNamespace = System.Collections.Generic ''' <see cref="aNamespace"/> Public Class Clazz End Class ]]> </file> </compilation> Dim xmlDoc = <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:Clazz"> <see cref="N:System.Collections.Generic"/> </member> </members> </doc> ]]> </xml> Dim compilation = CompileCheckDiagnosticsAndXmlDocument(xmlSource, <errors></errors>, xmlDoc) Dim model = compilation.GetSemanticModel(compilation.SyntaxTrees(0)) Dim crefNode = CrefFinder.FindCref(compilation.SyntaxTrees(0)) Assert.NotNull(crefNode) Dim info = model.GetSymbolInfo(crefNode) Assert.NotNull(info.Symbol) Assert.Equal("System.Collections.Generic", info.Symbol.ToTestDisplayString()) CheckAllAliases(model, crefNode, New AliasInfo("aNamespace", "System.Collections.Generic")) End Sub <WorkItem(757110, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/757110")> <Fact> Public Sub NoAssemblyElementForNetModule() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="EmptyCref"> <file name="a.vb"> <![CDATA[ Imports System ''' <summary> ''' Test ''' </summary> Class E End Class ]]> </file> </compilation>, TestOptions.ReleaseModule) CheckXmlDocument(comp, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <members> <member name="T:E"> <summary> Test </summary> </member> </members> </doc> ]]> </xml>) End Sub <Fact> Private Sub GetAliasInfo_Type() Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Imports aType = System.Collections.Generic.List(Of Integer) ''' <see cref="aType"/> Public Class Clazz End Class ]]> </file> </compilation> Dim xmlDoc = <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:Clazz"> <see cref="T:System.Collections.Generic.List`1"/> </member> </members> </doc> ]]> </xml> Dim compilation = CompileCheckDiagnosticsAndXmlDocument(xmlSource, <errors></errors>, xmlDoc) Dim model = compilation.GetSemanticModel(compilation.SyntaxTrees(0)) Dim crefNode = CrefFinder.FindCref(compilation.SyntaxTrees(0)) Assert.NotNull(crefNode) Dim info = model.GetSymbolInfo(crefNode) Assert.NotNull(info.Symbol) Assert.Equal("System.Collections.Generic.List(Of System.Int32)", info.Symbol.ToTestDisplayString()) CheckAllAliases(model, crefNode, New AliasInfo("aType", "System.Collections.Generic.List(Of Integer)")) End Sub <Fact> Private Sub GetAliasInfo_NamespaceAndType() Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Imports aNamespace = System.Collections.Generic ''' <see cref="aNamespace.List(Of T)"/> Public Class Clazz End Class ]]> </file> </compilation> Dim xmlDoc = <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:Clazz"> <see cref="T:System.Collections.Generic.List`1"/> </member> </members> </doc> ]]> </xml> Dim compilation = CompileCheckDiagnosticsAndXmlDocument(xmlSource, <errors></errors>, xmlDoc) Dim model = compilation.GetSemanticModel(compilation.SyntaxTrees(0)) Dim crefNode = CrefFinder.FindCref(compilation.SyntaxTrees(0)) Assert.NotNull(crefNode) Dim info = model.GetSymbolInfo(crefNode) Assert.NotNull(info.Symbol) Assert.Equal("System.Collections.Generic.List(Of T)", info.Symbol.ToTestDisplayString()) CheckAllAliases(model, crefNode, New AliasInfo("aNamespace", "System.Collections.Generic"), New AliasInfo("T", Nothing)) End Sub <Fact> Private Sub GetAliasInfo_TypeAndMethodWithSignature() Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Imports aType = System.Collections.Generic.List(Of Integer) ''' <see cref="aType.ToString()"/> Public Class Clazz End Class ]]> </file> </compilation> Dim xmlDoc = <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:Clazz"> <see cref="M:System.Object.ToString"/> </member> </members> </doc> ]]> </xml> Dim compilation = CompileCheckDiagnosticsAndXmlDocument(xmlSource, <errors></errors>, xmlDoc) Dim model = compilation.GetSemanticModel(compilation.SyntaxTrees(0)) Dim crefNode = CrefFinder.FindCref(compilation.SyntaxTrees(0)) Assert.NotNull(crefNode) Dim info = model.GetSymbolInfo(crefNode) Assert.NotNull(info.Symbol) Assert.Equal("Function System.Object.ToString() As System.String", info.Symbol.ToTestDisplayString()) CheckAllAliases(model, crefNode, New AliasInfo("aType", "System.Collections.Generic.List(Of Integer)"), New AliasInfo("ToString", Nothing)) End Sub <Fact> Private Sub GetAliasInfo_TypeAndMethodCompat() Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Imports aType = System.Collections.Generic.List(Of Integer) ''' <see cref="aType.ToString"/> Public Class Clazz End Class ]]> </file> </compilation> Dim xmlDoc = <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:Clazz"> <see cref="M:System.Object.ToString"/> </member> </members> </doc> ]]> </xml> Dim compilation = CompileCheckDiagnosticsAndXmlDocument(xmlSource, <errors></errors>, xmlDoc) Dim model = compilation.GetSemanticModel(compilation.SyntaxTrees(0)) Dim crefNode = CrefFinder.FindCref(compilation.SyntaxTrees(0)) Assert.NotNull(crefNode) Dim info = model.GetSymbolInfo(crefNode) Assert.NotNull(info.Symbol) Assert.Equal("Function System.Object.ToString() As System.String", info.Symbol.ToTestDisplayString()) CheckAllAliases(model, crefNode, New AliasInfo("aType", "System.Collections.Generic.List(Of Integer)"), New AliasInfo("ToString", Nothing)) End Sub <WorkItem(568006, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/568006")> <Fact> Public Sub Inaccessible1() Dim source = <compilation> <file name="test.vb"><![CDATA[ ''' <summary> ''' See <see cref="C.M"/>. ''' </summary> Class A End Class Class C Private Sub M() End Sub End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, parseOptions:=s_optionsDiagnoseDocComments) ' Compat fix: match dev11 with inaccessible lookup compilation.AssertNoDiagnostics() End Sub <WorkItem(568006, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/568006")> <Fact> Public Sub Inaccessible2() Dim source = <compilation> <file name="test.vb"><![CDATA[ ''' <summary> ''' See <see cref="C.Inner.M"/>. ''' </summary> Class A End Class Class C Private Class Inner Private Sub M() End Sub End Class End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, parseOptions:=s_optionsDiagnoseDocComments) ' Compat fix: match dev11 with inaccessible lookup compilation.AssertNoDiagnostics() End Sub <WorkItem(568006, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/568006")> <Fact> Public Sub Inaccessible3() Dim lib1Source = <compilation name="A"> <file name="a.vb"> Friend Class C End Class </file> </compilation> Dim lib2Source = <compilation name="B"> <file name="b.vb"> Public Class C End Class </file> </compilation> Dim source = <compilation> <file name="test.vb"><![CDATA[ ''' <summary> ''' See <see cref="C"/>. ''' </summary> Public Class Test End Class ]]> </file> </compilation> Dim lib1Ref = CreateCompilationWithMscorlib40(lib1Source).EmitToImageReference() Dim lib2Ref = CreateCompilationWithMscorlib40(lib2Source).EmitToImageReference() Dim compilation = CreateCompilationWithMscorlib40AndReferences(source, {lib1Ref, lib2Ref}, parseOptions:=s_optionsDiagnoseDocComments) Dim tree = compilation.SyntaxTrees.Single() Dim model = compilation.GetSemanticModel(tree) Dim crefSyntax = tree.GetRoot().DescendantNodes(descendIntoTrivia:=True).OfType(Of CrefReferenceSyntax).Single() ' Break: In dev11 the accessible symbol is preferred. We produce an ambiguity Dim symbolInfo = model.GetSymbolInfo(crefSyntax) Dim symbols = symbolInfo.CandidateSymbols Assert.Equal(CandidateReason.Ambiguous, symbolInfo.CandidateReason) Assert.Equal(2, symbols.Length) Assert.Equal("A", symbols(0).ContainingAssembly.Name) Assert.Equal("B", symbols(1).ContainingAssembly.Name) End Sub <WorkItem(568006, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/568006")> <WorkItem(709199, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/709199")> <Fact> Public Sub ProtectedInstanceBaseMember() Dim source = <compilation> <file name="test.vb"><![CDATA[ Class Base Protected F As Integer End Class ''' Accessible: <see cref="Base.F"/> Class Derived : Inherits Base End Class ''' Inaccessible: <see cref="Base.F"/> Class Other End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, parseOptions:=s_optionsDiagnoseDocComments) compilation.AssertNoDiagnostics() Dim tree = compilation.SyntaxTrees.Single() Dim model = compilation.GetSemanticModel(tree) Dim crefSyntax = tree.GetRoot().DescendantNodes(descendIntoTrivia:=True).OfType(Of CrefReferenceSyntax).First() Dim expectedSymbol = compilation.GlobalNamespace.GetMember(Of NamedTypeSymbol)("Base").GetMember(Of FieldSymbol)("F") Dim actualSymbol = model.GetSymbolInfo(crefSyntax).Symbol Assert.Equal(expectedSymbol, actualSymbol) End Sub <WorkItem(568006, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/568006")> <WorkItem(709199, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/709199")> <Fact> Public Sub ProtectedSharedBaseMember() Dim source = <compilation> <file name="test.vb"><![CDATA[ Class Base Protected Shared F As Integer End Class ''' Accessible: <see cref="Base.F"/> Class Derived : Inherits Base End Class ''' Inaccessible: <see cref="Base.F"/> Class Other End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, parseOptions:=s_optionsDiagnoseDocComments) compilation.AssertNoDiagnostics() Dim tree = compilation.SyntaxTrees.Single() Dim model = compilation.GetSemanticModel(tree) Dim crefSyntax = tree.GetRoot().DescendantNodes(descendIntoTrivia:=True).OfType(Of CrefReferenceSyntax).First() Dim expectedSymbol = compilation.GlobalNamespace.GetMember(Of NamedTypeSymbol)("Base").GetMember(Of FieldSymbol)("F") Dim actualSymbol = model.GetSymbolInfo(crefSyntax).Symbol Assert.Equal(expectedSymbol, actualSymbol) End Sub <WorkItem(768624, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768624")> <Fact> Public Sub CrefsOnDelegate() Dim source = <compilation> <file name="test.vb"><![CDATA[ ''' <see cref="T"/> ''' <see cref="p"/> ''' <see cref="Invoke"/> ''' <see cref="ToString"/> Delegate Sub D(Of T)(p As T) ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, parseOptions:=s_optionsDiagnoseDocComments) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC42309: XML comment has a tag with a 'cref' attribute 'T' that could not be resolved. ''' <see cref="T"/> ~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'p' that could not be resolved. ''' <see cref="p"/> ~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'Invoke' that could not be resolved. ''' <see cref="Invoke"/> ~~~~~~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'ToString' that could not be resolved. ''' <see cref="ToString"/> ~~~~~~~~~~~~~~~ ]]></errors>) End Sub <WorkItem(768624, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768624")> <Fact> Public Sub TypeParametersOfAssociatedSymbol() Dim source = <compilation> <file name="test.vb"><![CDATA[ ''' <see cref='T'/> Class C(Of T) ''' <see cref='U'/> Sub M(Of U)() End Sub End Class ''' <see cref='V'/> Delegate Sub D(Of V)() ]]> </file> </compilation> ' NOTE: Unlike C#, VB allows crefs to type parameters. Dim compilation = CreateCompilationWithMscorlib40(source, parseOptions:=s_optionsDiagnoseDocComments) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC42375: XML comment has a tag with a 'cref' attribute 'T' that bound to a type parameter. Use the <typeparamref> tag instead. ''' <see cref='T'/> ~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'U' that could not be resolved. ''' <see cref='U'/> ~~~~~~~~ BC42309: XML comment has a tag with a 'cref' attribute 'V' that could not be resolved. ''' <see cref='V'/> ~~~~~~~~ ]]></errors>) Dim tree = compilation.SyntaxTrees.Single() Dim model = compilation.GetSemanticModel(tree) Dim crefSyntaxes = tree.GetRoot().DescendantNodes(descendIntoTrivia:=True).OfType(Of CrefReferenceSyntax).ToArray() Dim [class] = compilation.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C") Dim method = [class].GetMember(Of MethodSymbol)("M") Dim [delegate] = compilation.GlobalNamespace.GetMember(Of NamedTypeSymbol)("D") Dim info0 As SymbolInfo = model.GetSymbolInfo(crefSyntaxes(0)) Assert.Null(info0.Symbol) ' As in dev11. Assert.Equal([class].TypeParameters.Single(), info0.CandidateSymbols.Single()) Assert.Equal(CandidateReason.NotReferencable, info0.CandidateReason) Assert.True(model.GetSymbolInfo(crefSyntaxes(1)).IsEmpty) Assert.True(model.GetSymbolInfo(crefSyntaxes(2)).IsEmpty) End Sub <WorkItem(768624, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768624")> <Fact> Public Sub MembersOfAssociatedSymbol() Dim source = <compilation> <file name="test.vb"><![CDATA[ ''' <see cref='F'/> Class C Private F As Integer End Class ''' <see cref='F'/> Structure S Private F As Integer End Structure ''' <see cref='P'/> Interface I Property P As Integer End Interface ''' <see cref='F'/> Module M Private F As Integer End Module ''' <see cref='F'/> Enum E F End Enum ]]> </file> </compilation> ' None of these work in dev11. Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, parseOptions:=s_optionsDiagnoseDocComments) compilation.AssertNoDiagnostics() Dim tree = compilation.SyntaxTrees.Single() Dim model = compilation.GetSemanticModel(tree) Dim crefSyntaxes = tree.GetRoot().DescendantNodes(descendIntoTrivia:=True).OfType(Of CrefReferenceSyntax).ToArray() Assert.Equal("C.F As System.Int32", model.GetSymbolInfo(crefSyntaxes(0)).Symbol.ToTestDisplayString()) Assert.Equal("S.F As System.Int32", model.GetSymbolInfo(crefSyntaxes(1)).Symbol.ToTestDisplayString()) Assert.Equal("Property I.P As System.Int32", model.GetSymbolInfo(crefSyntaxes(2)).Symbol.ToTestDisplayString()) Assert.Equal("M.F As System.Int32", model.GetSymbolInfo(crefSyntaxes(3)).Symbol.ToTestDisplayString()) Assert.Equal("E.F", model.GetSymbolInfo(crefSyntaxes(4)).Symbol.ToTestDisplayString()) End Sub <WorkItem(768624, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768624")> <Fact> Public Sub InnerVersusOuter() Dim source = <compilation> <file name="test.vb"><![CDATA[ Class Outer Private F As Integer ''' <see cref='F'/> Class Inner Private F As Integer End Class End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, parseOptions:=s_optionsDiagnoseDocComments) compilation.AssertNoDiagnostics() Dim tree = compilation.SyntaxTrees.Single() Dim model = compilation.GetSemanticModel(tree) Dim crefSyntax = tree.GetRoot().DescendantNodes(descendIntoTrivia:=True).OfType(Of CrefReferenceSyntax).Single() ' BREAK: In dev11, it refers to Outer.F. Assert.Equal("Outer.Inner.F As System.Int32", model.GetSymbolInfo(crefSyntax).Symbol.ToTestDisplayString()) End Sub <WorkItem(531505, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531505")> <Fact> Private Sub Pia() Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ ''' <see cref='FooStruct'/> ''' <see cref='FooStruct.NET'/> Public Class C End Class ]]> </file> </compilation> Dim xmlDoc = <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:C"> <see cref='T:FooStruct'/> <see cref='F:FooStruct.NET'/> </member> </members> </doc> ]]> </xml> Dim reference1 = TestReferences.SymbolsTests.NoPia.GeneralPia.WithEmbedInteropTypes(False) Dim reference2 = TestReferences.SymbolsTests.NoPia.GeneralPia.WithEmbedInteropTypes(True) Dim comp1 = CompileCheckDiagnosticsAndXmlDocument(xmlSource, <errors></errors>, xmlDoc, additionalRefs:={reference1}) Dim comp2 = CompileCheckDiagnosticsAndXmlDocument(xmlSource, <errors></errors>, xmlDoc, additionalRefs:={reference2}) Dim validator As Action(Of ModuleSymbol) = Sub(m As ModuleSymbol) DirectCast(m, PEModuleSymbol).Module.PretendThereArentNoPiaLocalTypes() ' No reference added. AssertEx.None(m.GetReferencedAssemblies(), Function(id) id.Name.Contains("GeneralPia")) ' No type embedded. Assert.Equal(0, m.GlobalNamespace.GetMembers("FooStruct").Length) End Sub CompileAndVerify(comp1, symbolValidator:=validator) CompileAndVerify(comp2, symbolValidator:=validator) End Sub <WorkItem(790978, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/790978")> <Fact> Public Sub SingleSymbol() Dim source = <compilation> <file name="a.vb"> <![CDATA[ ''' <summary> ''' summary information ''' </summary> ''' <remarks>nothing</remarks> Public Class C End Class ]]> </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(source, parseOptions:=s_optionsDiagnoseDocComments) comp.VerifyDiagnostics() Dim expectedXmlText = <![CDATA[ <member name="T:C"> <summary> summary information </summary> <remarks>nothing</remarks> </member> ]]>.Value.Replace(vbLf, Environment.NewLine).Trim Dim sourceSymbol = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C") Assert.Equal(expectedXmlText, sourceSymbol.GetDocumentationCommentXml()) Dim metadataRef = comp.EmitToImageReference() Dim comp2 = CreateEmptyCompilationWithReferences(<source/>, {metadataRef}) Dim metadataSymbol = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C") Assert.Equal(expectedXmlText, metadataSymbol.GetDocumentationCommentXml()) End Sub <Fact, WorkItem(908893, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908893")> Private Sub GenericTypeWithinGenericType() Dim xmlSource = <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Imports System Public Class ClazzA(Of A) ''' <see cref="Test"/> Public Class ClazzB(Of B) Public Sub Test(x as ClazzB(Of B)) End Sub End Class End Class ]]> </file> </compilation> Dim xmlDoc = <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> AssemblyName </name> </assembly> <members> <member name="T:ClazzA`1.ClazzB`1"> <see cref="M:ClazzA`1.ClazzB`1.Test(ClazzA{`0}.ClazzB{`1})"/> </member> </members> </doc> ]]> </xml> Dim compilation = CompileCheckDiagnosticsAndXmlDocument(xmlSource, <errors> </errors>, xmlDoc) End Sub #Region "Helpers" Private Structure AliasInfo Public ReadOnly Name As String Public ReadOnly Target As String Public Sub New(name As String, target As String) Me.Name = name Me.Target = target End Sub End Structure Private Sub CheckAllAliases(model As SemanticModel, cref As CrefReferenceSyntax, ParamArray expected As AliasInfo()) Dim names = SyntaxNodeFinder.FindNodes(Of IdentifierNameSyntax)(cref, SyntaxKind.IdentifierName) Assert.Equal(expected.Length, names.Count) For i = 0 To names.Count - 1 Dim e = expected(i) Dim sym = names(i) Assert.Equal(e.Name, sym.ToString().Trim()) Dim actual = model.GetAliasInfo(sym) If e.Target Is Nothing Then Assert.Null(actual) Else Assert.Equal(e.Target, actual.Target.ToDisplayString) End If Next End Sub Private Class CrefFinder Public Shared Function FindCref(tree As SyntaxTree) As CrefReferenceSyntax Dim crefs = SyntaxNodeFinder.FindNodes(Of CrefReferenceSyntax)(tree.GetRoot(), SyntaxKind.CrefReference) Return If(crefs.Count > 0, crefs(0), Nothing) End Function Public Shared Function FindAllCrefs(tree As SyntaxTree) As List(Of CrefReferenceSyntax) Return SyntaxNodeFinder.FindNodes(Of CrefReferenceSyntax)(tree.GetRoot(), SyntaxKind.CrefReference) End Function End Class Private Shared Function StringReplace(obj As Object, what As String, [with] As String) As Object Dim str = TryCast(obj, String) Return If(str Is Nothing, obj, str.Replace(what, [with])) End Function Private Shared Function AsXmlCommentText(file As TempFile) As String Return TestHelpers.AsXmlCommentText(file.ToString()) End Function Private Function FormatSourceXml(xml As XElement, ParamArray obj() As Object) As XElement For Each file In xml.<file> file.Value = String.Format(file.Value, obj) Next Return xml End Function Private Function FormatXmlSimple(xml As XElement, ParamArray obj() As Object) As XElement xml.Value = String.Format(xml.Value, obj) Return xml End Function Private Shared Function FilterOfSymbolKindOnly(symbols As ImmutableArray(Of ISymbol), ParamArray kinds() As SymbolKind) As ImmutableArray(Of ISymbol) Dim filter As New HashSet(Of SymbolKind)(kinds) Return (From s In symbols Where filter.Contains(s.Kind) Select s).AsImmutable() End Function Private Shared Sub AssertLookupResult(actual As ImmutableArray(Of ISymbol), ParamArray expected() As String) AssertStringArraysEqual(expected, (From s In actual Select s.ToTestDisplayString()).ToArray) End Sub Private Function CheckSymbolInfoOnly(model As SemanticModel, syntax As ExpressionSyntax, ParamArray expected() As String) As ImmutableArray(Of ISymbol) EnsureSymbolInfoOnCrefReference(model, syntax) Dim actual = model.GetSymbolInfo(syntax) If expected.Length = 0 Then Assert.True(actual.IsEmpty) ElseIf expected.Length = 1 Then Assert.NotNull(actual.Symbol) Assert.Equal(expected(0), actual.Symbol.ToTestDisplayString) Else Assert.Equal(CandidateReason.Ambiguous, actual.CandidateReason) AssertStringArraysEqual(expected, (From s In actual.CandidateSymbols Select s.ToTestDisplayString()).ToArray) End If Dim typeInfo = model.GetTypeInfo(syntax) If actual.Symbol IsNot Nothing AndAlso actual.Symbol.Kind = SymbolKind.TypeParameter Then ' Works everywhere since we want it to work in name attributes. Assert.Equal(actual.Symbol, typeInfo.Type) Else Assert.Null(typeInfo.Type) End If Return actual.GetAllSymbols() End Function Private Function GetEnclosingCrefReference(syntax As ExpressionSyntax) As CrefReferenceSyntax Dim node As VisualBasicSyntaxNode = syntax While node IsNot Nothing AndAlso node.Kind <> SyntaxKind.CrefReference node = node.Parent End While Return DirectCast(node, CrefReferenceSyntax) End Function Private Sub EnsureSymbolInfoOnCrefReference(model As SemanticModel, syntax As ExpressionSyntax) Dim cref = GetEnclosingCrefReference(syntax) If cref Is Nothing Then Return End If Debug.Assert(cref.Signature IsNot Nothing OrElse cref.AsClause Is Nothing) If cref.Signature IsNot Nothing Then Return End If Dim fromName = model.GetSymbolInfo(cref.Name) Dim fromCref = model.GetSymbolInfo(cref) Assert.Equal(fromCref.CandidateReason, fromName.CandidateReason) AssertStringArraysEqual((From s In fromName.GetAllSymbols() Select s.ToTestDisplayString()).ToArray, (From s In fromCref.GetAllSymbols() Select s.ToTestDisplayString()).ToArray) End Sub Private Function CheckTypeParameterCrefSymbolInfoAndTypeInfo(model As SemanticModel, syntax As ExpressionSyntax, Optional expected As String = Nothing) As ImmutableArray(Of Symbol) EnsureSymbolInfoOnCrefReference(model, syntax) Dim actual = model.GetSymbolInfo(syntax) Dim typeInfo = model.GetTypeInfo(syntax) If expected Is Nothing Then Assert.True(actual.IsEmpty) Assert.Null(typeInfo.Type) Return ImmutableArray.Create(Of Symbol)() Else Assert.Equal(CandidateReason.NotReferencable, actual.CandidateReason) Dim symbol = actual.CandidateSymbols.Single() Assert.NotNull(symbol) Assert.Equal(expected, symbol.ToTestDisplayString) Assert.NotNull(typeInfo.Type) Assert.Equal(typeInfo.Type, symbol) Return ImmutableArray.Create(DirectCast(symbol, Symbol)) End If End Function Private Function CheckSymbolInfoAndTypeInfo(model As SemanticModel, syntax As ExpressionSyntax, ParamArray expected() As String) As ImmutableArray(Of Symbol) EnsureSymbolInfoOnCrefReference(model, syntax) Dim actual = model.GetSymbolInfo(syntax) Dim typeInfo = model.GetTypeInfo(syntax) If expected.Length = 0 Then Assert.True(actual.IsEmpty) Assert.Null(typeInfo.Type) Return ImmutableArray.Create(Of Symbol)() ElseIf expected.Length = 1 Then Assert.NotNull(actual.Symbol) Assert.Equal(expected(0), actual.Symbol.ToTestDisplayString) Assert.NotNull(typeInfo.Type) Assert.Equal(typeInfo.Type, actual.Symbol) Return ImmutableArray.Create(Of Symbol)(DirectCast(actual.Symbol, Symbol)) Else Assert.Equal(CandidateReason.Ambiguous, actual.CandidateReason) AssertStringArraysEqual(expected, (From s In actual.CandidateSymbols Select s.ToTestDisplayString()).ToArray) Assert.Null(typeInfo.Type) Return actual.CandidateSymbols.Cast(Of Symbol).ToImmutableArray() End If End Function Private Shared Sub AssertStringArraysEqual(a() As String, b() As String) Assert.NotNull(a) Assert.NotNull(b) Assert.Equal(StringArraysToSortedString(a), StringArraysToSortedString(b)) End Sub Private Shared Function StringArraysToSortedString(a() As String) As String Dim builder As New StringBuilder Array.Sort(a) For Each s In a builder.AppendLine(s) Next Return builder.ToString() End Function Private Sub TestSymbolAndTypeInfoForType(model As SemanticModel, syntax As TypeSyntax, expected As ISymbol) EnsureSymbolInfoOnCrefReference(model, syntax) Dim expSymInfo = model.GetSymbolInfo(syntax) Assert.NotNull(expSymInfo.Symbol) Assert.Same(expected, expSymInfo.Symbol.OriginalDefinition) Dim expTypeInfo = model.GetTypeInfo(syntax) Assert.Equal(expected, expTypeInfo.Type.OriginalDefinition) Dim conversion = model.GetConversion(syntax) Assert.Equal(ConversionKind.Identity, conversion.Kind) End Sub Private Shared Function FindNodesOfTypeFromText(Of TNode As VisualBasicSyntaxNode)(tree As SyntaxTree, textToFind As String) As TNode() Dim text As String = tree.GetText().ToString() Dim list As New List(Of TNode) Dim position As Integer = text.IndexOf(textToFind, StringComparison.Ordinal) While position >= 0 Dim token As SyntaxToken = tree.GetRoot().FindToken(position, True) If token.ValueText = textToFind Then Dim node = TryCast(token.Parent, TNode) If node IsNot Nothing Then list.Add(node) End If End If position = text.IndexOf(textToFind, position + 1, StringComparison.Ordinal) End While Return list.ToArray() End Function Private Shared Function CompileCheckDiagnosticsAndXmlDocument( sources As XElement, errors As XElement, Optional expectedDocXml As XElement = Nothing, Optional withDiagnostics As Boolean = True, Optional stringMapper As Func(Of Object, Object) = Nothing, Optional additionalRefs As MetadataReference() = Nothing, Optional ensureEnglishUICulture As Boolean = False ) As VisualBasicCompilation Dim parseOptions As VisualBasicParseOptions = VisualBasicParseOptions.Default.WithDocumentationMode( If(withDiagnostics, DocumentationMode.Diagnose, DocumentationMode.Parse)) Dim compilation = CreateCompilation(sources, additionalRefs, TestOptions.ReleaseDll.WithXmlReferenceResolver(XmlFileResolver.Default), parseOptions) If errors IsNot Nothing Then Dim diagnostics As Diagnostic() Dim saveUICulture As Globalization.CultureInfo = Nothing If ensureEnglishUICulture Then Dim preferred = Roslyn.Test.Utilities.EnsureEnglishUICulture.PreferredOrNull If preferred Is Nothing Then ensureEnglishUICulture = False Else saveUICulture = Threading.Thread.CurrentThread.CurrentUICulture Threading.Thread.CurrentThread.CurrentUICulture = preferred End If End If Try diagnostics = compilation.GetDiagnostics(CompilationStage.Compile).ToArray() Finally If ensureEnglishUICulture Then Threading.Thread.CurrentThread.CurrentUICulture = saveUICulture End If End Try CompilationUtils.AssertTheseDiagnostics(diagnostics.AsImmutable(), errors) End If If expectedDocXml IsNot Nothing Then CheckXmlDocument(compilation, expectedDocXml, stringMapper, ensureEnglishUICulture) End If Return compilation End Function Private Shared Sub CheckXmlDocument( compilation As VisualBasicCompilation, expectedDocXml As XElement, Optional stringMapper As Func(Of Object, Object) = Nothing, Optional ensureEnglishUICulture As Boolean = False ) Assert.NotNull(expectedDocXml) Using output = New MemoryStream() Using xml = New MemoryStream() Dim emitResult As CodeAnalysis.Emit.EmitResult Dim saveUICulture As Globalization.CultureInfo = Nothing If ensureEnglishUICulture Then Dim preferred = Roslyn.Test.Utilities.EnsureEnglishUICulture.PreferredOrNull If preferred Is Nothing Then ensureEnglishUICulture = False Else saveUICulture = Threading.Thread.CurrentThread.CurrentUICulture Threading.Thread.CurrentThread.CurrentUICulture = preferred End If End If Try emitResult = compilation.Emit(output, xmlDocumentationStream:=xml) Finally If ensureEnglishUICulture Then Threading.Thread.CurrentThread.CurrentUICulture = saveUICulture End If End Try xml.Seek(0, SeekOrigin.Begin) Dim xmlDoc = New StreamReader(xml).ReadToEnd().Trim() If stringMapper IsNot Nothing Then xmlDoc = CStr(stringMapper(xmlDoc)) End If Assert.Equal( expectedDocXml.Value.Trim(), xmlDoc.Replace(vbCrLf, vbLf).Trim()) End Using End Using End Sub #End Region <WorkItem(1087447, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1087447"), WorkItem(436, "CodePlex")> <Fact> Public Sub Bug1087447_01() Dim compilation = CompileCheckDiagnosticsAndXmlDocument( <compilation name="EmptyCref"> <file name="a.vb"> <![CDATA[ ''' <summary> ''' <see cref="C(Of Integer).f()"/> ''' </summary> Class C(Of T) Sub f() End Sub End Class ]]> </file> </compilation>, <error><![CDATA[ BC42309: XML comment has a tag with a 'cref' attribute 'C(Of Integer).f()' that could not be resolved. ''' <see cref="C(Of Integer).f()"/> ~~~~~~~~~~~~~~~~~~~~~~~~ ]]></error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> EmptyCref </name> </assembly> <members> <member name="T:C`1"> <summary> <see cref="!:C(Of Integer).f()"/> </summary> </member> </members> </doc> ]]> </xml>) Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes(descendIntoTrivia:=True).OfType(Of IdentifierNameSyntax)().Where(Function(n) n.Identifier.ValueText = "f").Single() Dim symbolInfo1 = model.GetSymbolInfo(node1.Parent) Assert.Equal("Sub C(Of ?).f()", symbolInfo1.Symbol.ToTestDisplayString()) Dim node = tree.GetRoot().DescendantNodes(descendIntoTrivia:=True).OfType(Of TypeSyntax)().Where(Function(n) n.ToString() = "Integer").Single() Dim symbolInfo = model.GetSymbolInfo(node) Assert.Equal("?", symbolInfo.Symbol.ToTestDisplayString()) End Sub <WorkItem(1087447, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1087447"), WorkItem(436, "CodePlex")> <Fact> Public Sub Bug1087447_02() Dim compilation = CompileCheckDiagnosticsAndXmlDocument( <compilation name="EmptyCref"> <file name="a.vb"> <![CDATA[ ''' <summary> ''' <see cref="C(Of System.Int32).f()"/> ''' </summary> Class C(Of T) Sub f() End Sub End Class ]]> </file> </compilation>, <error><![CDATA[ BC42309: XML comment has a tag with a 'cref' attribute 'C(Of System.Int32).f()' that could not be resolved. ''' <see cref="C(Of System.Int32).f()"/> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></error>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> EmptyCref </name> </assembly> <members> <member name="T:C`1"> <summary> <see cref="!:C(Of System.Int32).f()"/> </summary> </member> </members> </doc> ]]> </xml>) Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes(descendIntoTrivia:=True).OfType(Of IdentifierNameSyntax)().Where(Function(n) n.Identifier.ValueText = "f").Single() Dim symbolInfo1 = model.GetSymbolInfo(node1.Parent) Assert.Equal("Sub C(Of ?).f()", symbolInfo1.Symbol.ToTestDisplayString()) Dim node = tree.GetRoot().DescendantNodes(descendIntoTrivia:=True).OfType(Of TypeSyntax)().Where(Function(n) n.ToString() = "System.Int32").Single() Dim symbolInfo = model.GetSymbolInfo(node) Assert.Equal("?", symbolInfo.Symbol.ToTestDisplayString()) End Sub <Fact, WorkItem(1115058, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1115058")> Public Sub UnterminatedElement() Dim sources = <compilation> <file name="a.vb"> <![CDATA[ Module Module1 '''<summary> ''' Something '''<summary> Sub Main() System.Console.WriteLine("Here") End Sub End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( sources, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.Regular.WithDocumentationMode(DocumentationMode.Diagnose)) ' Compilation should succeed with warnings AssertTheseDiagnostics(CompileAndVerify(compilation, expectedOutput:="Here").Diagnostics, <![CDATA[ BC42304: XML documentation parse error: Element is missing an end tag. XML comment will be ignored. '''<summary> ~~~~~~~~~ BC42304: XML documentation parse error: Element is missing an end tag. XML comment will be ignored. '''<summary> ~~~~~~~~~ BC42304: XML documentation parse error: '>' expected. XML comment will be ignored. '''<summary> ~ BC42304: XML documentation parse error: '>' expected. XML comment will be ignored. '''<summary> ~ BC42304: XML documentation parse error: Expected beginning '<' for an XML tag. XML comment will be ignored. '''<summary> ~ BC42304: XML documentation parse error: Expected beginning '<' for an XML tag. XML comment will be ignored. '''<summary> ~ ]]>) End Sub ''' <summary> ''' "--" is not valid within an XML comment. ''' </summary> <WorkItem(8807, "https://github.com/dotnet/roslyn/issues/8807")> <Fact> Public Sub IncludeErrorDashDashInName() Dim dir = Temp.CreateDirectory() Dim path = dir.Path Dim xmlFile = dir.CreateFile("---.xml").WriteAllText("<summary attrib="""" attrib=""""/>") Dim source = <compilation name="DashDash"> <file name="a.vb"> <![CDATA[ ''' <include file='{0}' path='//param'/> Class C End Class ]]> </file> </compilation> CompileCheckDiagnosticsAndXmlDocument(FormatSourceXml(source, System.IO.Path.Combine(path, "---.xml")), <error/>, <xml> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> DashDash </name> </assembly> <members> <member name="T:C"> <!--warning BC42320: Unable to include XML fragment '//param' of file '**FILE**'.--> </member> </members> </doc> ]]> </xml>, stringMapper:=Function(o) StringReplace(o, System.IO.Path.Combine(TestHelpers.AsXmlCommentText(path), "- - -.xml"), "**FILE**"), ensureEnglishUICulture:=True) End Sub <Fact> <WorkItem(410932, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?id=410932")> Public Sub LookupOnCrefTypeParameter() Dim sources = <compilation> <file name="a.vb"> <![CDATA[ Public Class Test Function F(Of T)() As T End Function ''' <summary> ''' <see cref="F(Of U)()"/> ''' </summary> Public Sub S() End Sub End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( sources, options:=TestOptions.ReleaseDll) Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim name = FindNodesOfTypeFromText(Of NameSyntax)(tree, "U").Single() Dim typeParameter = DirectCast(model.GetSymbolInfo(name).Symbol, TypeParameterSymbol) Assert.Empty(model.LookupSymbols(name.SpanStart, typeParameter, "GetAwaiter")) End Sub <Fact> Public Sub LookupOnCrefOfTupleType() Dim sources = <compilation> <file name="a.vb"> <![CDATA[ Imports System ''' <summary> ''' <see cref="ValueTuple(Of U,U)"/> ''' </summary> Public Class Test End Class ]]> </file> </compilation> Dim references = TargetFrameworkUtil.GetReferences(TargetFramework.StandardAndVBRuntime) Dim compilation = CreateEmptyCompilationWithReferences( sources, references) Dim cMember = compilation.GetMember(Of NamedTypeSymbol)("Test") Dim xmlDocumentationString = cMember.GetDocumentationCommentXml() Dim xml = System.Xml.Linq.XDocument.Parse(xmlDocumentationString) Dim cref = xml.Descendants("see").Single().Attribute("cref").Value Assert.Equal("T:System.ValueTuple`2", cref) End Sub <Fact> Public Sub LookupOnCrefOfTupleTypeField() Dim sources = <compilation> <file name="a.vb"> <![CDATA[ Imports System ''' <summary> ''' <see cref="ValueTuple(Of U,U).Item1"/> ''' </summary> Public Class Test End Class ]]> </file> </compilation> Dim references = TargetFrameworkUtil.GetReferences(TargetFramework.StandardAndVBRuntime) Dim compilation = CreateEmptyCompilationWithReferences( sources, references) Dim cMember = compilation.GetMember(Of NamedTypeSymbol)("Test") Dim xmlDocumentationString = cMember.GetDocumentationCommentXml() Dim xml = System.Xml.Linq.XDocument.Parse(xmlDocumentationString) Dim cref = xml.Descendants("see").Single().Attribute("cref").Value Assert.Equal("F:System.ValueTuple`2.Item1", cref) End Sub <Fact> <WorkItem(39315, "https://github.com/dotnet/roslyn/issues/39315")> Public Sub WriteDocumentationCommentXml_01() Dim sources = <compilation> <file name="a.vb"> <![CDATA[ ''' <summary> a.vb ''' </summary> ]]> </file> <file name="b.vb"> <![CDATA[ ''' <summary> b.vb ''' </summary> ]]> </file> </compilation> Using (New EnsureEnglishUICulture()) Dim comp = CreateCompilationWithMscorlib40(sources, parseOptions:=s_optionsDiagnoseDocComments) Dim diags = DiagnosticBag.GetInstance() DocumentationCommentCompiler.WriteDocumentationCommentXml( comp, assemblyName:=Nothing, xmlDocStream:=Nothing, diagnostics:=New BindingDiagnosticBag(diags), cancellationToken:=Nothing, filterTree:=comp.SyntaxTrees(0)) AssertTheseDiagnostics(diags.ToReadOnlyAndFree(), <errors><![CDATA[ BC42312: XML documentation comments must precede member or type declarations. ''' <summary> a.vb ~~~~~~~~~~~~~~~~ ]]></errors>) diags = DiagnosticBag.GetInstance() DocumentationCommentCompiler.WriteDocumentationCommentXml( comp, assemblyName:=Nothing, xmlDocStream:=Nothing, diagnostics:=New BindingDiagnosticBag(diags), cancellationToken:=Nothing, filterTree:=comp.SyntaxTrees(0), filterSpanWithinTree:=New Text.TextSpan(0, 0)) Assert.Empty(diags.ToReadOnlyAndFree()) diags = DiagnosticBag.GetInstance() DocumentationCommentCompiler.WriteDocumentationCommentXml( comp, assemblyName:=Nothing, xmlDocStream:=Nothing, diagnostics:=New BindingDiagnosticBag(diags), cancellationToken:=Nothing, filterTree:=comp.SyntaxTrees(1)) AssertTheseDiagnostics(diags.ToReadOnlyAndFree(), <errors><![CDATA[ BC42312: XML documentation comments must precede member or type declarations. ''' <summary> b.vb ~~~~~~~~~~~~~~~~ ]]></errors>) diags = DiagnosticBag.GetInstance() DocumentationCommentCompiler.WriteDocumentationCommentXml( comp, assemblyName:=Nothing, xmlDocStream:=Nothing, diagnostics:=New BindingDiagnosticBag(diags), cancellationToken:=Nothing, filterTree:=Nothing) AssertTheseDiagnostics(diags.ToReadOnlyAndFree(), <errors><![CDATA[ BC42312: XML documentation comments must precede member or type declarations. ''' <summary> a.vb ~~~~~~~~~~~~~~~~ BC42312: XML documentation comments must precede member or type declarations. ''' <summary> b.vb ~~~~~~~~~~~~~~~~ ]]></errors>) diags = DiagnosticBag.GetInstance() DocumentationCommentCompiler.WriteDocumentationCommentXml( comp, assemblyName:=Nothing, xmlDocStream:=Nothing, diagnostics:=New BindingDiagnosticBag(diags), cancellationToken:=Nothing, filterTree:=Nothing, filterSpanWithinTree:=New Text.TextSpan(0, 0)) AssertTheseDiagnostics(diags.ToReadOnlyAndFree(), <errors><![CDATA[ BC42312: XML documentation comments must precede member or type declarations. ''' <summary> a.vb ~~~~~~~~~~~~~~~~ BC42312: XML documentation comments must precede member or type declarations. ''' <summary> b.vb ~~~~~~~~~~~~~~~~ ]]></errors>) End Using End Sub End Class End Namespace
1
dotnet/roslyn
56,011
React to string comparison changing on .NET Core
The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
jaredpar
"2021-08-30T17:18:52Z"
"2021-08-30T20:20:04Z"
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
4d99cda6e446e77dbb302e26388c1093bd3ef569
React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
./src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/ComClassTests.vb
' 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.Reflection.Metadata Imports System.Reflection.Metadata.Ecma335 Imports System.Text Imports System.Xml.Linq Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class ComClassTests Inherits BasicTestBase Private Function ReflectComClass( pm As PEModuleSymbol, comClassName As String, Optional memberFilter As Func(Of Symbol, Boolean) = Nothing ) As XElement Dim type As PENamedTypeSymbol = DirectCast(pm.ContainingAssembly.GetTypeByMetadataName(comClassName), PENamedTypeSymbol) Dim combinedFilter = Function(m As Symbol) Return (memberFilter Is Nothing OrElse memberFilter(m)) AndAlso (m.ContainingSymbol IsNot type OrElse m.Kind <> SymbolKind.NamedType OrElse Not DirectCast(m, NamedTypeSymbol).IsDelegateType()) End Function Return ReflectType(type, combinedFilter) End Function Private Function ReflectType(type As PENamedTypeSymbol, Optional memberFilter As Func(Of Symbol, Boolean) = Nothing) As XElement Dim result = <<%= type.TypeKind.ToString() %> Name=<%= type.Name %>></> Dim typeDefFlags = New StringBuilder() MetadataSignatureHelper.AppendTypeAttributes(typeDefFlags, type.TypeDefFlags) result.Add(<TypeDefFlags><%= typeDefFlags %></TypeDefFlags>) If type.GetAttributes().Length > 0 Then result.Add(ReflectAttributes(type.GetAttributes())) End If For Each [interface] In type.Interfaces result.Add(<Implements><%= [interface].ToTestDisplayString() %></Implements>) Next For Each member In type.GetMembers If memberFilter IsNot Nothing AndAlso Not memberFilter(member) Then Continue For End If Select Case member.Kind Case SymbolKind.NamedType result.Add(ReflectType(DirectCast(member, PENamedTypeSymbol), memberFilter)) Case SymbolKind.Method result.Add(ReflectMethod(DirectCast(member, PEMethodSymbol))) Case SymbolKind.Property result.Add(ReflectProperty(DirectCast(member, PEPropertySymbol))) Case SymbolKind.Event result.Add(ReflectEvent(DirectCast(member, PEEventSymbol))) Case SymbolKind.Field result.Add(ReflectField(DirectCast(member, PEFieldSymbol))) Case Else Throw TestExceptionUtilities.UnexpectedValue(member.Kind) End Select Next Return result End Function Private Function ReflectAttributes(attrData As ImmutableArray(Of VisualBasicAttributeData)) As XElement Dim result = <Attributes></Attributes> For Each attr In attrData Dim application = <<%= attr.AttributeClass.ToTestDisplayString() %>/> result.Add(application) application.Add(<ctor><%= attr.AttributeConstructor.ToTestDisplayString() %></ctor>) For Each arg In attr.CommonConstructorArguments application.Add(<a><%= arg.Value.ToString() %></a>) Next For Each named In attr.CommonNamedArguments application.Add(<Named Name=<%= named.Key %>><%= named.Value.Value.ToString() %></Named>) Next Next Return result End Function Private Function ReflectMethod(m As PEMethodSymbol) As XElement Dim result = <Method Name=<%= m.Name %> CallingConvention=<%= m.CallingConvention %>/> Dim methodFlags = New StringBuilder() Dim methodImplFlags = New StringBuilder() MetadataSignatureHelper.AppendMethodAttributes(methodFlags, m.MethodFlags) MetadataSignatureHelper.AppendMethodImplAttributes(methodImplFlags, m.MethodImplFlags) result.Add(<MethodFlags><%= methodFlags %></MethodFlags>) result.Add(<MethodImplFlags><%= methodImplFlags %></MethodImplFlags>) If m.GetAttributes().Length > 0 Then result.Add(ReflectAttributes(m.GetAttributes())) End If For Each impl In m.ExplicitInterfaceImplementations result.Add(<Implements><%= impl.ToTestDisplayString() %></Implements>) Next For Each param In m.Parameters result.Add(ReflectParameter(DirectCast(param, PEParameterSymbol))) Next Dim ret = <Return><Type><%= m.ReturnType %></Type></Return> result.Add(ret) Dim retFlags = m.ReturnParam.ParamFlags If retFlags <> 0 Then Dim paramFlags = New StringBuilder() MetadataSignatureHelper.AppendParameterAttributes(paramFlags, retFlags) ret.Add(<ParamFlags><%= paramFlags %></ParamFlags>) End If If m.GetReturnTypeAttributes().Length > 0 Then ret.Add(ReflectAttributes(m.GetReturnTypeAttributes())) End If Return result End Function Private Function ReflectParameter(p As PEParameterSymbol) As XElement Dim result = <Parameter Name=<%= p.Name %>/> Dim paramFlags = New StringBuilder() MetadataSignatureHelper.AppendParameterAttributes(paramFlags, p.ParamFlags) result.Add(<ParamFlags><%= paramFlags %></ParamFlags>) If p.GetAttributes().Length > 0 Then result.Add(ReflectAttributes(p.GetAttributes())) End If If p.IsParamArray Then Dim peModule = DirectCast(p.ContainingModule, PEModuleSymbol).Module Dim numParamArray = peModule.GetParamArrayCountOrThrow(p.Handle) result.Add(<ParamArray count=<%= numParamArray %>/>) End If Dim type = <Type><%= p.Type %></Type> result.Add(type) If p.IsByRef Then type.@ByRef = "True" End If If p.HasExplicitDefaultValue Then Dim value = p.ExplicitDefaultValue If TypeOf value Is Date Then ' The default display of DateTime is different between Desktop and CoreClr hence ' we need to normalize the value here. value = (CDate(value)).ToString("yyyy-MM-ddTHH:mm:ss") End If result.Add(<Default><%= value %></Default>) End If ' TODO (tomat): add MarshallingInformation Return result End Function Private Function ReflectProperty(p As PEPropertySymbol) As XElement Dim result = <Property Name=<%= p.Name %>/> Dim propertyFlags As New StringBuilder() MetadataSignatureHelper.AppendPropertyAttributes(propertyFlags, p.PropertyFlags) result.Add(<PropertyFlags><%= propertyFlags %></PropertyFlags>) If p.GetAttributes().Length > 0 Then result.Add(ReflectAttributes(p.GetAttributes())) End If If p.GetMethod IsNot Nothing Then result.Add(<Get><%= p.GetMethod.ToTestDisplayString() %></Get>) End If If p.SetMethod IsNot Nothing Then result.Add(<Set><%= p.SetMethod.ToTestDisplayString() %></Set>) End If Return result End Function Private Function ReflectEvent(e As PEEventSymbol) As XElement Dim result = <Event Name=<%= e.Name %>/> Dim eventFlags = New StringBuilder() MetadataSignatureHelper.AppendEventAttributes(eventFlags, e.EventFlags) result.Add(<EventFlags><%= eventFlags %></EventFlags>) If e.GetAttributes().Length > 0 Then result.Add(ReflectAttributes(e.GetAttributes())) End If If e.AddMethod IsNot Nothing Then result.Add(<Add><%= e.AddMethod.ToTestDisplayString() %></Add>) End If If e.RemoveMethod IsNot Nothing Then result.Add(<Remove><%= e.RemoveMethod.ToTestDisplayString() %></Remove>) End If If e.RaiseMethod IsNot Nothing Then result.Add(<Raise><%= e.RaiseMethod.ToTestDisplayString() %></Raise>) End If Return result End Function Private Function ReflectField(f As PEFieldSymbol) As XElement Dim result = <Field Name=<%= f.Name %>/> Dim fieldFlags = New StringBuilder() MetadataSignatureHelper.AppendFieldAttributes(fieldFlags, f.FieldFlags) result.Add(<FieldFlags><%= fieldFlags %></FieldFlags>) If f.GetAttributes().Length > 0 Then result.Add(ReflectAttributes(f.GetAttributes())) End If result.Add(<Type><%= f.Type %></Type>) Return result End Function Private Sub AssertReflection(expected As XElement, actual As XElement) Dim expectedStr = expected.ToString().Trim() Dim actualStr = actual.ToString().Trim() Assert.True(expectedStr.Equals(actualStr), AssertEx.GetAssertMessage(expectedStr, actualStr)) End Sub <Fact> Public Sub SimpleTest1() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System.Runtime.InteropServices Public Class TestAttribute1 Inherits System.Attribute Sub New(x As String) End Sub End Class <System.AttributeUsage(System.AttributeTargets.All And Not System.AttributeTargets.Method)> Public Class TestAttribute2 Inherits System.Attribute Sub New(x As String) End Sub End Class <TestAttribute1("EventDelegate")> Public Delegate Sub EventDelegate(<TestAttribute1("EventDelegate_x")> x As Byte, ByRef y As String, <MarshalAs(UnmanagedType.BStr)> z As String) Public MustInherit Class ComClassTestBase MustOverride Sub M4(Optional x As Date = #8/23/1970#, Optional y As Decimal = 4.5D) MustOverride Sub M5(ParamArray z As Integer()) End Class <Microsoft.VisualBasic.ComClass("", "", "")> Public Class ComClassTest Inherits ComClassTestBase Sub M1() End Sub Property P1 As Integer Get Return Nothing End Get Set(value As Integer) End Set End Property Function M2(x As Integer, ByRef y As Double) As Object Return Nothing End Function Event E1 As EventDelegate <TestAttribute1("TestAttribute1_E2"), TestAttribute2("TestAttribute2_E2")> Event E2(<TestAttribute1("E2_x")> x As Byte, ByRef y As String, <MarshalAs(UnmanagedType.AnsiBStr)> z As String) <TestAttribute1("TestAttribute1_M3")> Function M3(<TestAttribute2("TestAttribute2_M3"), [In], Out, MarshalAs(UnmanagedType.AnsiBStr)> Optional ByRef x As String = "M3_x" ) As <TestAttribute1("Return_M3"), MarshalAs(UnmanagedType.BStr)> String Return Nothing End Function Public Overrides Sub M4(Optional x As Date = #8/23/1970#, Optional y As Decimal = 4.5D) End Sub Public NotOverridable Overrides Sub M5(ParamArray z() As Integer) End Sub Public ReadOnly Property P2 As String Get Return Nothing End Get End Property Public WriteOnly Property P3 As String Set(value As String) End Set End Property <TestAttribute1("TestAttribute1_P4")> Public Property P4(<TestAttribute2("TestAttribute2_P4_x"), [In], MarshalAs(UnmanagedType.AnsiBStr)> x As String, Optional y As Decimal = 5.5D ) As <TestAttribute1("Return_M4"), MarshalAs(UnmanagedType.BStr)> String <TestAttribute1("TestAttribute1_P4_Get")> Get Return Nothing End Get <TestAttribute1("TestAttribute1_P4_Set")> Set(<TestAttribute2("TestAttribute2_P4_value"), [In], MarshalAs(UnmanagedType.LPWStr)> value As String) End Set End Property Public Property P5 As Byte Friend Get Return Nothing End Get Set(value As Byte) End Set End Property Public Property P6 As Byte Get Return Nothing End Get Friend Set(value As Byte) End Set End Property Friend Sub M6() End Sub Public Shared Sub M7() End Sub Friend Property P7 As Long Get Return 0 End Get Set(value As Long) End Set End Property Public Shared Property P8 As Long Get Return 0 End Get Set(value As Long) End Set End Property Friend Event E3 As EventDelegate Public Shared Event E4 As EventDelegate Public WithEvents WithEvents1 As ComClassTest Friend Sub Handler(x As Byte, ByRef y As String, z As String) Handles WithEvents1.E1 End Sub Public F1 As Integer End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <System.Runtime.InteropServices.ComSourceInterfacesAttribute> <ctor>Sub System.Runtime.InteropServices.ComSourceInterfacesAttribute..ctor(sourceInterfaces As System.String)</ctor> <a>ComClassTest+__ComClassTest</a> </System.Runtime.InteropServices.ComSourceInterfacesAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor(_ClassID As System.String, _InterfaceID As System.String, _EventId As System.String)</ctor> <a></a><a></a><a></a> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Field Name="F1"> <FieldFlags>public instance</FieldFlags> <Type>Integer</Type> </Field> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Function ComClassTest._ComClassTest.get_P1() As System.Int32</Implements> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.set_P1(value As System.Int32)</Implements> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M2" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Function ComClassTest._ComClassTest.M2(x As System.Int32, ByRef y As System.Double) As System.Object</Implements> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Parameter Name="y"> <ParamFlags></ParamFlags> <Type ByRef="True">Double</Type> </Parameter> <Return> <Type>Object</Type> </Return> </Method> <Method Name="add_E1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>EventDelegate</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="remove_E1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>EventDelegate</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="add_E2" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>ComClassTest.E2EventHandler</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="remove_E2" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>ComClassTest.E2EventHandler</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <TestAttribute1> <ctor>Sub TestAttribute1..ctor(x As System.String)</ctor> <a>TestAttribute1_M3</a> </TestAttribute1> </Attributes> <Implements>Function ComClassTest._ComClassTest.M3([ByRef x As System.String = "M3_x"]) As System.String</Implements> <Parameter Name="x"> <ParamFlags>[opt] [in] [out] marshal default</ParamFlags> <Attributes> <TestAttribute2> <ctor>Sub TestAttribute2..ctor(x As System.String)</ctor> <a>TestAttribute2_M3</a> </TestAttribute2> </Attributes> <Type ByRef="True">String</Type> <Default>M3_x</Default> </Parameter> <Return> <Type>String</Type> <ParamFlags>marshal</ParamFlags> <Attributes> <TestAttribute1> <ctor>Sub TestAttribute1..ctor(x As System.String)</ctor> <a>Return_M3</a> </TestAttribute1> </Attributes> </Return> </Method> <Method Name="M4" CallingConvention="HasThis"> <MethodFlags>public hidebysig strict virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M4([x As System.DateTime = #8/23/1970 12:00:00 AM#], [y As System.Decimal = 4.5])</Implements> <Parameter Name="x"> <ParamFlags>[opt]</ParamFlags> <Type>Date</Type> <Default>1970-08-23T00:00:00</Default> </Parameter> <Parameter Name="y"> <ParamFlags>[opt]</ParamFlags> <Type>Decimal</Type> <Default>4.5</Default> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M5" CallingConvention="HasThis"> <MethodFlags>public hidebysig strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M5(ParamArray z As System.Int32())</Implements> <Parameter Name="z"> <ParamFlags></ParamFlags> <ParamArray count="1"/> <Type>Integer()</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P2" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Function ComClassTest._ComClassTest.get_P2() As System.String</Implements> <Return> <Type>String</Type> </Return> </Method> <Method Name="set_P3" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.set_P3(value As System.String)</Implements> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>String</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P4" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <TestAttribute1> <ctor>Sub TestAttribute1..ctor(x As System.String)</ctor> <a>TestAttribute1_P4_Get</a> </TestAttribute1> </Attributes> <Implements>Function ComClassTest._ComClassTest.get_P4(x As System.String, [y As System.Decimal = 5.5]) As System.String</Implements> <Parameter Name="x"> <ParamFlags>[in] marshal</ParamFlags> <Attributes> <TestAttribute2> <ctor>Sub TestAttribute2..ctor(x As System.String)</ctor> <a>TestAttribute2_P4_x</a> </TestAttribute2> </Attributes> <Type>String</Type> </Parameter> <Parameter Name="y"> <ParamFlags>[opt]</ParamFlags> <Type>Decimal</Type> <Default>5.5</Default> </Parameter> <Return> <Type>String</Type> <ParamFlags>marshal</ParamFlags> <Attributes> <TestAttribute1> <ctor>Sub TestAttribute1..ctor(x As System.String)</ctor> <a>Return_M4</a> </TestAttribute1> </Attributes> </Return> </Method> <Method Name="set_P4" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <TestAttribute1> <ctor>Sub TestAttribute1..ctor(x As System.String)</ctor> <a>TestAttribute1_P4_Set</a> </TestAttribute1> </Attributes> <Implements>Sub ComClassTest._ComClassTest.set_P4(x As System.String, [y As System.Decimal = 5.5], value As System.String)</Implements> <Parameter Name="x"> <ParamFlags>[in] marshal</ParamFlags> <Attributes> <TestAttribute2> <ctor>Sub TestAttribute2..ctor(x As System.String)</ctor> <a>TestAttribute2_P4_x</a> </TestAttribute2> </Attributes> <Type>String</Type> </Parameter> <Parameter Name="y"> <ParamFlags>[opt]</ParamFlags> <Type>Decimal</Type> <Default>5.5</Default> </Parameter> <Parameter Name="value"> <ParamFlags>[in] marshal</ParamFlags> <Attributes> <TestAttribute2> <ctor>Sub TestAttribute2..ctor(x As System.String)</ctor> <a>TestAttribute2_P4_value</a> </TestAttribute2> </Attributes> <Type>String</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P5" CallingConvention="HasThis"> <MethodFlags>assembly specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Byte</Type> </Return> </Method> <Method Name="set_P5" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.set_P5(value As System.Byte)</Implements> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Byte</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P6" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Function ComClassTest._ComClassTest.get_P6() As System.Byte</Implements> <Return> <Type>Byte</Type> </Return> </Method> <Method Name="set_P6" CallingConvention="HasThis"> <MethodFlags>assembly specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Byte</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M6" CallingConvention="HasThis"> <MethodFlags>assembly instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M7" CallingConvention="Default"> <MethodFlags>public static</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P7" CallingConvention="HasThis"> <MethodFlags>assembly specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Long</Type> </Return> </Method> <Method Name="set_P7" CallingConvention="HasThis"> <MethodFlags>assembly specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Long</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P8" CallingConvention="Default"> <MethodFlags>public specialname static</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Long</Type> </Return> </Method> <Method Name="set_P8" CallingConvention="Default"> <MethodFlags>public specialname static</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Long</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="add_E3" CallingConvention="HasThis"> <MethodFlags>assembly specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>EventDelegate</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="remove_E3" CallingConvention="HasThis"> <MethodFlags>assembly specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>EventDelegate</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="add_E4" CallingConvention="Default"> <MethodFlags>public specialname static</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>EventDelegate</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="remove_E4" CallingConvention="Default"> <MethodFlags>public specialname static</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>EventDelegate</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_WithEvents1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Return> <Type>ComClassTest</Type> </Return> </Method> <Method Name="set_WithEvents1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual instance</MethodFlags> <MethodImplFlags>cil managed synchronized</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="WithEventsValue"> <ParamFlags></ParamFlags> <Type>ComClassTest</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="Handler" CallingConvention="HasThis"> <MethodFlags>assembly instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Byte</Type> </Parameter> <Parameter Name="y"> <ParamFlags></ParamFlags> <Type ByRef="True">String</Type> </Parameter> <Parameter Name="z"> <ParamFlags></ParamFlags> <Type>String</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Get>Function ComClassTest.get_P1() As System.Int32</Get> <Set>Sub ComClassTest.set_P1(value As System.Int32)</Set> </Property> <Property Name="P2"> <PropertyFlags></PropertyFlags> <Get>Function ComClassTest.get_P2() As System.String</Get> </Property> <Property Name="P3"> <PropertyFlags></PropertyFlags> <Set>Sub ComClassTest.set_P3(value As System.String)</Set> </Property> <Property Name="P4"> <PropertyFlags></PropertyFlags> <Attributes> <TestAttribute1> <ctor>Sub TestAttribute1..ctor(x As System.String)</ctor> <a>TestAttribute1_P4</a> </TestAttribute1> </Attributes> <Get>Function ComClassTest.get_P4(x As System.String, [y As System.Decimal = 5.5]) As System.String</Get> <Set>Sub ComClassTest.set_P4(x As System.String, [y As System.Decimal = 5.5], value As System.String)</Set> </Property> <Property Name="P5"> <PropertyFlags></PropertyFlags> <Get>Function ComClassTest.get_P5() As System.Byte</Get> <Set>Sub ComClassTest.set_P5(value As System.Byte)</Set> </Property> <Property Name="P6"> <PropertyFlags></PropertyFlags> <Get>Function ComClassTest.get_P6() As System.Byte</Get> <Set>Sub ComClassTest.set_P6(value As System.Byte)</Set> </Property> <Property Name="P7"> <PropertyFlags></PropertyFlags> <Get>Function ComClassTest.get_P7() As System.Int64</Get> <Set>Sub ComClassTest.set_P7(value As System.Int64)</Set> </Property> <Property Name="P8"> <PropertyFlags></PropertyFlags> <Get>Function ComClassTest.get_P8() As System.Int64</Get> <Set>Sub ComClassTest.set_P8(value As System.Int64)</Set> </Property> <Property Name="WithEvents1"> <PropertyFlags></PropertyFlags> <Get>Function ComClassTest.get_WithEvents1() As ComClassTest</Get> <Set>Sub ComClassTest.set_WithEvents1(WithEventsValue As ComClassTest)</Set> </Property> <Event Name="E1"> <EventFlags></EventFlags> <Add>Sub ComClassTest.add_E1(obj As EventDelegate)</Add> <Remove>Sub ComClassTest.remove_E1(obj As EventDelegate)</Remove> </Event> <Event Name="E2"> <EventFlags></EventFlags> <Attributes> <TestAttribute1> <ctor>Sub TestAttribute1..ctor(x As System.String)</ctor> <a>TestAttribute1_E2</a> </TestAttribute1> <TestAttribute2> <ctor>Sub TestAttribute2..ctor(x As System.String)</ctor> <a>TestAttribute2_E2</a> </TestAttribute2> </Attributes> <Add>Sub ComClassTest.add_E2(obj As ComClassTest.E2EventHandler)</Add> <Remove>Sub ComClassTest.remove_E2(obj As ComClassTest.E2EventHandler)</Remove> </Event> <Event Name="E3"> <EventFlags></EventFlags> <Add>Sub ComClassTest.add_E3(obj As EventDelegate)</Add> <Remove>Sub ComClassTest.remove_E3(obj As EventDelegate)</Remove> </Event> <Event Name="E4"> <EventFlags></EventFlags> <Add>Sub ComClassTest.add_E4(obj As EventDelegate)</Add> <Remove>Sub ComClassTest.remove_E4(obj As EventDelegate)</Remove> </Event> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M2" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>3</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Parameter Name="y"> <ParamFlags></ParamFlags> <Type ByRef="True">Double</Type> </Parameter> <Return> <Type>Object</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>4</a> </System.Runtime.InteropServices.DispIdAttribute> <TestAttribute1> <ctor>Sub TestAttribute1..ctor(x As System.String)</ctor> <a>TestAttribute1_M3</a> </TestAttribute1> </Attributes> <Parameter Name="x"> <ParamFlags>[opt] [in] [out] marshal default</ParamFlags> <Attributes> <TestAttribute2> <ctor>Sub TestAttribute2..ctor(x As System.String)</ctor> <a>TestAttribute2_M3</a> </TestAttribute2> </Attributes> <Type ByRef="True">String</Type> <Default>M3_x</Default> </Parameter> <Return> <Type>String</Type> <ParamFlags>marshal</ParamFlags> <Attributes> <TestAttribute1> <ctor>Sub TestAttribute1..ctor(x As System.String)</ctor> <a>Return_M3</a> </TestAttribute1> </Attributes> </Return> </Method> <Method Name="M4" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>5</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="x"> <ParamFlags>[opt]</ParamFlags> <Type>Date</Type> <Default>1970-08-23T00:00:00</Default> </Parameter> <Parameter Name="y"> <ParamFlags>[opt]</ParamFlags> <Type>Decimal</Type> <Default>4.5</Default> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M5" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>6</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="z"> <ParamFlags></ParamFlags> <ParamArray count="1"/> <Type>Integer()</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P2" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>7</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>String</Type> </Return> </Method> <Method Name="set_P3" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>8</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>String</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P4" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>9</a> </System.Runtime.InteropServices.DispIdAttribute> <TestAttribute1> <ctor>Sub TestAttribute1..ctor(x As System.String)</ctor> <a>TestAttribute1_P4_Get</a> </TestAttribute1> </Attributes> <Parameter Name="x"> <ParamFlags>[in] marshal</ParamFlags> <Attributes> <TestAttribute2> <ctor>Sub TestAttribute2..ctor(x As System.String)</ctor> <a>TestAttribute2_P4_x</a> </TestAttribute2> </Attributes> <Type>String</Type> </Parameter> <Parameter Name="y"> <ParamFlags>[opt]</ParamFlags> <Type>Decimal</Type> <Default>5.5</Default> </Parameter> <Return> <Type>String</Type> <ParamFlags>marshal</ParamFlags> <Attributes> <TestAttribute1> <ctor>Sub TestAttribute1..ctor(x As System.String)</ctor> <a>Return_M4</a> </TestAttribute1> </Attributes> </Return> </Method> <Method Name="set_P4" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>9</a> </System.Runtime.InteropServices.DispIdAttribute> <TestAttribute1> <ctor>Sub TestAttribute1..ctor(x As System.String)</ctor> <a>TestAttribute1_P4_Set</a> </TestAttribute1> </Attributes> <Parameter Name="x"> <ParamFlags>[in] marshal</ParamFlags> <Attributes> <TestAttribute2> <ctor>Sub TestAttribute2..ctor(x As System.String)</ctor> <a>TestAttribute2_P4_x</a> </TestAttribute2> </Attributes> <Type>String</Type> </Parameter> <Parameter Name="y"> <ParamFlags>[opt]</ParamFlags> <Type>Decimal</Type> <Default>5.5</Default> </Parameter> <Parameter Name="value"> <ParamFlags>[in] marshal</ParamFlags> <Attributes> <TestAttribute2> <ctor>Sub TestAttribute2..ctor(x As System.String)</ctor> <a>TestAttribute2_P4_value</a> </TestAttribute2> </Attributes> <Type>String</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="set_P5" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>10</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Byte</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P6" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>11</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Byte</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest._ComClassTest.get_P1() As System.Int32</Get> <Set>Sub ComClassTest._ComClassTest.set_P1(value As System.Int32)</Set> </Property> <Property Name="P2"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>7</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest._ComClassTest.get_P2() As System.String</Get> </Property> <Property Name="P3"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>8</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Set>Sub ComClassTest._ComClassTest.set_P3(value As System.String)</Set> </Property> <Property Name="P4"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>9</a> </System.Runtime.InteropServices.DispIdAttribute> <TestAttribute1> <ctor>Sub TestAttribute1..ctor(x As System.String)</ctor> <a>TestAttribute1_P4</a> </TestAttribute1> </Attributes> <Get>Function ComClassTest._ComClassTest.get_P4(x As System.String, [y As System.Decimal = 5.5]) As System.String</Get> <Set>Sub ComClassTest._ComClassTest.set_P4(x As System.String, [y As System.Decimal = 5.5], value As System.String)</Set> </Property> <Property Name="P5"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>10</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Set>Sub ComClassTest._ComClassTest.set_P5(value As System.Byte)</Set> </Property> <Property Name="P6"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>11</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest._ComClassTest.get_P6() As System.Byte</Get> </Property> </Interface> <Interface Name="__ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.InterfaceTypeAttribute> <ctor>Sub System.Runtime.InteropServices.InterfaceTypeAttribute..ctor(interfaceType As System.Int16)</ctor> <a>2</a> </System.Runtime.InteropServices.InterfaceTypeAttribute> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="E1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Byte</Type> </Parameter> <Parameter Name="y"> <ParamFlags></ParamFlags> <Type ByRef="True">String</Type> </Parameter> <Parameter Name="z"> <ParamFlags></ParamFlags> <Type>String</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="E2" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> <TestAttribute1> <ctor>Sub TestAttribute1..ctor(x As System.String)</ctor> <a>TestAttribute1_E2</a> </TestAttribute1> </Attributes> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Byte</Type> </Parameter> <Parameter Name="y"> <ParamFlags></ParamFlags> <Type ByRef="True">String</Type> </Parameter> <Parameter Name="z"> <ParamFlags></ParamFlags> <Type>String</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> </Interface> </Class> ' Strip TODO comments from the base-line. For Each d In expected.DescendantNodes.ToArray() Dim comment = TryCast(d, XComment) If comment IsNot Nothing Then comment.Remove() End If Next Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub).VerifyDiagnostics() End Sub <Fact> Public Sub SimpleTest2() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest Sub M1() End Sub End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub).VerifyDiagnostics() End Sub <Fact> Public Sub SimpleTest3() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ <Microsoft.VisualBasic.ComClass("7666AC25-855F-4534-BC55-27BF09D49D46")> Public Class ComClassTest Event E1 As System.Action End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.GuidAttribute> <ctor>Sub System.Runtime.InteropServices.GuidAttribute..ctor(guid As System.String)</ctor> <a>7666AC25-855F-4534-BC55-27BF09D49D46</a> </System.Runtime.InteropServices.GuidAttribute> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <System.Runtime.InteropServices.ComSourceInterfacesAttribute> <ctor>Sub System.Runtime.InteropServices.ComSourceInterfacesAttribute..ctor(sourceInterfaces As System.String)</ctor> <a>ComClassTest+__ComClassTest</a> </System.Runtime.InteropServices.ComSourceInterfacesAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor(_ClassID As System.String)</ctor> <a>7666AC25-855F-4534-BC55-27BF09D49D46</a> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="add_E1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>System.Action</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="remove_E1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>System.Action</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Event Name="E1"> <EventFlags></EventFlags> <Add>Sub ComClassTest.add_E1(obj As System.Action)</Add> <Remove>Sub ComClassTest.remove_E1(obj As System.Action)</Remove> </Event> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> </Interface> <Interface Name="__ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.InterfaceTypeAttribute> <ctor>Sub System.Runtime.InteropServices.InterfaceTypeAttribute..ctor(interfaceType As System.Int16)</ctor> <a>2</a> </System.Runtime.InteropServices.InterfaceTypeAttribute> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="E1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub).VerifyDiagnostics() End Sub <Fact> Public Sub SimpleTest4() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ <Microsoft.VisualBasic.ComClass("7666AC25-855F-4534-BC55-27BF09D49D46", "54388137-8A76-491e-AA3A-853E23AC1217")> Public Class ComClassTest Sub M1() End Sub End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.GuidAttribute> <ctor>Sub System.Runtime.InteropServices.GuidAttribute..ctor(guid As System.String)</ctor> <a>7666AC25-855F-4534-BC55-27BF09D49D46</a> </System.Runtime.InteropServices.GuidAttribute> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor(_ClassID As System.String, _InterfaceID As System.String)</ctor> <a>7666AC25-855F-4534-BC55-27BF09D49D46</a> <a>54388137-8A76-491e-AA3A-853E23AC1217</a> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.GuidAttribute> <ctor>Sub System.Runtime.InteropServices.GuidAttribute..ctor(guid As System.String)</ctor> <a>54388137-8A76-491e-AA3A-853E23AC1217</a> </System.Runtime.InteropServices.GuidAttribute> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub).VerifyDiagnostics() End Sub <Fact> Public Sub SimpleTest5() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub) AssertTheseDiagnostics(verifier.Compilation, <expected> BC40011: 'Microsoft.VisualBasic.ComClassAttribute' is specified for class 'ComClassTest' but 'ComClassTest' has no public members that can be exposed to COM; therefore, no COM interfaces are generated. Public Class ComClassTest ~~~~~~~~~~~~ </expected>) End Sub <Fact> Public Sub SimpleTest6() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ <Microsoft.VisualBasic.ComClass("7666AC25-855F-4534-BC55-27BF09D49D46", "54388137-8A76-491e-AA3A-853E23AC1217", "EA329A13-16A0-478d-B41F-47583A761FF2", InterfaceShadows:=True)> Public Class ComClassTest Sub M1() Dim x as Integer = 12 Dim y = Function() x End Sub End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.GuidAttribute> <ctor>Sub System.Runtime.InteropServices.GuidAttribute..ctor(guid As System.String)</ctor> <a>7666AC25-855F-4534-BC55-27BF09D49D46</a> </System.Runtime.InteropServices.GuidAttribute> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor(_ClassID As System.String, _InterfaceID As System.String, _EventId As System.String)</ctor> <a>7666AC25-855F-4534-BC55-27BF09D49D46</a> <a>54388137-8A76-491e-AA3A-853E23AC1217</a> <a>EA329A13-16A0-478d-B41F-47583A761FF2</a> <Named Name="InterfaceShadows">True</Named> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.GuidAttribute> <ctor>Sub System.Runtime.InteropServices.GuidAttribute..ctor(guid As System.String)</ctor> <a>54388137-8A76-491e-AA3A-853E23AC1217</a> </System.Runtime.InteropServices.GuidAttribute> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> </Interface> <Class Name="_Closure$__1-0"> <TypeDefFlags>nested assembly auto ansi sealed</TypeDefFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Field Name="$VB$Local_x"> <FieldFlags>public instance</FieldFlags> <Type>Integer</Type> </Field> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="_Lambda$__0" CallingConvention="HasThis"> <MethodFlags>assembly specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Integer</Type> </Return> </Method> </Class> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub).VerifyDiagnostics() End Sub <Fact> Public Sub Test_ERR_ComClassOnGeneric() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest(Of T) End Class Public Class ComClassTest1(Of T) <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest2 End Class End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll) Dim expected = <expected> BC31527: 'Microsoft.VisualBasic.ComClassAttribute' cannot be applied to a class that is generic or contained inside a generic type. Public Class ComClassTest(Of T) ~~~~~~~~~~~~ BC31527: 'Microsoft.VisualBasic.ComClassAttribute' cannot be applied to a class that is generic or contained inside a generic type. Public Class ComClassTest2 ~~~~~~~~~~~~~ </expected> AssertTheseDeclarationDiagnostics(compilation, expected) AssertTheseDiagnostics(compilation, expected) End Sub <Fact()> Public Sub Test_ERR_BadAttributeUuid2() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass("1", "2", "3")> Public Class ComClassTest Public Sub Goo() End Sub End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll) Dim expected = <expected> BC32500: 'ComClassAttribute' cannot be applied because the format of the GUID '1' is not correct. Public Class ComClassTest ~~~~~~~~~~~~ BC32500: 'ComClassAttribute' cannot be applied because the format of the GUID '2' is not correct. Public Class ComClassTest ~~~~~~~~~~~~ BC32500: 'ComClassAttribute' cannot be applied because the format of the GUID '3' is not correct. Public Class ComClassTest ~~~~~~~~~~~~ </expected> AssertTheseDeclarationDiagnostics(compilation, expected) AssertTheseDiagnostics(compilation, expected) End Sub <Fact> Public Sub Test_ERR_ComClassDuplicateGuids1() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass("7666AC25-855F-4534-BC55-27BF09D49D46", "7666AC25-855F-4534-BC55-27BF09D49D46", "7666AC25-855F-4534-BC55-27BF09D49D46")> Public Class ComClassTest1 Public Sub Goo() End Sub End Class <Microsoft.VisualBasic.ComClass("7666AC25-855F-4534-BC55-27BF09D49D46", "7666AC25-855F-4534-BC55-27BF09D49D46", "")> Public Class ComClassTest2 Public Sub Goo() End Sub End Class <Microsoft.VisualBasic.ComClass("7666AC25-855F-4534-BC55-27BF09D49D46", "", "7666AC25-855F-4534-BC55-27BF09D49D46")> Public Class ComClassTest3 Public Sub Goo() End Sub End Class <Microsoft.VisualBasic.ComClass("", "00000000-0000-0000-0000-000000000000", "")> Public Class ComClassTest4 Public Sub Goo() End Sub End Class <Microsoft.VisualBasic.ComClass("", "", "00000000-0000-0000-0000-000000000000")> Public Class ComClassTest5 Public Sub Goo() End Sub End Class <Microsoft.VisualBasic.ComClass("", "00000000-0000-0000-0000-000000000000", "0")> Public Class ComClassTest6 Public Sub Goo() End Sub End Class <Microsoft.VisualBasic.ComClass("", "0", "00000000-0000-0000-0000-000000000000")> Public Class ComClassTest7 Public Sub Goo() End Sub End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll) Dim expected = <expected> BC32507: 'InterfaceId' and 'EventsId' parameters for 'Microsoft.VisualBasic.ComClassAttribute' on 'ComClassTest1' cannot have the same value. Public Class ComClassTest1 ~~~~~~~~~~~~~ BC32500: 'ComClassAttribute' cannot be applied because the format of the GUID '0' is not correct. Public Class ComClassTest6 ~~~~~~~~~~~~~ BC32500: 'ComClassAttribute' cannot be applied because the format of the GUID '0' is not correct. Public Class ComClassTest7 ~~~~~~~~~~~~~ </expected> AssertTheseDeclarationDiagnostics(compilation, expected) AssertTheseDiagnostics(compilation, expected) End Sub <Fact> Public Sub Test_ERR_ComClassAndReservedAttribute1_Guid() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass(), Guid("7666AC25-855F-4534-BC55-27BF09D49D46")> Public Class ComClassTest Public Sub Goo() End Sub End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll) Dim expected = <expected> BC32501: 'Microsoft.VisualBasic.ComClassAttribute' and 'GuidAttribute' cannot both be applied to the same class. Public Class ComClassTest ~~~~~~~~~~~~ </expected> AssertTheseDeclarationDiagnostics(compilation, expected) AssertTheseDiagnostics(compilation, expected) End Sub <Fact> Public Sub Test_ERR_ComClassAndReservedAttribute1_ClassInterface() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass(), ClassInterface(0)> Public Class ComClassTest1 Public Sub Goo() End Sub End Class <Microsoft.VisualBasic.ComClass(), ClassInterface(ClassInterfaceType.None)> Public Class ComClassTest2 Public Sub Goo() End Sub End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll) Dim expected = <expected> BC32501: 'Microsoft.VisualBasic.ComClassAttribute' and 'ClassInterfaceAttribute' cannot both be applied to the same class. Public Class ComClassTest1 ~~~~~~~~~~~~~ BC32501: 'Microsoft.VisualBasic.ComClassAttribute' and 'ClassInterfaceAttribute' cannot both be applied to the same class. Public Class ComClassTest2 ~~~~~~~~~~~~~ </expected> AssertTheseDeclarationDiagnostics(compilation, expected) AssertTheseDiagnostics(compilation, expected) End Sub <Fact> Public Sub Test_ERR_ComClassAndReservedAttribute1_ComSourceInterfaces() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass(), ComSourceInterfaces("x")> Public Class ComClassTest1 Public Sub Goo() End Sub End Class <Microsoft.VisualBasic.ComClass(), ComSourceInterfaces(GetType(ComClassTest1))> Public Class ComClassTest2 Public Sub Goo() End Sub End Class <Microsoft.VisualBasic.ComClass(), ComSourceInterfaces(GetType(ComClassTest1), GetType(ComClassTest1))> Public Class ComClassTest3 Public Sub Goo() End Sub End Class <Microsoft.VisualBasic.ComClass(), ComSourceInterfaces(GetType(ComClassTest1), GetType(ComClassTest1), GetType(ComClassTest1))> Public Class ComClassTest4 Public Sub Goo() End Sub End Class <Microsoft.VisualBasic.ComClass(), ComSourceInterfaces(GetType(ComClassTest1), GetType(ComClassTest1), GetType(ComClassTest1), GetType(ComClassTest1))> Public Class ComClassTest5 Public Sub Goo() End Sub End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll) Dim expected = <expected> BC32501: 'Microsoft.VisualBasic.ComClassAttribute' and 'ComSourceInterfacesAttribute' cannot both be applied to the same class. Public Class ComClassTest1 ~~~~~~~~~~~~~ BC32501: 'Microsoft.VisualBasic.ComClassAttribute' and 'ComSourceInterfacesAttribute' cannot both be applied to the same class. Public Class ComClassTest2 ~~~~~~~~~~~~~ BC32501: 'Microsoft.VisualBasic.ComClassAttribute' and 'ComSourceInterfacesAttribute' cannot both be applied to the same class. Public Class ComClassTest3 ~~~~~~~~~~~~~ BC32501: 'Microsoft.VisualBasic.ComClassAttribute' and 'ComSourceInterfacesAttribute' cannot both be applied to the same class. Public Class ComClassTest4 ~~~~~~~~~~~~~ BC32501: 'Microsoft.VisualBasic.ComClassAttribute' and 'ComSourceInterfacesAttribute' cannot both be applied to the same class. Public Class ComClassTest5 ~~~~~~~~~~~~~ </expected> AssertTheseDeclarationDiagnostics(compilation, expected) AssertTheseDiagnostics(compilation, expected) End Sub <Fact> Public Sub Test_ERR_ComClassAndReservedAttribute1_ComVisible() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass(), ComVisible(False)> Public Class ComClassTest1 Public Sub Goo() End Sub End Class <Microsoft.VisualBasic.ComClass(), ComVisible(True)> Public Class ComClassTest2 Public Sub Goo() End Sub End Class <Microsoft.VisualBasic.ComClass(), ComVisible()> Public Class ComClassTest3 Public Sub Goo() End Sub End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll) Dim expected = <expected><![CDATA[ BC32501: 'Microsoft.VisualBasic.ComClassAttribute' and 'ComVisibleAttribute(False)' cannot both be applied to the same class. Public Class ComClassTest1 ~~~~~~~~~~~~~ BC30455: Argument not specified for parameter 'visibility' of 'Public Overloads Sub New(visibility As Boolean)'. <Microsoft.VisualBasic.ComClass(), ComVisible()> ~~~~~~~~~~ ]]></expected> AssertTheseDeclarationDiagnostics(compilation, expected) AssertTheseDiagnostics(compilation, expected) End Sub <Fact> Public Sub Test_ERR_ComClassRequiresPublicClass1_ERR_ComClassRequiresPublicClass2() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Friend Class ComClassTest1 Public Sub Goo() End Sub End Class Friend Class ComClassTest2 Friend Class ComClassTest3 <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest4 Public Sub Goo() End Sub End Class End Class End Class Friend Class ComClassTest5 Public Class ComClassTest6 <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest7 Public Sub Goo() End Sub End Class End Class End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll) Dim expected = <expected> BC32509: 'Microsoft.VisualBasic.ComClassAttribute' cannot be applied to 'ComClassTest1' because it is not declared 'Public'. Friend Class ComClassTest1 ~~~~~~~~~~~~~ BC32504: 'Microsoft.VisualBasic.ComClassAttribute' cannot be applied to 'ComClassTest4' because its container 'ComClassTest3' is not declared 'Public'. Public Class ComClassTest4 ~~~~~~~~~~~~~ BC32504: 'Microsoft.VisualBasic.ComClassAttribute' cannot be applied to 'ComClassTest7' because its container 'ComClassTest5' is not declared 'Public'. Public Class ComClassTest7 ~~~~~~~~~~~~~ </expected> AssertTheseDeclarationDiagnostics(compilation, expected) AssertTheseDiagnostics(compilation, expected) End Sub <Fact> Public Sub Test_ERR_ComClassCantBeAbstract0() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public MustInherit Class ComClassTest1 Public Sub Goo() End Sub End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll) Dim expected = <expected> BC32508: 'Microsoft.VisualBasic.ComClassAttribute' cannot be applied to a class that is declared 'MustInherit'. Public MustInherit Class ComClassTest1 ~~~~~~~~~~~~~ </expected> AssertTheseDeclarationDiagnostics(compilation, expected) AssertTheseDiagnostics(compilation, expected) End Sub <Fact> Public Sub Test_ERR_MemberConflictWithSynth4() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest1 Public Sub Goo() End Sub Public Event E1() WithEvents ComClassTest1 As ComClassTest1 Private Sub __ComClassTest1() End Sub Protected Sub __ComClassTest1(x As Integer) End Sub End Class <Microsoft.VisualBasic.ComClass(InterfaceShadows:=False)> Public Class ComClassTest2 Public Sub Goo() End Sub Public Event E1() WithEvents ComClassTest2 As ComClassTest2 Private Sub __ComClassTest2() End Sub Protected Sub __ComClassTest2(x As Integer) End Sub End Class <Microsoft.VisualBasic.ComClass(InterfaceShadows:=True)> Public Class ComClassTest3 Public Sub Goo() End Sub Public Event E1() WithEvents ComClassTest3 As ComClassTest3 Private Sub __ComClassTest3() End Sub Protected Sub __ComClassTest3(x As Integer) End Sub End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll) Dim expected = <expected> BC31058: Conflicts with 'Interface _ComClassTest1', which is implicitly declared for 'ComClassAttribute' in Class 'ComClassTest1'. WithEvents ComClassTest1 As ComClassTest1 ~~~~~~~~~~~~~ BC31058: Conflicts with 'Interface __ComClassTest1', which is implicitly declared for 'ComClassAttribute' in Class 'ComClassTest1'. Private Sub __ComClassTest1() ~~~~~~~~~~~~~~~ BC31058: Conflicts with 'Interface __ComClassTest1', which is implicitly declared for 'ComClassAttribute' in Class 'ComClassTest1'. Protected Sub __ComClassTest1(x As Integer) ~~~~~~~~~~~~~~~ BC31058: Conflicts with 'Interface _ComClassTest2', which is implicitly declared for 'ComClassAttribute' in Class 'ComClassTest2'. WithEvents ComClassTest2 As ComClassTest2 ~~~~~~~~~~~~~ BC31058: Conflicts with 'Interface __ComClassTest2', which is implicitly declared for 'ComClassAttribute' in Class 'ComClassTest2'. Private Sub __ComClassTest2() ~~~~~~~~~~~~~~~ BC31058: Conflicts with 'Interface __ComClassTest2', which is implicitly declared for 'ComClassAttribute' in Class 'ComClassTest2'. Protected Sub __ComClassTest2(x As Integer) ~~~~~~~~~~~~~~~ BC31058: Conflicts with 'Interface _ComClassTest3', which is implicitly declared for 'ComClassAttribute' in Class 'ComClassTest3'. WithEvents ComClassTest3 As ComClassTest3 ~~~~~~~~~~~~~ BC31058: Conflicts with 'Interface __ComClassTest3', which is implicitly declared for 'ComClassAttribute' in Class 'ComClassTest3'. Private Sub __ComClassTest3() ~~~~~~~~~~~~~~~ BC31058: Conflicts with 'Interface __ComClassTest3', which is implicitly declared for 'ComClassAttribute' in Class 'ComClassTest3'. Protected Sub __ComClassTest3(x As Integer) ~~~~~~~~~~~~~~~ </expected> AssertTheseDeclarationDiagnostics(compilation, expected) AssertTheseDiagnostics(compilation, expected) End Sub <Fact> Public Sub Test_WRN_ComClassInterfaceShadows5_1() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Public Class ComClassBase Private Sub _ComClassTest1() End Sub Private Sub __ComClassTest1() End Sub Protected Sub _ComClassTest1(x As Integer) End Sub Protected Sub __ComClassTest1(x As Integer) End Sub Friend Sub _ComClassTest1(x As Integer, y As Integer) End Sub Friend Sub __ComClassTest1(x As Integer, y As Integer) End Sub Protected Friend Sub _ComClassTest1(x As Integer, y As Integer, z As Integer) End Sub Protected Friend Sub __ComClassTest1(x As Integer, y As Integer, z As Integer) End Sub Public Sub _ComClassTest1(x As Long) End Sub Public Sub __ComClassTest1(x As Long) End Sub End Class <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest1 Inherits ComClassBase Public Sub Goo() End Sub Public Event E1() End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll) Dim expected = <expected> BC42101: 'Microsoft.VisualBasic.ComClassAttribute' on class 'ComClassTest1' implicitly declares Interface '__ComClassTest1', which conflicts with a member of the same name in Class 'ComClassBase'. Use 'Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)' if you want to hide the name on the base ComClassBase. Public Class ComClassTest1 ~~~~~~~~~~~~~ BC42101: 'Microsoft.VisualBasic.ComClassAttribute' on class 'ComClassTest1' implicitly declares Interface '__ComClassTest1', which conflicts with a member of the same name in Class 'ComClassBase'. Use 'Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)' if you want to hide the name on the base ComClassBase. Public Class ComClassTest1 ~~~~~~~~~~~~~ BC42101: 'Microsoft.VisualBasic.ComClassAttribute' on class 'ComClassTest1' implicitly declares Interface '__ComClassTest1', which conflicts with a member of the same name in Class 'ComClassBase'. Use 'Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)' if you want to hide the name on the base ComClassBase. Public Class ComClassTest1 ~~~~~~~~~~~~~ BC42101: 'Microsoft.VisualBasic.ComClassAttribute' on class 'ComClassTest1' implicitly declares Interface '__ComClassTest1', which conflicts with a member of the same name in Class 'ComClassBase'. Use 'Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)' if you want to hide the name on the base ComClassBase. Public Class ComClassTest1 ~~~~~~~~~~~~~ BC42101: 'Microsoft.VisualBasic.ComClassAttribute' on class 'ComClassTest1' implicitly declares Interface '_ComClassTest1', which conflicts with a member of the same name in Class 'ComClassBase'. Use 'Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)' if you want to hide the name on the base ComClassBase. Public Class ComClassTest1 ~~~~~~~~~~~~~ BC42101: 'Microsoft.VisualBasic.ComClassAttribute' on class 'ComClassTest1' implicitly declares Interface '_ComClassTest1', which conflicts with a member of the same name in Class 'ComClassBase'. Use 'Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)' if you want to hide the name on the base ComClassBase. Public Class ComClassTest1 ~~~~~~~~~~~~~ BC42101: 'Microsoft.VisualBasic.ComClassAttribute' on class 'ComClassTest1' implicitly declares Interface '_ComClassTest1', which conflicts with a member of the same name in Class 'ComClassBase'. Use 'Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)' if you want to hide the name on the base ComClassBase. Public Class ComClassTest1 ~~~~~~~~~~~~~ BC42101: 'Microsoft.VisualBasic.ComClassAttribute' on class 'ComClassTest1' implicitly declares Interface '_ComClassTest1', which conflicts with a member of the same name in Class 'ComClassBase'. Use 'Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)' if you want to hide the name on the base ComClassBase. Public Class ComClassTest1 ~~~~~~~~~~~~~ </expected> AssertTheseDeclarationDiagnostics(compilation, expected) AssertTheseDiagnostics(compilation, expected) End Sub <Fact> Public Sub Test_WRN_ComClassInterfaceShadows5_2() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Public Class ComClassBase Private Sub _ComClassTest1() End Sub Private Sub __ComClassTest1() End Sub Protected Sub _ComClassTest1(x As Integer) End Sub Protected Sub __ComClassTest1(x As Integer) End Sub Friend Sub _ComClassTest1(x As Integer, y As Integer) End Sub Friend Sub __ComClassTest1(x As Integer, y As Integer) End Sub Protected Friend Sub _ComClassTest1(x As Integer, y As Integer, z As Integer) End Sub Protected Friend Sub __ComClassTest1(x As Integer, y As Integer, z As Integer) End Sub Public Sub _ComClassTest1(x As Long) End Sub Public Sub __ComClassTest1(x As Long) End Sub End Class <Microsoft.VisualBasic.ComClass(InterfaceShadows:=False)> Public Class ComClassTest1 Inherits ComClassBase Public Sub Goo() End Sub Public Event E1() End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll) Dim expected = <expected> BC42101: 'Microsoft.VisualBasic.ComClassAttribute' on class 'ComClassTest1' implicitly declares Interface '__ComClassTest1', which conflicts with a member of the same name in Class 'ComClassBase'. Use 'Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)' if you want to hide the name on the base ComClassBase. Public Class ComClassTest1 ~~~~~~~~~~~~~ BC42101: 'Microsoft.VisualBasic.ComClassAttribute' on class 'ComClassTest1' implicitly declares Interface '__ComClassTest1', which conflicts with a member of the same name in Class 'ComClassBase'. Use 'Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)' if you want to hide the name on the base ComClassBase. Public Class ComClassTest1 ~~~~~~~~~~~~~ BC42101: 'Microsoft.VisualBasic.ComClassAttribute' on class 'ComClassTest1' implicitly declares Interface '__ComClassTest1', which conflicts with a member of the same name in Class 'ComClassBase'. Use 'Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)' if you want to hide the name on the base ComClassBase. Public Class ComClassTest1 ~~~~~~~~~~~~~ BC42101: 'Microsoft.VisualBasic.ComClassAttribute' on class 'ComClassTest1' implicitly declares Interface '__ComClassTest1', which conflicts with a member of the same name in Class 'ComClassBase'. Use 'Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)' if you want to hide the name on the base ComClassBase. Public Class ComClassTest1 ~~~~~~~~~~~~~ BC42101: 'Microsoft.VisualBasic.ComClassAttribute' on class 'ComClassTest1' implicitly declares Interface '_ComClassTest1', which conflicts with a member of the same name in Class 'ComClassBase'. Use 'Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)' if you want to hide the name on the base ComClassBase. Public Class ComClassTest1 ~~~~~~~~~~~~~ BC42101: 'Microsoft.VisualBasic.ComClassAttribute' on class 'ComClassTest1' implicitly declares Interface '_ComClassTest1', which conflicts with a member of the same name in Class 'ComClassBase'. Use 'Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)' if you want to hide the name on the base ComClassBase. Public Class ComClassTest1 ~~~~~~~~~~~~~ BC42101: 'Microsoft.VisualBasic.ComClassAttribute' on class 'ComClassTest1' implicitly declares Interface '_ComClassTest1', which conflicts with a member of the same name in Class 'ComClassBase'. Use 'Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)' if you want to hide the name on the base ComClassBase. Public Class ComClassTest1 ~~~~~~~~~~~~~ BC42101: 'Microsoft.VisualBasic.ComClassAttribute' on class 'ComClassTest1' implicitly declares Interface '_ComClassTest1', which conflicts with a member of the same name in Class 'ComClassBase'. Use 'Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)' if you want to hide the name on the base ComClassBase. Public Class ComClassTest1 ~~~~~~~~~~~~~ </expected> AssertTheseDeclarationDiagnostics(compilation, expected) AssertTheseDiagnostics(compilation, expected) End Sub <Fact> Public Sub Test_WRN_ComClassInterfaceShadows5_3() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Public Class ComClassBase Private Sub _ComClassTest1() End Sub Private Sub __ComClassTest1() End Sub Protected Sub _ComClassTest1(x As Integer) End Sub Protected Sub __ComClassTest1(x As Integer) End Sub Friend Sub _ComClassTest1(x As Integer, y As Integer) End Sub Friend Sub __ComClassTest1(x As Integer, y As Integer) End Sub Protected Friend Sub _ComClassTest1(x As Integer, y As Integer, z As Integer) End Sub Protected Friend Sub __ComClassTest1(x As Integer, y As Integer, z As Integer) End Sub Public Sub _ComClassTest1(x As Long) End Sub Public Sub __ComClassTest1(x As Long) End Sub End Class <Microsoft.VisualBasic.ComClass(InterfaceShadows:=True)> Public Class ComClassTest1 Inherits ComClassBase Public Sub Goo() End Sub Public Event E1() End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll) Dim expected = <expected> </expected> AssertTheseDeclarationDiagnostics(compilation, expected) AssertTheseDiagnostics(compilation, expected) End Sub <Fact> Public Sub Test_WRN_ComClassPropertySetObject1() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest1 Public Property P1 As Object Get Return Nothing End Get Set(value As Object) End Set End Property Public WriteOnly Property P2 As Object Set(value As Object) End Set End Property Public ReadOnly Property P3 As Object Get Return Nothing End Get End Property End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll) Dim expected = <expected> BC42102: 'Public Property P1 As Object' cannot be exposed to COM as a property 'Let'. You will not be able to assign non-object values (such as numbers or strings) to this property from Visual Basic 6.0 using a 'Let' statement. Public Property P1 As Object ~~ BC42102: 'Public WriteOnly Property P2 As Object' cannot be exposed to COM as a property 'Let'. You will not be able to assign non-object values (such as numbers or strings) to this property from Visual Basic 6.0 using a 'Let' statement. Public WriteOnly Property P2 As Object ~~ </expected> AssertTheseDeclarationDiagnostics(compilation, expected) AssertTheseDiagnostics(compilation, expected) End Sub <Fact> Public Sub Test_ERR_ComClassGenericMethod() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest1 Public Sub Goo(Of T)() End Sub End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll) Dim expected = <expected> BC30943: Generic methods cannot be exposed to COM. Public Sub Goo(Of T)() ~~~ </expected> AssertTheseDeclarationDiagnostics(compilation, expected) AssertTheseDiagnostics(compilation, expected) End Sub <Fact()> Public Sub ComClassWithWarnings() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Public Class ComClassBase Public Sub _ComClassTest1() End Sub Public Sub __ComClassTest1() End Sub End Class <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest1 Inherits ComClassBase Public Sub M1() End Sub Public Event E1() Public WriteOnly Property P2 As Object Set(value As Object) End Set End Property End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest1"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <System.Runtime.InteropServices.ComSourceInterfacesAttribute> <ctor>Sub System.Runtime.InteropServices.ComSourceInterfacesAttribute..ctor(sourceInterfaces As System.String)</ctor> <a>ComClassTest1+__ComClassTest1</a> </System.Runtime.InteropServices.ComSourceInterfacesAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest1._ComClassTest1</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest1._ComClassTest1.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="add_E1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>ComClassTest1.E1EventHandler</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="remove_E1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>ComClassTest1.E1EventHandler</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="set_P2" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest1._ComClassTest1.set_P2(value As System.Object)</Implements> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Object</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P2"> <PropertyFlags></PropertyFlags> <Set>Sub ComClassTest1.set_P2(value As System.Object)</Set> </Property> <Event Name="E1"> <EventFlags></EventFlags> <Add>Sub ComClassTest1.add_E1(obj As ComClassTest1.E1EventHandler)</Add> <Remove>Sub ComClassTest1.remove_E1(obj As ComClassTest1.E1EventHandler)</Remove> </Event> <Interface Name="_ComClassTest1"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="set_P2" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Object</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P2"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Set>Sub ComClassTest1._ComClassTest1.set_P2(value As System.Object)</Set> </Property> </Interface> <Interface Name="__ComClassTest1"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.InterfaceTypeAttribute> <ctor>Sub System.Runtime.InteropServices.InterfaceTypeAttribute..ctor(interfaceType As System.Int16)</ctor> <a>2</a> </System.Runtime.InteropServices.InterfaceTypeAttribute> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="E1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest1")) End Sub) Dim warnings = <expected> BC42101: 'Microsoft.VisualBasic.ComClassAttribute' on class 'ComClassTest1' implicitly declares Interface '__ComClassTest1', which conflicts with a member of the same name in Class 'ComClassBase'. Use 'Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)' if you want to hide the name on the base ComClassBase. Public Class ComClassTest1 ~~~~~~~~~~~~~ BC42101: 'Microsoft.VisualBasic.ComClassAttribute' on class 'ComClassTest1' implicitly declares Interface '_ComClassTest1', which conflicts with a member of the same name in Class 'ComClassBase'. Use 'Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)' if you want to hide the name on the base ComClassBase. Public Class ComClassTest1 ~~~~~~~~~~~~~ BC42102: 'Public WriteOnly Property P2 As Object' cannot be exposed to COM as a property 'Let'. You will not be able to assign non-object values (such as numbers or strings) to this property from Visual Basic 6.0 using a 'Let' statement. Public WriteOnly Property P2 As Object ~~ </expected> AssertTheseDiagnostics(verifier.Compilation, warnings) End Sub <Fact> Public Sub Test_ERR_InvalidAttributeUsage2() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Module ComClassTest1 Public Sub M1() End Sub End Module ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll) Dim expected = <expected> BC30662: Attribute 'ComClassAttribute' cannot be applied to 'ComClassTest1' because the attribute is not valid on this declaration type. Public Module ComClassTest1 ~~~~~~~~~~~~~ </expected> AssertTheseDeclarationDiagnostics(compilation, expected) AssertTheseDiagnostics(compilation, expected) End Sub <Fact()> Public Sub ComInvisibleMembers() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest <ComVisible(False)> Public Sub M1(Of T)() End Sub Public Sub M2() End Sub <ComVisible(False)> Public Property P1 As Integer Get Return 0 End Get Set(value As Integer) End Set End Property Public Property P2 As Integer <ComVisible(False)> Get Return 0 End Get Set(value As Integer) End Set End Property Public Property P3 As Integer Get Return 0 End Get <ComVisible(False)> Set(value As Integer) End Set End Property Public ReadOnly Property P4 As Integer <ComVisible(False)> Get Return 0 End Get End Property Public WriteOnly Property P5 As Integer <ComVisible(False)> Set(value As Integer) End Set End Property End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="Generic, HasThis"> <MethodFlags>public instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>False</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M2" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M2()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P2" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>False</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P2" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.set_P2(value As System.Int32)</Implements> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P3" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Function ComClassTest._ComClassTest.get_P3() As System.Int32</Implements> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P3" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>False</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P4" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>False</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P5" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>False</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>False</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Get>Function ComClassTest.get_P1() As System.Int32</Get> <Set>Sub ComClassTest.set_P1(value As System.Int32)</Set> </Property> <Property Name="P2"> <PropertyFlags></PropertyFlags> <Get>Function ComClassTest.get_P2() As System.Int32</Get> <Set>Sub ComClassTest.set_P2(value As System.Int32)</Set> </Property> <Property Name="P3"> <PropertyFlags></PropertyFlags> <Get>Function ComClassTest.get_P3() As System.Int32</Get> <Set>Sub ComClassTest.set_P3(value As System.Int32)</Set> </Property> <Property Name="P4"> <PropertyFlags></PropertyFlags> <Get>Function ComClassTest.get_P4() As System.Int32</Get> </Property> <Property Name="P5"> <PropertyFlags></PropertyFlags> <Set>Sub ComClassTest.set_P5(value As System.Int32)</Set> </Property> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="M2" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="set_P2" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P3" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>3</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Integer</Type> </Return> </Method> <Property Name="P2"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Set>Sub ComClassTest._ComClassTest.set_P2(value As System.Int32)</Set> </Property> <Property Name="P3"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>3</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest._ComClassTest.get_P3() As System.Int32</Get> </Property> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub).VerifyDiagnostics() End Sub <Fact()> Public Sub GuidAttributeTest1() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ <Microsoft.VisualBasic.ComClass("", "7666AC25-855F-4534-BC55-27BF09D49D46", "")> Public Class ComClassTest Public Sub M1() End Sub Public Event E1() End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <System.Runtime.InteropServices.ComSourceInterfacesAttribute> <ctor>Sub System.Runtime.InteropServices.ComSourceInterfacesAttribute..ctor(sourceInterfaces As System.String)</ctor> <a>ComClassTest+__ComClassTest</a> </System.Runtime.InteropServices.ComSourceInterfacesAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor(_ClassID As System.String, _InterfaceID As System.String, _EventId As System.String)</ctor> <a></a> <a>7666AC25-855F-4534-BC55-27BF09D49D46</a> <a></a> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="add_E1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>ComClassTest.E1EventHandler</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="remove_E1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>ComClassTest.E1EventHandler</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Event Name="E1"> <EventFlags></EventFlags> <Add>Sub ComClassTest.add_E1(obj As ComClassTest.E1EventHandler)</Add> <Remove>Sub ComClassTest.remove_E1(obj As ComClassTest.E1EventHandler)</Remove> </Event> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.GuidAttribute> <ctor>Sub System.Runtime.InteropServices.GuidAttribute..ctor(guid As System.String)</ctor> <a>7666AC25-855F-4534-BC55-27BF09D49D46</a> </System.Runtime.InteropServices.GuidAttribute> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> </Interface> <Interface Name="__ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.InterfaceTypeAttribute> <ctor>Sub System.Runtime.InteropServices.InterfaceTypeAttribute..ctor(interfaceType As System.Int16)</ctor> <a>2</a> </System.Runtime.InteropServices.InterfaceTypeAttribute> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="E1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub).VerifyDiagnostics() End Sub <Fact()> Public Sub GuidAttributeTest2() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ <Microsoft.VisualBasic.ComClass("", "", "7666AC25-855F-4534-BC55-27BF09D49D46")> Public Class ComClassTest Public Sub M1() End Sub Public Event E1() End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <System.Runtime.InteropServices.ComSourceInterfacesAttribute> <ctor>Sub System.Runtime.InteropServices.ComSourceInterfacesAttribute..ctor(sourceInterfaces As System.String)</ctor> <a>ComClassTest+__ComClassTest</a> </System.Runtime.InteropServices.ComSourceInterfacesAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor(_ClassID As System.String, _InterfaceID As System.String, _EventId As System.String)</ctor> <a></a> <a></a> <a>7666AC25-855F-4534-BC55-27BF09D49D46</a> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="add_E1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>ComClassTest.E1EventHandler</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="remove_E1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>ComClassTest.E1EventHandler</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Event Name="E1"> <EventFlags></EventFlags> <Add>Sub ComClassTest.add_E1(obj As ComClassTest.E1EventHandler)</Add> <Remove>Sub ComClassTest.remove_E1(obj As ComClassTest.E1EventHandler)</Remove> </Event> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> </Interface> <Interface Name="__ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.GuidAttribute> <ctor>Sub System.Runtime.InteropServices.GuidAttribute..ctor(guid As System.String)</ctor> <a>7666AC25-855F-4534-BC55-27BF09D49D46</a> </System.Runtime.InteropServices.GuidAttribute> <System.Runtime.InteropServices.InterfaceTypeAttribute> <ctor>Sub System.Runtime.InteropServices.InterfaceTypeAttribute..ctor(interfaceType As System.Int16)</ctor> <a>2</a> </System.Runtime.InteropServices.InterfaceTypeAttribute> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="E1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub).VerifyDiagnostics() End Sub <Fact()> Public Sub GuidAttributeTest3() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass("{7666AC25-855F-4534-BC55-27BF09D49D44}", "(7666AC25-855F-4534-BC55-27BF09D49D45)", "7666AC25855F4534BC5527BF09D49D46")> Public Class ComClassTest Public Sub M1() End Sub Public Event E1() End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll) Dim expected = <expected> BC32500: 'ComClassAttribute' cannot be applied because the format of the GUID '(7666AC25-855F-4534-BC55-27BF09D49D45)' is not correct. Public Class ComClassTest ~~~~~~~~~~~~ BC32500: 'ComClassAttribute' cannot be applied because the format of the GUID '{7666AC25-855F-4534-BC55-27BF09D49D44}' is not correct. Public Class ComClassTest ~~~~~~~~~~~~ BC32500: 'ComClassAttribute' cannot be applied because the format of the GUID '7666AC25855F4534BC5527BF09D49D46' is not correct. Public Class ComClassTest ~~~~~~~~~~~~ </expected> AssertTheseDeclarationDiagnostics(compilation, expected) AssertTheseDiagnostics(compilation, expected) End Sub <Fact()> Public Sub ComSourceInterfacesAttribute1() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Namespace nS Class Test2 End Class End Namespace Namespace NS Public Class ComClassTest1 Class ComClassTest2 <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest3 Public Event E1() End Class End Class End Class End Namespace Namespace ns Class Test1 End Class End Namespace ]]></file> </compilation> Dim expected = <Class Name="ComClassTest3"> <TypeDefFlags>nested public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <System.Runtime.InteropServices.ComSourceInterfacesAttribute> <ctor>Sub System.Runtime.InteropServices.ComSourceInterfacesAttribute..ctor(sourceInterfaces As System.String)</ctor> <a>NS.ComClassTest1+ComClassTest2+ComClassTest3+__ComClassTest3</a> </System.Runtime.InteropServices.ComSourceInterfacesAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>NS.ComClassTest1.ComClassTest2.ComClassTest3._ComClassTest3</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="add_E1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>NS.ComClassTest1.ComClassTest2.ComClassTest3.E1EventHandler</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="remove_E1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>NS.ComClassTest1.ComClassTest2.ComClassTest3.E1EventHandler</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Event Name="E1"> <EventFlags></EventFlags> <Add>Sub NS.ComClassTest1.ComClassTest2.ComClassTest3.add_E1(obj As NS.ComClassTest1.ComClassTest2.ComClassTest3.E1EventHandler)</Add> <Remove>Sub NS.ComClassTest1.ComClassTest2.ComClassTest3.remove_E1(obj As NS.ComClassTest1.ComClassTest2.ComClassTest3.E1EventHandler)</Remove> </Event> <Interface Name="_ComClassTest3"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> </Interface> <Interface Name="__ComClassTest3"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.InterfaceTypeAttribute> <ctor>Sub System.Runtime.InteropServices.InterfaceTypeAttribute..ctor(interfaceType As System.Int16)</ctor> <a>2</a> </System.Runtime.InteropServices.InterfaceTypeAttribute> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="E1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "NS.ComClassTest1+ComClassTest2+ComClassTest3")) End Sub) End Sub <Fact()> Public Sub OrderOfAccessors() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass("", "", "")> Public Class ComClassTest Property P1 As Integer Set(value As Integer) End Set Get Return Nothing End Get End Property End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor(_ClassID As System.String, _InterfaceID As System.String, _EventId As System.String)</ctor> <a></a> <a></a> <a></a> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.set_P1(value As System.Int32)</Implements> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Function ComClassTest._ComClassTest.get_P1() As System.Int32</Implements> <Return> <Type>Integer</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Get>Function ComClassTest.get_P1() As System.Int32</Get> <Set>Sub ComClassTest.set_P1(value As System.Int32)</Set> </Property> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Integer</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest._ComClassTest.get_P1() As System.Int32</Get> <Set>Sub ComClassTest._ComClassTest.set_P1(value As System.Int32)</Set> </Property> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub) End Sub <Fact()> Public Sub DispId1() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest Sub M1() End Sub <DispId(15)> Sub M2() End Sub Sub M3() End Sub Event E1 As Action <DispId(16)> Event E2 As Action Event E3 As Action End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <System.Runtime.InteropServices.ComSourceInterfacesAttribute> <ctor>Sub System.Runtime.InteropServices.ComSourceInterfacesAttribute..ctor(sourceInterfaces As System.String)</ctor> <a>ComClassTest+__ComClassTest</a> </System.Runtime.InteropServices.ComSourceInterfacesAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M2" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Implements>Sub ComClassTest._ComClassTest.M2()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M3()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="add_E1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>System.Action</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="remove_E1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>System.Action</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="add_E2" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>System.Action</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="remove_E2" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>System.Action</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="add_E3" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>System.Action</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="remove_E3" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>System.Action</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Event Name="E1"> <EventFlags></EventFlags> <Add>Sub ComClassTest.add_E1(obj As System.Action)</Add> <Remove>Sub ComClassTest.remove_E1(obj As System.Action)</Remove> </Event> <Event Name="E2"> <EventFlags></EventFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>16</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Add>Sub ComClassTest.add_E2(obj As System.Action)</Add> <Remove>Sub ComClassTest.remove_E2(obj As System.Action)</Remove> </Event> <Event Name="E3"> <EventFlags></EventFlags> <Add>Sub ComClassTest.add_E3(obj As System.Action)</Add> <Remove>Sub ComClassTest.remove_E3(obj As System.Action)</Remove> </Event> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M2" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> </Interface> <Interface Name="__ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.InterfaceTypeAttribute> <ctor>Sub System.Runtime.InteropServices.InterfaceTypeAttribute..ctor(interfaceType As System.Int16)</ctor> <a>2</a> </System.Runtime.InteropServices.InterfaceTypeAttribute> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="E1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="E2" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>16</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="E3" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub) End Sub <Fact()> Public Sub DispId2() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest Sub M1() End Sub <DispId(1)> Sub M2() End Sub <DispId(3)> Friend Sub M3() End Sub Sub M4() End Sub Event E1 As Action <DispId(2)> Event E2 As Action <DispId(3)> Friend Event E3 As Action Event E4 As Action End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <System.Runtime.InteropServices.ComSourceInterfacesAttribute> <ctor>Sub System.Runtime.InteropServices.ComSourceInterfacesAttribute..ctor(sourceInterfaces As System.String)</ctor> <a>ComClassTest+__ComClassTest</a> </System.Runtime.InteropServices.ComSourceInterfacesAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M2" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Implements>Sub ComClassTest._ComClassTest.M2()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>assembly instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>3</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M4" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M4()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="add_E1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>System.Action</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="remove_E1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>System.Action</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="add_E2" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>System.Action</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="remove_E2" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>System.Action</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="add_E3" CallingConvention="HasThis"> <MethodFlags>assembly specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>System.Action</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="remove_E3" CallingConvention="HasThis"> <MethodFlags>assembly specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>System.Action</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="add_E4" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>System.Action</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="remove_E4" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>System.Action</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Event Name="E1"> <EventFlags></EventFlags> <Add>Sub ComClassTest.add_E1(obj As System.Action)</Add> <Remove>Sub ComClassTest.remove_E1(obj As System.Action)</Remove> </Event> <Event Name="E2"> <EventFlags></EventFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Add>Sub ComClassTest.add_E2(obj As System.Action)</Add> <Remove>Sub ComClassTest.remove_E2(obj As System.Action)</Remove> </Event> <Event Name="E3"> <EventFlags></EventFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>3</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Add>Sub ComClassTest.add_E3(obj As System.Action)</Add> <Remove>Sub ComClassTest.remove_E3(obj As System.Action)</Remove> </Event> <Event Name="E4"> <EventFlags></EventFlags> <Add>Sub ComClassTest.add_E4(obj As System.Action)</Add> <Remove>Sub ComClassTest.remove_E4(obj As System.Action)</Remove> </Event> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M2" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M4" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>3</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> </Interface> <Interface Name="__ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.InterfaceTypeAttribute> <ctor>Sub System.Runtime.InteropServices.InterfaceTypeAttribute..ctor(interfaceType As System.Int16)</ctor> <a>2</a> </System.Runtime.InteropServices.InterfaceTypeAttribute> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="E1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="E2" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="E4" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>3</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub) End Sub <Fact()> Public Sub DispId3() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest Sub M1() End Sub <DispId(15)> Property P1 As Integer <DispId(16)> Get Return 0 End Get Set(value As Integer) End Set End Property Sub M3() End Sub End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>16</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Implements>Function ComClassTest._ComClassTest.get_P1() As System.Int32</Implements> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.set_P1(value As System.Int32)</Implements> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M3()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest.get_P1() As System.Int32</Get> <Set>Sub ComClassTest.set_P1(value As System.Int32)</Set> </Property> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>16</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>3</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest._ComClassTest.get_P1() As System.Int32</Get> <Set>Sub ComClassTest._ComClassTest.set_P1(value As System.Int32)</Set> </Property> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub) End Sub <Fact()> Public Sub DispId4() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest Sub M1() End Sub <DispId(15)> Property P1 As Integer Get Return 0 End Get <DispId(16)> Set(value As Integer) End Set End Property Sub M3() End Sub End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Function ComClassTest._ComClassTest.get_P1() As System.Int32</Implements> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>16</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Implements>Sub ComClassTest._ComClassTest.set_P1(value As System.Int32)</Implements> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M3()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest.get_P1() As System.Int32</Get> <Set>Sub ComClassTest.set_P1(value As System.Int32)</Set> </Property> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>16</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>3</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest._ComClassTest.get_P1() As System.Int32</Get> <Set>Sub ComClassTest._ComClassTest.set_P1(value As System.Int32)</Set> </Property> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub) End Sub <Fact()> Public Sub DispId5() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest Sub M1() End Sub Property P1 As Integer <DispId(15)> Get Return 0 End Get <DispId(16)> Set(value As Integer) End Set End Property Sub M3() End Sub End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Implements>Function ComClassTest._ComClassTest.get_P1() As System.Int32</Implements> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>16</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Implements>Sub ComClassTest._ComClassTest.set_P1(value As System.Int32)</Implements> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M3()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Get>Function ComClassTest.get_P1() As System.Int32</Get> <Set>Sub ComClassTest.set_P1(value As System.Int32)</Set> </Property> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>16</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>3</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest._ComClassTest.get_P1() As System.Int32</Get> <Set>Sub ComClassTest._ComClassTest.set_P1(value As System.Int32)</Set> </Property> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub) End Sub <Fact()> Public Sub DispId6() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest Sub M1() End Sub <DispId(17)> Property P1 As Integer <DispId(15)> Get Return 0 End Get <DispId(16)> Set(value As Integer) End Set End Property Sub M3() End Sub End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Implements>Function ComClassTest._ComClassTest.get_P1() As System.Int32</Implements> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>16</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Implements>Sub ComClassTest._ComClassTest.set_P1(value As System.Int32)</Implements> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M3()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>17</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest.get_P1() As System.Int32</Get> <Set>Sub ComClassTest.set_P1(value As System.Int32)</Set> </Property> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>16</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>17</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest._ComClassTest.get_P1() As System.Int32</Get> <Set>Sub ComClassTest._ComClassTest.set_P1(value As System.Int32)</Set> </Property> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub) End Sub <Fact()> Public Sub DispId7() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest Sub M1() End Sub <DispId(15)> Default Property P1(x As Integer) As Integer <DispId(16)> Get Return 0 End Get Set(value As Integer) End Set End Property Sub M3() End Sub End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Reflection.DefaultMemberAttribute> <ctor>Sub System.Reflection.DefaultMemberAttribute..ctor(memberName As System.String)</ctor> <a>P1</a> </System.Reflection.DefaultMemberAttribute> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>16</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Implements>Function ComClassTest._ComClassTest.get_P1(x As System.Int32) As System.Int32</Implements> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.set_P1(x As System.Int32, value As System.Int32)</Implements> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M3()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest.get_P1(x As System.Int32) As System.Int32</Get> <Set>Sub ComClassTest.set_P1(x As System.Int32, value As System.Int32)</Set> </Property> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> <System.Reflection.DefaultMemberAttribute> <ctor>Sub System.Reflection.DefaultMemberAttribute..ctor(memberName As System.String)</ctor> <a>P1</a> </System.Reflection.DefaultMemberAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>16</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>0</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>3</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest._ComClassTest.get_P1(x As System.Int32) As System.Int32</Get> <Set>Sub ComClassTest._ComClassTest.set_P1(x As System.Int32, value As System.Int32)</Set> </Property> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub) End Sub <Fact()> Public Sub DispId8() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest Sub M1() End Sub <DispId(15)> Default Property P1(x As Integer) As Integer Get Return 0 End Get <DispId(16)> Set(value As Integer) End Set End Property Sub M3() End Sub End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Reflection.DefaultMemberAttribute> <ctor>Sub System.Reflection.DefaultMemberAttribute..ctor(memberName As System.String)</ctor> <a>P1</a> </System.Reflection.DefaultMemberAttribute> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Function ComClassTest._ComClassTest.get_P1(x As System.Int32) As System.Int32</Implements> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>16</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Implements>Sub ComClassTest._ComClassTest.set_P1(x As System.Int32, value As System.Int32)</Implements> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M3()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest.get_P1(x As System.Int32) As System.Int32</Get> <Set>Sub ComClassTest.set_P1(x As System.Int32, value As System.Int32)</Set> </Property> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> <System.Reflection.DefaultMemberAttribute> <ctor>Sub System.Reflection.DefaultMemberAttribute..ctor(memberName As System.String)</ctor> <a>P1</a> </System.Reflection.DefaultMemberAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>0</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>16</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>3</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest._ComClassTest.get_P1(x As System.Int32) As System.Int32</Get> <Set>Sub ComClassTest._ComClassTest.set_P1(x As System.Int32, value As System.Int32)</Set> </Property> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub) End Sub <Fact()> Public Sub DispId9() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest Sub M1() End Sub Default Property P1(x As Integer) As Integer <DispId(15)> Get Return 0 End Get <DispId(16)> Set(value As Integer) End Set End Property Sub M3() End Sub End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Reflection.DefaultMemberAttribute> <ctor>Sub System.Reflection.DefaultMemberAttribute..ctor(memberName As System.String)</ctor> <a>P1</a> </System.Reflection.DefaultMemberAttribute> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Implements>Function ComClassTest._ComClassTest.get_P1(x As System.Int32) As System.Int32</Implements> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>16</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Implements>Sub ComClassTest._ComClassTest.set_P1(x As System.Int32, value As System.Int32)</Implements> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M3()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Get>Function ComClassTest.get_P1(x As System.Int32) As System.Int32</Get> <Set>Sub ComClassTest.set_P1(x As System.Int32, value As System.Int32)</Set> </Property> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> <System.Reflection.DefaultMemberAttribute> <ctor>Sub System.Reflection.DefaultMemberAttribute..ctor(memberName As System.String)</ctor> <a>P1</a> </System.Reflection.DefaultMemberAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>16</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>3</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>0</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest._ComClassTest.get_P1(x As System.Int32) As System.Int32</Get> <Set>Sub ComClassTest._ComClassTest.set_P1(x As System.Int32, value As System.Int32)</Set> </Property> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub) End Sub <Fact()> Public Sub DispId10() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest Sub M1() End Sub <DispId(17)> Default Property P1(x As Integer) As Integer <DispId(15)> Get Return 0 End Get <DispId(16)> Set(value As Integer) End Set End Property Sub M3() End Sub End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Reflection.DefaultMemberAttribute> <ctor>Sub System.Reflection.DefaultMemberAttribute..ctor(memberName As System.String)</ctor> <a>P1</a> </System.Reflection.DefaultMemberAttribute> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Implements>Function ComClassTest._ComClassTest.get_P1(x As System.Int32) As System.Int32</Implements> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>16</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Implements>Sub ComClassTest._ComClassTest.set_P1(x As System.Int32, value As System.Int32)</Implements> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M3()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>17</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest.get_P1(x As System.Int32) As System.Int32</Get> <Set>Sub ComClassTest.set_P1(x As System.Int32, value As System.Int32)</Set> </Property> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> <System.Reflection.DefaultMemberAttribute> <ctor>Sub System.Reflection.DefaultMemberAttribute..ctor(memberName As System.String)</ctor> <a>P1</a> </System.Reflection.DefaultMemberAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>16</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>17</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest._ComClassTest.get_P1(x As System.Int32) As System.Int32</Get> <Set>Sub ComClassTest._ComClassTest.set_P1(x As System.Int32, value As System.Int32)</Set> </Property> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub) End Sub <Fact()> Public Sub DispId11() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest Sub M1() End Sub <DispId(17)> Default ReadOnly Property P1(x As Integer) As Integer <DispId(15)> Get Return 0 End Get End Property Sub M3() End Sub End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Reflection.DefaultMemberAttribute> <ctor>Sub System.Reflection.DefaultMemberAttribute..ctor(memberName As System.String)</ctor> <a>P1</a> </System.Reflection.DefaultMemberAttribute> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Implements>Function ComClassTest._ComClassTest.get_P1(x As System.Int32) As System.Int32</Implements> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M3()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>17</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest.get_P1(x As System.Int32) As System.Int32</Get> </Property> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> <System.Reflection.DefaultMemberAttribute> <ctor>Sub System.Reflection.DefaultMemberAttribute..ctor(memberName As System.String)</ctor> <a>P1</a> </System.Reflection.DefaultMemberAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>17</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest._ComClassTest.get_P1(x As System.Int32) As System.Int32</Get> </Property> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub) End Sub <Fact()> Public Sub DispId12() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest Sub M1() End Sub <DispId(17)> Default WriteOnly Property P1(x As Integer) As Integer <DispId(16)> Set(value As Integer) End Set End Property Sub M3() End Sub End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Reflection.DefaultMemberAttribute> <ctor>Sub System.Reflection.DefaultMemberAttribute..ctor(memberName As System.String)</ctor> <a>P1</a> </System.Reflection.DefaultMemberAttribute> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>16</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Implements>Sub ComClassTest._ComClassTest.set_P1(x As System.Int32, value As System.Int32)</Implements> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M3()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>17</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Set>Sub ComClassTest.set_P1(x As System.Int32, value As System.Int32)</Set> </Property> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> <System.Reflection.DefaultMemberAttribute> <ctor>Sub System.Reflection.DefaultMemberAttribute..ctor(memberName As System.String)</ctor> <a>P1</a> </System.Reflection.DefaultMemberAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>16</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>17</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Set>Sub ComClassTest._ComClassTest.set_P1(x As System.Int32, value As System.Int32)</Set> </Property> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub) End Sub <Fact()> Public Sub DispId13() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest Sub M1() End Sub Function GetEnumerator() As Collections.IEnumerator Return Nothing End Function Sub M3() End Sub End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="GetEnumerator" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Function ComClassTest._ComClassTest.GetEnumerator() As System.Collections.IEnumerator</Implements> <Return> <Type>System.Collections.IEnumerator</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M3()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="GetEnumerator" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>-4</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>System.Collections.IEnumerator</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>3</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub) End Sub <Fact()> Public Sub DispId14() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest Sub M1() End Sub <DispId(13)> Function GetEnumerator() As Collections.IEnumerator Return Nothing End Function Sub M3() End Sub End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="GetEnumerator" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>13</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Implements>Function ComClassTest._ComClassTest.GetEnumerator() As System.Collections.IEnumerator</Implements> <Return> <Type>System.Collections.IEnumerator</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M3()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="GetEnumerator" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>13</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>System.Collections.IEnumerator</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub) End Sub <Fact()> Public Sub DispId15() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest Function GetEnumerator(Optional x As Integer = 0) As Collections.IEnumerator Return Nothing End Function Sub GetEnumerator() End Sub End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="GetEnumerator" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Function ComClassTest._ComClassTest.GetEnumerator([x As System.Int32 = 0]) As System.Collections.IEnumerator</Implements> <Parameter Name="x"> <ParamFlags>[opt] default</ParamFlags> <Type>Integer</Type> <Default>0</Default> </Parameter> <Return> <Type>System.Collections.IEnumerator</Type> </Return> </Method> <Method Name="GetEnumerator" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.GetEnumerator()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="GetEnumerator" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="x"> <ParamFlags>[opt] default</ParamFlags> <Type>Integer</Type> <Default>0</Default> </Parameter> <Return> <Type>System.Collections.IEnumerator</Type> </Return> </Method> <Method Name="GetEnumerator" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub) End Sub <Fact()> Public Sub DispId16() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest Function GetEnumerator() As Integer Return Nothing End Function End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="GetEnumerator" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Function ComClassTest._ComClassTest.GetEnumerator() As System.Int32</Implements> <Return> <Type>Integer</Type> </Return> </Method> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="GetEnumerator" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Integer</Type> </Return> </Method> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub) End Sub <Fact()> Public Sub DispId17() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest ReadOnly Property GetEnumerator() As Collections.IEnumerator Get Return Nothing End Get End Property ReadOnly Property GetEnumerator(Optional x As Integer = 0) As Collections.IEnumerator Get Return Nothing End Get End Property End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_GetEnumerator" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Function ComClassTest._ComClassTest.get_GetEnumerator() As System.Collections.IEnumerator</Implements> <Return> <Type>System.Collections.IEnumerator</Type> </Return> </Method> <Method Name="get_GetEnumerator" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Function ComClassTest._ComClassTest.get_GetEnumerator([x As System.Int32 = 0]) As System.Collections.IEnumerator</Implements> <Parameter Name="x"> <ParamFlags>[opt] default</ParamFlags> <Type>Integer</Type> <Default>0</Default> </Parameter> <Return> <Type>System.Collections.IEnumerator</Type> </Return> </Method> <Property Name="GetEnumerator"> <PropertyFlags></PropertyFlags> <Get>Function ComClassTest.get_GetEnumerator() As System.Collections.IEnumerator</Get> </Property> <Property Name="GetEnumerator"> <PropertyFlags></PropertyFlags> <Get>Function ComClassTest.get_GetEnumerator([x As System.Int32 = 0]) As System.Collections.IEnumerator</Get> </Property> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="get_GetEnumerator" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>-4</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>System.Collections.IEnumerator</Type> </Return> </Method> <Method Name="get_GetEnumerator" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="x"> <ParamFlags>[opt] default</ParamFlags> <Type>Integer</Type> <Default>0</Default> </Parameter> <Return> <Type>System.Collections.IEnumerator</Type> </Return> </Method> <Property Name="GetEnumerator"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>-4</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest._ComClassTest.get_GetEnumerator() As System.Collections.IEnumerator</Get> </Property> <Property Name="GetEnumerator"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest._ComClassTest.get_GetEnumerator([x As System.Int32 = 0]) As System.Collections.IEnumerator</Get> </Property> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub) End Sub <Fact()> Public Sub DefaultProperty1() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System <Microsoft.VisualBasic.ComClass()> <Reflection.DefaultMember("p1")> Public Class ComClassTest Default ReadOnly Property P1(x As Integer) As Integer Get Return Nothing End Get End Property Event E1 As Action End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <System.Runtime.InteropServices.ComSourceInterfacesAttribute> <ctor>Sub System.Runtime.InteropServices.ComSourceInterfacesAttribute..ctor(sourceInterfaces As System.String)</ctor> <a>ComClassTest+__ComClassTest</a> </System.Runtime.InteropServices.ComSourceInterfacesAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> <System.Reflection.DefaultMemberAttribute> <ctor>Sub System.Reflection.DefaultMemberAttribute..ctor(memberName As System.String)</ctor> <a>p1</a> </System.Reflection.DefaultMemberAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Function ComClassTest._ComClassTest.get_P1(x As System.Int32) As System.Int32</Implements> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="add_E1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>System.Action</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="remove_E1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>System.Action</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Get>Function ComClassTest.get_P1(x As System.Int32) As System.Int32</Get> </Property> <Event Name="E1"> <EventFlags></EventFlags> <Add>Sub ComClassTest.add_E1(obj As System.Action)</Add> <Remove>Sub ComClassTest.remove_E1(obj As System.Action)</Remove> </Event> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> <System.Reflection.DefaultMemberAttribute> <ctor>Sub System.Reflection.DefaultMemberAttribute..ctor(memberName As System.String)</ctor> <a>P1</a> </System.Reflection.DefaultMemberAttribute> </Attributes> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>0</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Integer</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>0</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest._ComClassTest.get_P1(x As System.Int32) As System.Int32</Get> </Property> </Interface> <Interface Name="__ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.InterfaceTypeAttribute> <ctor>Sub System.Runtime.InteropServices.InterfaceTypeAttribute..ctor(interfaceType As System.Int16)</ctor> <a>2</a> </System.Runtime.InteropServices.InterfaceTypeAttribute> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="E1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub).VerifyDiagnostics() End Sub <Fact()> Public Sub DispId18() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest <DispId(0)> ReadOnly Property P1(x As Integer) As Integer Get Return Nothing End Get End Property <DispId(-1)> Sub M1() End Sub <DispId(-2)> Event E1 As Action End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll) AssertTheseDeclarationDiagnostics(compilation, <expected> BC32505: 'System.Runtime.InteropServices.DispIdAttribute' cannot be applied to 'P1' because 'Microsoft.VisualBasic.ComClassAttribute' reserves zero for the default property. ReadOnly Property P1(x As Integer) As Integer ~~ BC32506: 'System.Runtime.InteropServices.DispIdAttribute' cannot be applied to 'M1' because 'Microsoft.VisualBasic.ComClassAttribute' reserves values less than zero. Sub M1() ~~ BC32506: 'System.Runtime.InteropServices.DispIdAttribute' cannot be applied to 'E1' because 'Microsoft.VisualBasic.ComClassAttribute' reserves values less than zero. Event E1 As Action ~~ </expected>) End Sub <Fact()> Public Sub DispId19() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest <DispId(0)> Sub M1() End Sub <DispId(0)> Event E1 As Action End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll) AssertTheseDeclarationDiagnostics(compilation, <expected> BC32505: 'System.Runtime.InteropServices.DispIdAttribute' cannot be applied to 'M1' because 'Microsoft.VisualBasic.ComClassAttribute' reserves zero for the default property. Sub M1() ~~ BC32505: 'System.Runtime.InteropServices.DispIdAttribute' cannot be applied to 'E1' because 'Microsoft.VisualBasic.ComClassAttribute' reserves zero for the default property. Event E1 As Action ~~ </expected>) End Sub <Fact()> Public Sub DefaultProperty2() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest <DispId(0)> Default ReadOnly Property P1(x As Integer) As Integer Get Return Nothing End Get End Property End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Reflection.DefaultMemberAttribute> <ctor>Sub System.Reflection.DefaultMemberAttribute..ctor(memberName As System.String)</ctor> <a>P1</a> </System.Reflection.DefaultMemberAttribute> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Function ComClassTest._ComClassTest.get_P1(x As System.Int32) As System.Int32</Implements> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Integer</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>0</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest.get_P1(x As System.Int32) As System.Int32</Get> </Property> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> <System.Reflection.DefaultMemberAttribute> <ctor>Sub System.Reflection.DefaultMemberAttribute..ctor(memberName As System.String)</ctor> <a>P1</a> </System.Reflection.DefaultMemberAttribute> </Attributes> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>0</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Integer</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>0</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest._ComClassTest.get_P1(x As System.Int32) As System.Int32</Get> </Property> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub).VerifyDiagnostics() End Sub <Fact()> Public Sub Serializable_and_SpecialName() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System <Microsoft.VisualBasic.ComClass()> <Serializable()> <System.Runtime.CompilerServices.SpecialName()> Public Class ComClassTest <System.Runtime.CompilerServices.SpecialName()> Sub M1() End Sub <System.Runtime.CompilerServices.SpecialName()> Event E1 As Action <System.Runtime.CompilerServices.SpecialName()> Property P1 As Integer Get Return 0 End Get Set(value As Integer) End Set End Property Property P2 As Integer <System.Runtime.CompilerServices.SpecialName()> Get Return 0 End Get <System.Runtime.CompilerServices.SpecialName()> Set(value As Integer) End Set End Property End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi serializable specialname</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <System.Runtime.InteropServices.ComSourceInterfacesAttribute> <ctor>Sub System.Runtime.InteropServices.ComSourceInterfacesAttribute..ctor(sourceInterfaces As System.String)</ctor> <a>ComClassTest+__ComClassTest</a> </System.Runtime.InteropServices.ComSourceInterfacesAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="add_E1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>System.Action</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="remove_E1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>System.Action</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Function ComClassTest._ComClassTest.get_P1() As System.Int32</Implements> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.set_P1(value As System.Int32)</Implements> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P2" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Function ComClassTest._ComClassTest.get_P2() As System.Int32</Implements> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P2" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.set_P2(value As System.Int32)</Implements> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags>specialname</PropertyFlags> <Get>Function ComClassTest.get_P1() As System.Int32</Get> <Set>Sub ComClassTest.set_P1(value As System.Int32)</Set> </Property> <Property Name="P2"> <PropertyFlags></PropertyFlags> <Get>Function ComClassTest.get_P2() As System.Int32</Get> <Set>Sub ComClassTest.set_P2(value As System.Int32)</Set> </Property> <Event Name="E1"> <EventFlags>specialname</EventFlags> <Add>Sub ComClassTest.add_E1(obj As System.Action)</Add> <Remove>Sub ComClassTest.remove_E1(obj As System.Action)</Remove> </Event> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P2" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>3</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P2" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>3</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags>specialname</PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest._ComClassTest.get_P1() As System.Int32</Get> <Set>Sub ComClassTest._ComClassTest.set_P1(value As System.Int32)</Set> </Property> <Property Name="P2"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>3</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest._ComClassTest.get_P2() As System.Int32</Get> <Set>Sub ComClassTest._ComClassTest.set_P2(value As System.Int32)</Set> </Property> </Interface> <Interface Name="__ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.InterfaceTypeAttribute> <ctor>Sub System.Runtime.InteropServices.InterfaceTypeAttribute..ctor(interfaceType As System.Int16)</ctor> <a>2</a> </System.Runtime.InteropServices.InterfaceTypeAttribute> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="E1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub).VerifyDiagnostics() End Sub <Fact(), WorkItem(531506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531506")> Public Sub Bug18218() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System.Runtime.InteropServices <Assembly: GuidAttribute("5F025F24-FAEA-4C2F-9EF6-C89A8FC90101")> <Assembly: ComVisible(True)> <Microsoft.VisualBasic.ComClass(ComClass1.ClassId, ComClass1.InterfaceId, ComClass1.EventsId)> Public Class ComClass1 Implements I6 #Region "COM GUIDs" ' These GUIDs provide the COM identity for this class ' and its COM interfaces. If you change them, existing ' clients will no longer be able to access the class. Public Const ClassId As String = "5D025F24-FAEA-4C2F-9EF6-C89A8FC9667F" Public Const InterfaceId As String = "5FDA4272-D6AD-4FA4-AD89-FAB8F0A04512" Public Const EventsId As String = "33241EB2-DFC5-4164-998E-A6577B0DA960" #End Region Public Interface I6 End Interface Public Property Scen1 As String Get Return Nothing End Get Set(ByVal Value As String) End Set End Property End Class ]]></file> </compilation> Dim expected = <Class Name="ComClass1"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.GuidAttribute> <ctor>Sub System.Runtime.InteropServices.GuidAttribute..ctor(guid As System.String)</ctor> <a>5D025F24-FAEA-4C2F-9EF6-C89A8FC9667F</a> </System.Runtime.InteropServices.GuidAttribute> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor(_ClassID As System.String, _InterfaceID As System.String, _EventId As System.String)</ctor> <a>5D025F24-FAEA-4C2F-9EF6-C89A8FC9667F</a> <a>5FDA4272-D6AD-4FA4-AD89-FAB8F0A04512</a> <a>33241EB2-DFC5-4164-998E-A6577B0DA960</a> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClass1._ComClass1</Implements> <Implements>ComClass1.I6</Implements> <Field Name="ClassId"> <FieldFlags>public static literal default</FieldFlags> <Type>String</Type> </Field> <Field Name="InterfaceId"> <FieldFlags>public static literal default</FieldFlags> <Type>String</Type> </Field> <Field Name="EventsId"> <FieldFlags>public static literal default</FieldFlags> <Type>String</Type> </Field> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_Scen1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Function ComClass1._ComClass1.get_Scen1() As System.String</Implements> <Return> <Type>String</Type> </Return> </Method> <Method Name="set_Scen1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClass1._ComClass1.set_Scen1(Value As System.String)</Implements> <Parameter Name="Value"> <ParamFlags></ParamFlags> <Type>String</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Property Name="Scen1"> <PropertyFlags></PropertyFlags> <Get>Function ComClass1.get_Scen1() As System.String</Get> <Set>Sub ComClass1.set_Scen1(Value As System.String)</Set> </Property> <Interface Name="I6"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> </Interface> <Interface Name="_ComClass1"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.GuidAttribute> <ctor>Sub System.Runtime.InteropServices.GuidAttribute..ctor(guid As System.String)</ctor> <a>5FDA4272-D6AD-4FA4-AD89-FAB8F0A04512</a> </System.Runtime.InteropServices.GuidAttribute> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="get_Scen1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>String</Type> </Return> </Method> <Method Name="set_Scen1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="Value"> <ParamFlags></ParamFlags> <Type>String</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Property Name="Scen1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClass1._ComClass1.get_Scen1() As System.String</Get> <Set>Sub ComClass1._ComClass1.set_Scen1(Value As System.String)</Set> </Property> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClass1")) End Sub).VerifyDiagnostics() End Sub <Fact, WorkItem(664574, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/664574")> Public Sub Bug664574() Dim compilationDef = <compilation> <file name="a.vb"><![CDATA[ Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass(ComClass1.ClassId, ComClass1.InterfaceId, ComClass1.EventsId)> Public Class ComClass1 #Region "COM GUIDs" ' These GUIDs provide the COM identity for this class ' and its COM interfaces. If you change them, existing ' clients will no longer be able to access the class. Public Const ClassId As String = "C1F1CEC8-2BDD-4AFC-8E86-FDC8DBEE951B" Public Const InterfaceId As String = "E4174EC8-7EDD-4672-90BA-3D1CFFF76C14" Public Const EventsId As String = "8F12C15B-4CA9-450C-9C85-37E9B74164B8" #End Region Public Function dfoo(<MarshalAs(UnmanagedType.Currency)> ByVal x As Decimal) As <MarshalAs(UnmanagedType.Currency)> Decimal Return x + 1.1D End Function End Class ]]></file> </compilation> Dim expected = <Class Name="ComClass1"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.GuidAttribute> <ctor>Sub System.Runtime.InteropServices.GuidAttribute..ctor(guid As System.String)</ctor> <a>C1F1CEC8-2BDD-4AFC-8E86-FDC8DBEE951B</a> </System.Runtime.InteropServices.GuidAttribute> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor(_ClassID As System.String, _InterfaceID As System.String, _EventId As System.String)</ctor> <a>C1F1CEC8-2BDD-4AFC-8E86-FDC8DBEE951B</a> <a>E4174EC8-7EDD-4672-90BA-3D1CFFF76C14</a> <a>8F12C15B-4CA9-450C-9C85-37E9B74164B8</a> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClass1._ComClass1</Implements> <Method Name="dfoo" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Function ComClass1._ComClass1.dfoo(x As System.Decimal) As System.Decimal</Implements> <Parameter Name="x"> <ParamFlags>marshal</ParamFlags> <Type>Decimal</Type> </Parameter> <Return> <Type>Decimal</Type> <ParamFlags>marshal</ParamFlags> </Return> </Method> <Interface Name="_ComClass1"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.GuidAttribute> <ctor>Sub System.Runtime.InteropServices.GuidAttribute..ctor(guid As System.String)</ctor> <a>E4174EC8-7EDD-4672-90BA-3D1CFFF76C14</a> </System.Runtime.InteropServices.GuidAttribute> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="dfoo" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="x"> <ParamFlags>marshal</ParamFlags> <Type>Decimal</Type> </Parameter> <Return> <Type>Decimal</Type> <ParamFlags>marshal</ParamFlags> </Return> </Method> </Interface> </Class> ' Strip TODO comments from the base-line. For Each d In expected.DescendantNodes.ToArray() Dim comment = TryCast(d, XComment) If comment IsNot Nothing Then comment.Remove() End If Next Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClass1", Function(s) Return s.Kind = SymbolKind.NamedType OrElse s.Name = "dfoo" End Function)) End Sub).VerifyDiagnostics() End Sub <Fact, WorkItem(664583, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/664583")> Public Sub Bug664583() Dim compilationDef = <compilation> <file name="a.vb"><![CDATA[ <Microsoft.VisualBasic.ComClass(ComClass1.ClassId, ComClass1.InterfaceId, ComClass1.EventsId)> Public Class ComClass1 #Region "COM GUIDs" ' These GUIDs provide the COM identity for this class ' and its COM interfaces. If you change them, existing ' clients will no longer be able to access the class. Public Const ClassId As String = "C1F1CEC8-2BDD-4AFC-8E86-FDC8DBEE951B" Public Const InterfaceId As String = "E4174EC8-7EDD-4672-90BA-3D1CFFF76C14" Public Const EventsId As String = "8F12C15B-4CA9-450C-9C85-37E9B74164B8" #End Region Public Readonly Property Goo As Integer Get Return 0 End Get End Property Structure Struct1 Public member1 As Integer Structure Struct2 Public member12 As Integer End Structure End Structure Structure struct2 Public member2 As Integer End Structure End Class ]]></file> </compilation> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim ComClass1_Struct1 = DirectCast(m.ContainingAssembly.GetTypeByMetadataName("ComClass1+Struct1"), PENamedTypeSymbol) Dim ComClass1_Struct1_Struct2 = DirectCast(m.ContainingAssembly.GetTypeByMetadataName("ComClass1+Struct1+Struct2"), PENamedTypeSymbol) Dim ComClass1_struct2 = DirectCast(m.ContainingAssembly.GetTypeByMetadataName("ComClass1+struct2"), PENamedTypeSymbol) Assert.True(MetadataTokens.GetRowNumber(ComClass1_Struct1.Handle) < MetadataTokens.GetRowNumber(ComClass1_Struct1_Struct2.Handle)) Assert.True(MetadataTokens.GetRowNumber(ComClass1_Struct1.Handle) < MetadataTokens.GetRowNumber(ComClass1_struct2.Handle)) Assert.True(MetadataTokens.GetRowNumber(ComClass1_struct2.Handle) < MetadataTokens.GetRowNumber(ComClass1_Struct1_Struct2.Handle)) End Sub).VerifyDiagnostics() End Sub <Fact, WorkItem(700050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700050")> Public Sub Bug700050() Dim compilationDef = <compilation> <file name="a.vb"><![CDATA[ Module Module1 Sub Main() End Sub End Module <Microsoft.VisualBasic.ComClass(ComClass1.ClassId, ComClass1.InterfaceId, ComClass1.EventsId)> Public Class ComClass1 Public Const ClassId As String = "" Public Const InterfaceId As String = "" Public Const EventsId As String = "" Public Sub New() End Sub Public Sub Goo() End Sub Public Property oBrowser As Object ' cannot be exposed to COM as a property 'Let'. You will not be able to assign non-object values (such as numbers or strings) to this property from Visual Basic 6.0 using a 'Let' statement. End Class ]]></file> </compilation> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim _ComClass1 = DirectCast(m.ContainingAssembly.GetTypeByMetadataName("ComClass1+_ComClass1"), PENamedTypeSymbol) Assert.Equal(0, _ComClass1.GetMembers("oBrowser").Length) End Sub).VerifyDiagnostics() End Sub End Class End Namespace
' 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.Reflection.Metadata Imports System.Reflection.Metadata.Ecma335 Imports System.Text Imports System.Xml.Linq Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class ComClassTests Inherits BasicTestBase Private Function ReflectComClass( pm As PEModuleSymbol, comClassName As String, Optional memberFilter As Func(Of Symbol, Boolean) = Nothing ) As XElement Dim type As PENamedTypeSymbol = DirectCast(pm.ContainingAssembly.GetTypeByMetadataName(comClassName), PENamedTypeSymbol) Dim combinedFilter = Function(m As Symbol) Return (memberFilter Is Nothing OrElse memberFilter(m)) AndAlso (m.ContainingSymbol IsNot type OrElse m.Kind <> SymbolKind.NamedType OrElse Not DirectCast(m, NamedTypeSymbol).IsDelegateType()) End Function Return ReflectType(type, combinedFilter) End Function Private Function ReflectType(type As PENamedTypeSymbol, Optional memberFilter As Func(Of Symbol, Boolean) = Nothing) As XElement Dim result = <<%= type.TypeKind.ToString() %> Name=<%= type.Name %>></> Dim typeDefFlags = New StringBuilder() MetadataSignatureHelper.AppendTypeAttributes(typeDefFlags, type.TypeDefFlags) result.Add(<TypeDefFlags><%= typeDefFlags %></TypeDefFlags>) If type.GetAttributes().Length > 0 Then result.Add(ReflectAttributes(type.GetAttributes())) End If For Each [interface] In type.Interfaces result.Add(<Implements><%= [interface].ToTestDisplayString() %></Implements>) Next For Each member In type.GetMembers If memberFilter IsNot Nothing AndAlso Not memberFilter(member) Then Continue For End If Select Case member.Kind Case SymbolKind.NamedType result.Add(ReflectType(DirectCast(member, PENamedTypeSymbol), memberFilter)) Case SymbolKind.Method result.Add(ReflectMethod(DirectCast(member, PEMethodSymbol))) Case SymbolKind.Property result.Add(ReflectProperty(DirectCast(member, PEPropertySymbol))) Case SymbolKind.Event result.Add(ReflectEvent(DirectCast(member, PEEventSymbol))) Case SymbolKind.Field result.Add(ReflectField(DirectCast(member, PEFieldSymbol))) Case Else Throw TestExceptionUtilities.UnexpectedValue(member.Kind) End Select Next Return result End Function Private Function ReflectAttributes(attrData As ImmutableArray(Of VisualBasicAttributeData)) As XElement Dim result = <Attributes></Attributes> For Each attr In attrData Dim application = <<%= attr.AttributeClass.ToTestDisplayString() %>/> result.Add(application) application.Add(<ctor><%= attr.AttributeConstructor.ToTestDisplayString() %></ctor>) For Each arg In attr.CommonConstructorArguments application.Add(<a><%= arg.Value.ToString() %></a>) Next For Each named In attr.CommonNamedArguments application.Add(<Named Name=<%= named.Key %>><%= named.Value.Value.ToString() %></Named>) Next Next Return result End Function Private Function ReflectMethod(m As PEMethodSymbol) As XElement Dim result = <Method Name=<%= m.Name %> CallingConvention=<%= m.CallingConvention %>/> Dim methodFlags = New StringBuilder() Dim methodImplFlags = New StringBuilder() MetadataSignatureHelper.AppendMethodAttributes(methodFlags, m.MethodFlags) MetadataSignatureHelper.AppendMethodImplAttributes(methodImplFlags, m.MethodImplFlags) result.Add(<MethodFlags><%= methodFlags %></MethodFlags>) result.Add(<MethodImplFlags><%= methodImplFlags %></MethodImplFlags>) If m.GetAttributes().Length > 0 Then result.Add(ReflectAttributes(m.GetAttributes())) End If For Each impl In m.ExplicitInterfaceImplementations result.Add(<Implements><%= impl.ToTestDisplayString() %></Implements>) Next For Each param In m.Parameters result.Add(ReflectParameter(DirectCast(param, PEParameterSymbol))) Next Dim ret = <Return><Type><%= m.ReturnType %></Type></Return> result.Add(ret) Dim retFlags = m.ReturnParam.ParamFlags If retFlags <> 0 Then Dim paramFlags = New StringBuilder() MetadataSignatureHelper.AppendParameterAttributes(paramFlags, retFlags) ret.Add(<ParamFlags><%= paramFlags %></ParamFlags>) End If If m.GetReturnTypeAttributes().Length > 0 Then ret.Add(ReflectAttributes(m.GetReturnTypeAttributes())) End If Return result End Function Private Function ReflectParameter(p As PEParameterSymbol) As XElement Dim result = <Parameter Name=<%= p.Name %>/> Dim paramFlags = New StringBuilder() MetadataSignatureHelper.AppendParameterAttributes(paramFlags, p.ParamFlags) result.Add(<ParamFlags><%= paramFlags %></ParamFlags>) If p.GetAttributes().Length > 0 Then result.Add(ReflectAttributes(p.GetAttributes())) End If If p.IsParamArray Then Dim peModule = DirectCast(p.ContainingModule, PEModuleSymbol).Module Dim numParamArray = peModule.GetParamArrayCountOrThrow(p.Handle) result.Add(<ParamArray count=<%= numParamArray %>/>) End If Dim type = <Type><%= p.Type %></Type> result.Add(type) If p.IsByRef Then type.@ByRef = "True" End If If p.HasExplicitDefaultValue Then Dim value = p.ExplicitDefaultValue If TypeOf value Is Date Then ' The default display of DateTime is different between Desktop and CoreClr hence ' we need to normalize the value here. value = (CDate(value)).ToString("yyyy-MM-ddTHH:mm:ss") End If result.Add(<Default><%= value %></Default>) End If ' TODO (tomat): add MarshallingInformation Return result End Function Private Function ReflectProperty(p As PEPropertySymbol) As XElement Dim result = <Property Name=<%= p.Name %>/> Dim propertyFlags As New StringBuilder() MetadataSignatureHelper.AppendPropertyAttributes(propertyFlags, p.PropertyFlags) result.Add(<PropertyFlags><%= propertyFlags %></PropertyFlags>) If p.GetAttributes().Length > 0 Then result.Add(ReflectAttributes(p.GetAttributes())) End If If p.GetMethod IsNot Nothing Then result.Add(<Get><%= p.GetMethod.ToTestDisplayString() %></Get>) End If If p.SetMethod IsNot Nothing Then result.Add(<Set><%= p.SetMethod.ToTestDisplayString() %></Set>) End If Return result End Function Private Function ReflectEvent(e As PEEventSymbol) As XElement Dim result = <Event Name=<%= e.Name %>/> Dim eventFlags = New StringBuilder() MetadataSignatureHelper.AppendEventAttributes(eventFlags, e.EventFlags) result.Add(<EventFlags><%= eventFlags %></EventFlags>) If e.GetAttributes().Length > 0 Then result.Add(ReflectAttributes(e.GetAttributes())) End If If e.AddMethod IsNot Nothing Then result.Add(<Add><%= e.AddMethod.ToTestDisplayString() %></Add>) End If If e.RemoveMethod IsNot Nothing Then result.Add(<Remove><%= e.RemoveMethod.ToTestDisplayString() %></Remove>) End If If e.RaiseMethod IsNot Nothing Then result.Add(<Raise><%= e.RaiseMethod.ToTestDisplayString() %></Raise>) End If Return result End Function Private Function ReflectField(f As PEFieldSymbol) As XElement Dim result = <Field Name=<%= f.Name %>/> Dim fieldFlags = New StringBuilder() MetadataSignatureHelper.AppendFieldAttributes(fieldFlags, f.FieldFlags) result.Add(<FieldFlags><%= fieldFlags %></FieldFlags>) If f.GetAttributes().Length > 0 Then result.Add(ReflectAttributes(f.GetAttributes())) End If result.Add(<Type><%= f.Type %></Type>) Return result End Function Private Sub AssertReflection(expected As XElement, actual As XElement) Dim expectedStr = expected.ToString().Trim() Dim actualStr = actual.ToString().Trim() Assert.True(expectedStr.Equals(actualStr), AssertEx.GetAssertMessage(expectedStr, actualStr)) End Sub <Fact> Public Sub SimpleTest1() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System.Runtime.InteropServices Public Class TestAttribute1 Inherits System.Attribute Sub New(x As String) End Sub End Class <System.AttributeUsage(System.AttributeTargets.All And Not System.AttributeTargets.Method)> Public Class TestAttribute2 Inherits System.Attribute Sub New(x As String) End Sub End Class <TestAttribute1("EventDelegate")> Public Delegate Sub EventDelegate(<TestAttribute1("EventDelegate_x")> x As Byte, ByRef y As String, <MarshalAs(UnmanagedType.BStr)> z As String) Public MustInherit Class ComClassTestBase MustOverride Sub M4(Optional x As Date = #8/23/1970#, Optional y As Decimal = 4.5D) MustOverride Sub M5(ParamArray z As Integer()) End Class <Microsoft.VisualBasic.ComClass("", "", "")> Public Class ComClassTest Inherits ComClassTestBase Sub M1() End Sub Property P1 As Integer Get Return Nothing End Get Set(value As Integer) End Set End Property Function M2(x As Integer, ByRef y As Double) As Object Return Nothing End Function Event E1 As EventDelegate <TestAttribute1("TestAttribute1_E2"), TestAttribute2("TestAttribute2_E2")> Event E2(<TestAttribute1("E2_x")> x As Byte, ByRef y As String, <MarshalAs(UnmanagedType.AnsiBStr)> z As String) <TestAttribute1("TestAttribute1_M3")> Function M3(<TestAttribute2("TestAttribute2_M3"), [In], Out, MarshalAs(UnmanagedType.AnsiBStr)> Optional ByRef x As String = "M3_x" ) As <TestAttribute1("Return_M3"), MarshalAs(UnmanagedType.BStr)> String Return Nothing End Function Public Overrides Sub M4(Optional x As Date = #8/23/1970#, Optional y As Decimal = 4.5D) End Sub Public NotOverridable Overrides Sub M5(ParamArray z() As Integer) End Sub Public ReadOnly Property P2 As String Get Return Nothing End Get End Property Public WriteOnly Property P3 As String Set(value As String) End Set End Property <TestAttribute1("TestAttribute1_P4")> Public Property P4(<TestAttribute2("TestAttribute2_P4_x"), [In], MarshalAs(UnmanagedType.AnsiBStr)> x As String, Optional y As Decimal = 5.5D ) As <TestAttribute1("Return_M4"), MarshalAs(UnmanagedType.BStr)> String <TestAttribute1("TestAttribute1_P4_Get")> Get Return Nothing End Get <TestAttribute1("TestAttribute1_P4_Set")> Set(<TestAttribute2("TestAttribute2_P4_value"), [In], MarshalAs(UnmanagedType.LPWStr)> value As String) End Set End Property Public Property P5 As Byte Friend Get Return Nothing End Get Set(value As Byte) End Set End Property Public Property P6 As Byte Get Return Nothing End Get Friend Set(value As Byte) End Set End Property Friend Sub M6() End Sub Public Shared Sub M7() End Sub Friend Property P7 As Long Get Return 0 End Get Set(value As Long) End Set End Property Public Shared Property P8 As Long Get Return 0 End Get Set(value As Long) End Set End Property Friend Event E3 As EventDelegate Public Shared Event E4 As EventDelegate Public WithEvents WithEvents1 As ComClassTest Friend Sub Handler(x As Byte, ByRef y As String, z As String) Handles WithEvents1.E1 End Sub Public F1 As Integer End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <System.Runtime.InteropServices.ComSourceInterfacesAttribute> <ctor>Sub System.Runtime.InteropServices.ComSourceInterfacesAttribute..ctor(sourceInterfaces As System.String)</ctor> <a>ComClassTest+__ComClassTest</a> </System.Runtime.InteropServices.ComSourceInterfacesAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor(_ClassID As System.String, _InterfaceID As System.String, _EventId As System.String)</ctor> <a></a><a></a><a></a> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Field Name="F1"> <FieldFlags>public instance</FieldFlags> <Type>Integer</Type> </Field> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Function ComClassTest._ComClassTest.get_P1() As System.Int32</Implements> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.set_P1(value As System.Int32)</Implements> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M2" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Function ComClassTest._ComClassTest.M2(x As System.Int32, ByRef y As System.Double) As System.Object</Implements> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Parameter Name="y"> <ParamFlags></ParamFlags> <Type ByRef="True">Double</Type> </Parameter> <Return> <Type>Object</Type> </Return> </Method> <Method Name="add_E1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>EventDelegate</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="remove_E1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>EventDelegate</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="add_E2" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>ComClassTest.E2EventHandler</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="remove_E2" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>ComClassTest.E2EventHandler</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <TestAttribute1> <ctor>Sub TestAttribute1..ctor(x As System.String)</ctor> <a>TestAttribute1_M3</a> </TestAttribute1> </Attributes> <Implements>Function ComClassTest._ComClassTest.M3([ByRef x As System.String = "M3_x"]) As System.String</Implements> <Parameter Name="x"> <ParamFlags>[opt] [in] [out] marshal default</ParamFlags> <Attributes> <TestAttribute2> <ctor>Sub TestAttribute2..ctor(x As System.String)</ctor> <a>TestAttribute2_M3</a> </TestAttribute2> </Attributes> <Type ByRef="True">String</Type> <Default>M3_x</Default> </Parameter> <Return> <Type>String</Type> <ParamFlags>marshal</ParamFlags> <Attributes> <TestAttribute1> <ctor>Sub TestAttribute1..ctor(x As System.String)</ctor> <a>Return_M3</a> </TestAttribute1> </Attributes> </Return> </Method> <Method Name="M4" CallingConvention="HasThis"> <MethodFlags>public hidebysig strict virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M4([x As System.DateTime = #8/23/1970 12:00:00 AM#], [y As System.Decimal = 4.5])</Implements> <Parameter Name="x"> <ParamFlags>[opt]</ParamFlags> <Type>Date</Type> <Default>1970-08-23T00:00:00</Default> </Parameter> <Parameter Name="y"> <ParamFlags>[opt]</ParamFlags> <Type>Decimal</Type> <Default>4.5</Default> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M5" CallingConvention="HasThis"> <MethodFlags>public hidebysig strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M5(ParamArray z As System.Int32())</Implements> <Parameter Name="z"> <ParamFlags></ParamFlags> <ParamArray count="1"/> <Type>Integer()</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P2" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Function ComClassTest._ComClassTest.get_P2() As System.String</Implements> <Return> <Type>String</Type> </Return> </Method> <Method Name="set_P3" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.set_P3(value As System.String)</Implements> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>String</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P4" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <TestAttribute1> <ctor>Sub TestAttribute1..ctor(x As System.String)</ctor> <a>TestAttribute1_P4_Get</a> </TestAttribute1> </Attributes> <Implements>Function ComClassTest._ComClassTest.get_P4(x As System.String, [y As System.Decimal = 5.5]) As System.String</Implements> <Parameter Name="x"> <ParamFlags>[in] marshal</ParamFlags> <Attributes> <TestAttribute2> <ctor>Sub TestAttribute2..ctor(x As System.String)</ctor> <a>TestAttribute2_P4_x</a> </TestAttribute2> </Attributes> <Type>String</Type> </Parameter> <Parameter Name="y"> <ParamFlags>[opt]</ParamFlags> <Type>Decimal</Type> <Default>5.5</Default> </Parameter> <Return> <Type>String</Type> <ParamFlags>marshal</ParamFlags> <Attributes> <TestAttribute1> <ctor>Sub TestAttribute1..ctor(x As System.String)</ctor> <a>Return_M4</a> </TestAttribute1> </Attributes> </Return> </Method> <Method Name="set_P4" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <TestAttribute1> <ctor>Sub TestAttribute1..ctor(x As System.String)</ctor> <a>TestAttribute1_P4_Set</a> </TestAttribute1> </Attributes> <Implements>Sub ComClassTest._ComClassTest.set_P4(x As System.String, [y As System.Decimal = 5.5], value As System.String)</Implements> <Parameter Name="x"> <ParamFlags>[in] marshal</ParamFlags> <Attributes> <TestAttribute2> <ctor>Sub TestAttribute2..ctor(x As System.String)</ctor> <a>TestAttribute2_P4_x</a> </TestAttribute2> </Attributes> <Type>String</Type> </Parameter> <Parameter Name="y"> <ParamFlags>[opt]</ParamFlags> <Type>Decimal</Type> <Default>5.5</Default> </Parameter> <Parameter Name="value"> <ParamFlags>[in] marshal</ParamFlags> <Attributes> <TestAttribute2> <ctor>Sub TestAttribute2..ctor(x As System.String)</ctor> <a>TestAttribute2_P4_value</a> </TestAttribute2> </Attributes> <Type>String</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P5" CallingConvention="HasThis"> <MethodFlags>assembly specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Byte</Type> </Return> </Method> <Method Name="set_P5" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.set_P5(value As System.Byte)</Implements> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Byte</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P6" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Function ComClassTest._ComClassTest.get_P6() As System.Byte</Implements> <Return> <Type>Byte</Type> </Return> </Method> <Method Name="set_P6" CallingConvention="HasThis"> <MethodFlags>assembly specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Byte</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M6" CallingConvention="HasThis"> <MethodFlags>assembly instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M7" CallingConvention="Default"> <MethodFlags>public static</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P7" CallingConvention="HasThis"> <MethodFlags>assembly specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Long</Type> </Return> </Method> <Method Name="set_P7" CallingConvention="HasThis"> <MethodFlags>assembly specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Long</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P8" CallingConvention="Default"> <MethodFlags>public specialname static</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Long</Type> </Return> </Method> <Method Name="set_P8" CallingConvention="Default"> <MethodFlags>public specialname static</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Long</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="add_E3" CallingConvention="HasThis"> <MethodFlags>assembly specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>EventDelegate</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="remove_E3" CallingConvention="HasThis"> <MethodFlags>assembly specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>EventDelegate</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="add_E4" CallingConvention="Default"> <MethodFlags>public specialname static</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>EventDelegate</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="remove_E4" CallingConvention="Default"> <MethodFlags>public specialname static</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>EventDelegate</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_WithEvents1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Return> <Type>ComClassTest</Type> </Return> </Method> <Method Name="set_WithEvents1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual instance</MethodFlags> <MethodImplFlags>cil managed synchronized</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="WithEventsValue"> <ParamFlags></ParamFlags> <Type>ComClassTest</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="Handler" CallingConvention="HasThis"> <MethodFlags>assembly instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Byte</Type> </Parameter> <Parameter Name="y"> <ParamFlags></ParamFlags> <Type ByRef="True">String</Type> </Parameter> <Parameter Name="z"> <ParamFlags></ParamFlags> <Type>String</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Get>Function ComClassTest.get_P1() As System.Int32</Get> <Set>Sub ComClassTest.set_P1(value As System.Int32)</Set> </Property> <Property Name="P2"> <PropertyFlags></PropertyFlags> <Get>Function ComClassTest.get_P2() As System.String</Get> </Property> <Property Name="P3"> <PropertyFlags></PropertyFlags> <Set>Sub ComClassTest.set_P3(value As System.String)</Set> </Property> <Property Name="P4"> <PropertyFlags></PropertyFlags> <Attributes> <TestAttribute1> <ctor>Sub TestAttribute1..ctor(x As System.String)</ctor> <a>TestAttribute1_P4</a> </TestAttribute1> </Attributes> <Get>Function ComClassTest.get_P4(x As System.String, [y As System.Decimal = 5.5]) As System.String</Get> <Set>Sub ComClassTest.set_P4(x As System.String, [y As System.Decimal = 5.5], value As System.String)</Set> </Property> <Property Name="P5"> <PropertyFlags></PropertyFlags> <Get>Function ComClassTest.get_P5() As System.Byte</Get> <Set>Sub ComClassTest.set_P5(value As System.Byte)</Set> </Property> <Property Name="P6"> <PropertyFlags></PropertyFlags> <Get>Function ComClassTest.get_P6() As System.Byte</Get> <Set>Sub ComClassTest.set_P6(value As System.Byte)</Set> </Property> <Property Name="P7"> <PropertyFlags></PropertyFlags> <Get>Function ComClassTest.get_P7() As System.Int64</Get> <Set>Sub ComClassTest.set_P7(value As System.Int64)</Set> </Property> <Property Name="P8"> <PropertyFlags></PropertyFlags> <Get>Function ComClassTest.get_P8() As System.Int64</Get> <Set>Sub ComClassTest.set_P8(value As System.Int64)</Set> </Property> <Property Name="WithEvents1"> <PropertyFlags></PropertyFlags> <Get>Function ComClassTest.get_WithEvents1() As ComClassTest</Get> <Set>Sub ComClassTest.set_WithEvents1(WithEventsValue As ComClassTest)</Set> </Property> <Event Name="E1"> <EventFlags></EventFlags> <Add>Sub ComClassTest.add_E1(obj As EventDelegate)</Add> <Remove>Sub ComClassTest.remove_E1(obj As EventDelegate)</Remove> </Event> <Event Name="E2"> <EventFlags></EventFlags> <Attributes> <TestAttribute1> <ctor>Sub TestAttribute1..ctor(x As System.String)</ctor> <a>TestAttribute1_E2</a> </TestAttribute1> <TestAttribute2> <ctor>Sub TestAttribute2..ctor(x As System.String)</ctor> <a>TestAttribute2_E2</a> </TestAttribute2> </Attributes> <Add>Sub ComClassTest.add_E2(obj As ComClassTest.E2EventHandler)</Add> <Remove>Sub ComClassTest.remove_E2(obj As ComClassTest.E2EventHandler)</Remove> </Event> <Event Name="E3"> <EventFlags></EventFlags> <Add>Sub ComClassTest.add_E3(obj As EventDelegate)</Add> <Remove>Sub ComClassTest.remove_E3(obj As EventDelegate)</Remove> </Event> <Event Name="E4"> <EventFlags></EventFlags> <Add>Sub ComClassTest.add_E4(obj As EventDelegate)</Add> <Remove>Sub ComClassTest.remove_E4(obj As EventDelegate)</Remove> </Event> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M2" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>3</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Parameter Name="y"> <ParamFlags></ParamFlags> <Type ByRef="True">Double</Type> </Parameter> <Return> <Type>Object</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>4</a> </System.Runtime.InteropServices.DispIdAttribute> <TestAttribute1> <ctor>Sub TestAttribute1..ctor(x As System.String)</ctor> <a>TestAttribute1_M3</a> </TestAttribute1> </Attributes> <Parameter Name="x"> <ParamFlags>[opt] [in] [out] marshal default</ParamFlags> <Attributes> <TestAttribute2> <ctor>Sub TestAttribute2..ctor(x As System.String)</ctor> <a>TestAttribute2_M3</a> </TestAttribute2> </Attributes> <Type ByRef="True">String</Type> <Default>M3_x</Default> </Parameter> <Return> <Type>String</Type> <ParamFlags>marshal</ParamFlags> <Attributes> <TestAttribute1> <ctor>Sub TestAttribute1..ctor(x As System.String)</ctor> <a>Return_M3</a> </TestAttribute1> </Attributes> </Return> </Method> <Method Name="M4" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>5</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="x"> <ParamFlags>[opt]</ParamFlags> <Type>Date</Type> <Default>1970-08-23T00:00:00</Default> </Parameter> <Parameter Name="y"> <ParamFlags>[opt]</ParamFlags> <Type>Decimal</Type> <Default>4.5</Default> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M5" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>6</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="z"> <ParamFlags></ParamFlags> <ParamArray count="1"/> <Type>Integer()</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P2" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>7</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>String</Type> </Return> </Method> <Method Name="set_P3" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>8</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>String</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P4" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>9</a> </System.Runtime.InteropServices.DispIdAttribute> <TestAttribute1> <ctor>Sub TestAttribute1..ctor(x As System.String)</ctor> <a>TestAttribute1_P4_Get</a> </TestAttribute1> </Attributes> <Parameter Name="x"> <ParamFlags>[in] marshal</ParamFlags> <Attributes> <TestAttribute2> <ctor>Sub TestAttribute2..ctor(x As System.String)</ctor> <a>TestAttribute2_P4_x</a> </TestAttribute2> </Attributes> <Type>String</Type> </Parameter> <Parameter Name="y"> <ParamFlags>[opt]</ParamFlags> <Type>Decimal</Type> <Default>5.5</Default> </Parameter> <Return> <Type>String</Type> <ParamFlags>marshal</ParamFlags> <Attributes> <TestAttribute1> <ctor>Sub TestAttribute1..ctor(x As System.String)</ctor> <a>Return_M4</a> </TestAttribute1> </Attributes> </Return> </Method> <Method Name="set_P4" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>9</a> </System.Runtime.InteropServices.DispIdAttribute> <TestAttribute1> <ctor>Sub TestAttribute1..ctor(x As System.String)</ctor> <a>TestAttribute1_P4_Set</a> </TestAttribute1> </Attributes> <Parameter Name="x"> <ParamFlags>[in] marshal</ParamFlags> <Attributes> <TestAttribute2> <ctor>Sub TestAttribute2..ctor(x As System.String)</ctor> <a>TestAttribute2_P4_x</a> </TestAttribute2> </Attributes> <Type>String</Type> </Parameter> <Parameter Name="y"> <ParamFlags>[opt]</ParamFlags> <Type>Decimal</Type> <Default>5.5</Default> </Parameter> <Parameter Name="value"> <ParamFlags>[in] marshal</ParamFlags> <Attributes> <TestAttribute2> <ctor>Sub TestAttribute2..ctor(x As System.String)</ctor> <a>TestAttribute2_P4_value</a> </TestAttribute2> </Attributes> <Type>String</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="set_P5" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>10</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Byte</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P6" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>11</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Byte</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest._ComClassTest.get_P1() As System.Int32</Get> <Set>Sub ComClassTest._ComClassTest.set_P1(value As System.Int32)</Set> </Property> <Property Name="P2"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>7</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest._ComClassTest.get_P2() As System.String</Get> </Property> <Property Name="P3"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>8</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Set>Sub ComClassTest._ComClassTest.set_P3(value As System.String)</Set> </Property> <Property Name="P4"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>9</a> </System.Runtime.InteropServices.DispIdAttribute> <TestAttribute1> <ctor>Sub TestAttribute1..ctor(x As System.String)</ctor> <a>TestAttribute1_P4</a> </TestAttribute1> </Attributes> <Get>Function ComClassTest._ComClassTest.get_P4(x As System.String, [y As System.Decimal = 5.5]) As System.String</Get> <Set>Sub ComClassTest._ComClassTest.set_P4(x As System.String, [y As System.Decimal = 5.5], value As System.String)</Set> </Property> <Property Name="P5"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>10</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Set>Sub ComClassTest._ComClassTest.set_P5(value As System.Byte)</Set> </Property> <Property Name="P6"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>11</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest._ComClassTest.get_P6() As System.Byte</Get> </Property> </Interface> <Interface Name="__ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.InterfaceTypeAttribute> <ctor>Sub System.Runtime.InteropServices.InterfaceTypeAttribute..ctor(interfaceType As System.Int16)</ctor> <a>2</a> </System.Runtime.InteropServices.InterfaceTypeAttribute> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="E1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Byte</Type> </Parameter> <Parameter Name="y"> <ParamFlags></ParamFlags> <Type ByRef="True">String</Type> </Parameter> <Parameter Name="z"> <ParamFlags></ParamFlags> <Type>String</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="E2" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> <TestAttribute1> <ctor>Sub TestAttribute1..ctor(x As System.String)</ctor> <a>TestAttribute1_E2</a> </TestAttribute1> </Attributes> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Byte</Type> </Parameter> <Parameter Name="y"> <ParamFlags></ParamFlags> <Type ByRef="True">String</Type> </Parameter> <Parameter Name="z"> <ParamFlags></ParamFlags> <Type>String</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> </Interface> </Class> ' Strip TODO comments from the base-line. For Each d In expected.DescendantNodes.ToArray() Dim comment = TryCast(d, XComment) If comment IsNot Nothing Then comment.Remove() End If Next Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub).VerifyDiagnostics() End Sub <Fact> Public Sub SimpleTest2() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest Sub M1() End Sub End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub).VerifyDiagnostics() End Sub <Fact> Public Sub SimpleTest3() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ <Microsoft.VisualBasic.ComClass("7666AC25-855F-4534-BC55-27BF09D49D46")> Public Class ComClassTest Event E1 As System.Action End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.GuidAttribute> <ctor>Sub System.Runtime.InteropServices.GuidAttribute..ctor(guid As System.String)</ctor> <a>7666AC25-855F-4534-BC55-27BF09D49D46</a> </System.Runtime.InteropServices.GuidAttribute> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <System.Runtime.InteropServices.ComSourceInterfacesAttribute> <ctor>Sub System.Runtime.InteropServices.ComSourceInterfacesAttribute..ctor(sourceInterfaces As System.String)</ctor> <a>ComClassTest+__ComClassTest</a> </System.Runtime.InteropServices.ComSourceInterfacesAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor(_ClassID As System.String)</ctor> <a>7666AC25-855F-4534-BC55-27BF09D49D46</a> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="add_E1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>System.Action</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="remove_E1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>System.Action</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Event Name="E1"> <EventFlags></EventFlags> <Add>Sub ComClassTest.add_E1(obj As System.Action)</Add> <Remove>Sub ComClassTest.remove_E1(obj As System.Action)</Remove> </Event> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> </Interface> <Interface Name="__ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.InterfaceTypeAttribute> <ctor>Sub System.Runtime.InteropServices.InterfaceTypeAttribute..ctor(interfaceType As System.Int16)</ctor> <a>2</a> </System.Runtime.InteropServices.InterfaceTypeAttribute> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="E1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub).VerifyDiagnostics() End Sub <Fact> Public Sub SimpleTest4() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ <Microsoft.VisualBasic.ComClass("7666AC25-855F-4534-BC55-27BF09D49D46", "54388137-8A76-491e-AA3A-853E23AC1217")> Public Class ComClassTest Sub M1() End Sub End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.GuidAttribute> <ctor>Sub System.Runtime.InteropServices.GuidAttribute..ctor(guid As System.String)</ctor> <a>7666AC25-855F-4534-BC55-27BF09D49D46</a> </System.Runtime.InteropServices.GuidAttribute> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor(_ClassID As System.String, _InterfaceID As System.String)</ctor> <a>7666AC25-855F-4534-BC55-27BF09D49D46</a> <a>54388137-8A76-491e-AA3A-853E23AC1217</a> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.GuidAttribute> <ctor>Sub System.Runtime.InteropServices.GuidAttribute..ctor(guid As System.String)</ctor> <a>54388137-8A76-491e-AA3A-853E23AC1217</a> </System.Runtime.InteropServices.GuidAttribute> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub).VerifyDiagnostics() End Sub <Fact> Public Sub SimpleTest5() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub) AssertTheseDiagnostics(verifier.Compilation, <expected> BC40011: 'Microsoft.VisualBasic.ComClassAttribute' is specified for class 'ComClassTest' but 'ComClassTest' has no public members that can be exposed to COM; therefore, no COM interfaces are generated. Public Class ComClassTest ~~~~~~~~~~~~ </expected>) End Sub <Fact> Public Sub SimpleTest6() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ <Microsoft.VisualBasic.ComClass("7666AC25-855F-4534-BC55-27BF09D49D46", "54388137-8A76-491e-AA3A-853E23AC1217", "EA329A13-16A0-478d-B41F-47583A761FF2", InterfaceShadows:=True)> Public Class ComClassTest Sub M1() Dim x as Integer = 12 Dim y = Function() x End Sub End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.GuidAttribute> <ctor>Sub System.Runtime.InteropServices.GuidAttribute..ctor(guid As System.String)</ctor> <a>7666AC25-855F-4534-BC55-27BF09D49D46</a> </System.Runtime.InteropServices.GuidAttribute> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor(_ClassID As System.String, _InterfaceID As System.String, _EventId As System.String)</ctor> <a>7666AC25-855F-4534-BC55-27BF09D49D46</a> <a>54388137-8A76-491e-AA3A-853E23AC1217</a> <a>EA329A13-16A0-478d-B41F-47583A761FF2</a> <Named Name="InterfaceShadows">True</Named> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.GuidAttribute> <ctor>Sub System.Runtime.InteropServices.GuidAttribute..ctor(guid As System.String)</ctor> <a>54388137-8A76-491e-AA3A-853E23AC1217</a> </System.Runtime.InteropServices.GuidAttribute> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> </Interface> <Class Name="_Closure$__1-0"> <TypeDefFlags>nested assembly auto ansi sealed</TypeDefFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Field Name="$VB$Local_x"> <FieldFlags>public instance</FieldFlags> <Type>Integer</Type> </Field> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="_Lambda$__0" CallingConvention="HasThis"> <MethodFlags>assembly specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Integer</Type> </Return> </Method> </Class> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub).VerifyDiagnostics() End Sub <Fact> Public Sub Test_ERR_ComClassOnGeneric() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest(Of T) End Class Public Class ComClassTest1(Of T) <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest2 End Class End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll) Dim expected = <expected> BC31527: 'Microsoft.VisualBasic.ComClassAttribute' cannot be applied to a class that is generic or contained inside a generic type. Public Class ComClassTest(Of T) ~~~~~~~~~~~~ BC31527: 'Microsoft.VisualBasic.ComClassAttribute' cannot be applied to a class that is generic or contained inside a generic type. Public Class ComClassTest2 ~~~~~~~~~~~~~ </expected> AssertTheseDeclarationDiagnostics(compilation, expected) AssertTheseDiagnostics(compilation, expected) End Sub <Fact()> Public Sub Test_ERR_BadAttributeUuid2() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass("1", "2", "3")> Public Class ComClassTest Public Sub Goo() End Sub End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll) Dim expected = <expected> BC32500: 'ComClassAttribute' cannot be applied because the format of the GUID '1' is not correct. Public Class ComClassTest ~~~~~~~~~~~~ BC32500: 'ComClassAttribute' cannot be applied because the format of the GUID '2' is not correct. Public Class ComClassTest ~~~~~~~~~~~~ BC32500: 'ComClassAttribute' cannot be applied because the format of the GUID '3' is not correct. Public Class ComClassTest ~~~~~~~~~~~~ </expected> AssertTheseDeclarationDiagnostics(compilation, expected) AssertTheseDiagnostics(compilation, expected) End Sub <Fact> Public Sub Test_ERR_ComClassDuplicateGuids1() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass("7666AC25-855F-4534-BC55-27BF09D49D46", "7666AC25-855F-4534-BC55-27BF09D49D46", "7666AC25-855F-4534-BC55-27BF09D49D46")> Public Class ComClassTest1 Public Sub Goo() End Sub End Class <Microsoft.VisualBasic.ComClass("7666AC25-855F-4534-BC55-27BF09D49D46", "7666AC25-855F-4534-BC55-27BF09D49D46", "")> Public Class ComClassTest2 Public Sub Goo() End Sub End Class <Microsoft.VisualBasic.ComClass("7666AC25-855F-4534-BC55-27BF09D49D46", "", "7666AC25-855F-4534-BC55-27BF09D49D46")> Public Class ComClassTest3 Public Sub Goo() End Sub End Class <Microsoft.VisualBasic.ComClass("", "00000000-0000-0000-0000-000000000000", "")> Public Class ComClassTest4 Public Sub Goo() End Sub End Class <Microsoft.VisualBasic.ComClass("", "", "00000000-0000-0000-0000-000000000000")> Public Class ComClassTest5 Public Sub Goo() End Sub End Class <Microsoft.VisualBasic.ComClass("", "00000000-0000-0000-0000-000000000000", "0")> Public Class ComClassTest6 Public Sub Goo() End Sub End Class <Microsoft.VisualBasic.ComClass("", "0", "00000000-0000-0000-0000-000000000000")> Public Class ComClassTest7 Public Sub Goo() End Sub End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll) Dim expected = <expected> BC32507: 'InterfaceId' and 'EventsId' parameters for 'Microsoft.VisualBasic.ComClassAttribute' on 'ComClassTest1' cannot have the same value. Public Class ComClassTest1 ~~~~~~~~~~~~~ BC32500: 'ComClassAttribute' cannot be applied because the format of the GUID '0' is not correct. Public Class ComClassTest6 ~~~~~~~~~~~~~ BC32500: 'ComClassAttribute' cannot be applied because the format of the GUID '0' is not correct. Public Class ComClassTest7 ~~~~~~~~~~~~~ </expected> AssertTheseDeclarationDiagnostics(compilation, expected) AssertTheseDiagnostics(compilation, expected) End Sub <Fact> Public Sub Test_ERR_ComClassAndReservedAttribute1_Guid() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass(), Guid("7666AC25-855F-4534-BC55-27BF09D49D46")> Public Class ComClassTest Public Sub Goo() End Sub End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll) Dim expected = <expected> BC32501: 'Microsoft.VisualBasic.ComClassAttribute' and 'GuidAttribute' cannot both be applied to the same class. Public Class ComClassTest ~~~~~~~~~~~~ </expected> AssertTheseDeclarationDiagnostics(compilation, expected) AssertTheseDiagnostics(compilation, expected) End Sub <Fact> Public Sub Test_ERR_ComClassAndReservedAttribute1_ClassInterface() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass(), ClassInterface(0)> Public Class ComClassTest1 Public Sub Goo() End Sub End Class <Microsoft.VisualBasic.ComClass(), ClassInterface(ClassInterfaceType.None)> Public Class ComClassTest2 Public Sub Goo() End Sub End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll) Dim expected = <expected> BC32501: 'Microsoft.VisualBasic.ComClassAttribute' and 'ClassInterfaceAttribute' cannot both be applied to the same class. Public Class ComClassTest1 ~~~~~~~~~~~~~ BC32501: 'Microsoft.VisualBasic.ComClassAttribute' and 'ClassInterfaceAttribute' cannot both be applied to the same class. Public Class ComClassTest2 ~~~~~~~~~~~~~ </expected> AssertTheseDeclarationDiagnostics(compilation, expected) AssertTheseDiagnostics(compilation, expected) End Sub <Fact> Public Sub Test_ERR_ComClassAndReservedAttribute1_ComSourceInterfaces() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass(), ComSourceInterfaces("x")> Public Class ComClassTest1 Public Sub Goo() End Sub End Class <Microsoft.VisualBasic.ComClass(), ComSourceInterfaces(GetType(ComClassTest1))> Public Class ComClassTest2 Public Sub Goo() End Sub End Class <Microsoft.VisualBasic.ComClass(), ComSourceInterfaces(GetType(ComClassTest1), GetType(ComClassTest1))> Public Class ComClassTest3 Public Sub Goo() End Sub End Class <Microsoft.VisualBasic.ComClass(), ComSourceInterfaces(GetType(ComClassTest1), GetType(ComClassTest1), GetType(ComClassTest1))> Public Class ComClassTest4 Public Sub Goo() End Sub End Class <Microsoft.VisualBasic.ComClass(), ComSourceInterfaces(GetType(ComClassTest1), GetType(ComClassTest1), GetType(ComClassTest1), GetType(ComClassTest1))> Public Class ComClassTest5 Public Sub Goo() End Sub End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll) Dim expected = <expected> BC32501: 'Microsoft.VisualBasic.ComClassAttribute' and 'ComSourceInterfacesAttribute' cannot both be applied to the same class. Public Class ComClassTest1 ~~~~~~~~~~~~~ BC32501: 'Microsoft.VisualBasic.ComClassAttribute' and 'ComSourceInterfacesAttribute' cannot both be applied to the same class. Public Class ComClassTest2 ~~~~~~~~~~~~~ BC32501: 'Microsoft.VisualBasic.ComClassAttribute' and 'ComSourceInterfacesAttribute' cannot both be applied to the same class. Public Class ComClassTest3 ~~~~~~~~~~~~~ BC32501: 'Microsoft.VisualBasic.ComClassAttribute' and 'ComSourceInterfacesAttribute' cannot both be applied to the same class. Public Class ComClassTest4 ~~~~~~~~~~~~~ BC32501: 'Microsoft.VisualBasic.ComClassAttribute' and 'ComSourceInterfacesAttribute' cannot both be applied to the same class. Public Class ComClassTest5 ~~~~~~~~~~~~~ </expected> AssertTheseDeclarationDiagnostics(compilation, expected) AssertTheseDiagnostics(compilation, expected) End Sub <Fact> Public Sub Test_ERR_ComClassAndReservedAttribute1_ComVisible() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass(), ComVisible(False)> Public Class ComClassTest1 Public Sub Goo() End Sub End Class <Microsoft.VisualBasic.ComClass(), ComVisible(True)> Public Class ComClassTest2 Public Sub Goo() End Sub End Class <Microsoft.VisualBasic.ComClass(), ComVisible()> Public Class ComClassTest3 Public Sub Goo() End Sub End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll) Dim expected = <expected><![CDATA[ BC32501: 'Microsoft.VisualBasic.ComClassAttribute' and 'ComVisibleAttribute(False)' cannot both be applied to the same class. Public Class ComClassTest1 ~~~~~~~~~~~~~ BC30455: Argument not specified for parameter 'visibility' of 'Public Overloads Sub New(visibility As Boolean)'. <Microsoft.VisualBasic.ComClass(), ComVisible()> ~~~~~~~~~~ ]]></expected> AssertTheseDeclarationDiagnostics(compilation, expected) AssertTheseDiagnostics(compilation, expected) End Sub <Fact> Public Sub Test_ERR_ComClassRequiresPublicClass1_ERR_ComClassRequiresPublicClass2() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Friend Class ComClassTest1 Public Sub Goo() End Sub End Class Friend Class ComClassTest2 Friend Class ComClassTest3 <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest4 Public Sub Goo() End Sub End Class End Class End Class Friend Class ComClassTest5 Public Class ComClassTest6 <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest7 Public Sub Goo() End Sub End Class End Class End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll) Dim expected = <expected> BC32509: 'Microsoft.VisualBasic.ComClassAttribute' cannot be applied to 'ComClassTest1' because it is not declared 'Public'. Friend Class ComClassTest1 ~~~~~~~~~~~~~ BC32504: 'Microsoft.VisualBasic.ComClassAttribute' cannot be applied to 'ComClassTest4' because its container 'ComClassTest3' is not declared 'Public'. Public Class ComClassTest4 ~~~~~~~~~~~~~ BC32504: 'Microsoft.VisualBasic.ComClassAttribute' cannot be applied to 'ComClassTest7' because its container 'ComClassTest5' is not declared 'Public'. Public Class ComClassTest7 ~~~~~~~~~~~~~ </expected> AssertTheseDeclarationDiagnostics(compilation, expected) AssertTheseDiagnostics(compilation, expected) End Sub <Fact> Public Sub Test_ERR_ComClassCantBeAbstract0() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public MustInherit Class ComClassTest1 Public Sub Goo() End Sub End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll) Dim expected = <expected> BC32508: 'Microsoft.VisualBasic.ComClassAttribute' cannot be applied to a class that is declared 'MustInherit'. Public MustInherit Class ComClassTest1 ~~~~~~~~~~~~~ </expected> AssertTheseDeclarationDiagnostics(compilation, expected) AssertTheseDiagnostics(compilation, expected) End Sub <Fact> Public Sub Test_ERR_MemberConflictWithSynth4() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest1 Public Sub Goo() End Sub Public Event E1() WithEvents ComClassTest1 As ComClassTest1 Private Sub __ComClassTest1() End Sub Protected Sub __ComClassTest1(x As Integer) End Sub End Class <Microsoft.VisualBasic.ComClass(InterfaceShadows:=False)> Public Class ComClassTest2 Public Sub Goo() End Sub Public Event E1() WithEvents ComClassTest2 As ComClassTest2 Private Sub __ComClassTest2() End Sub Protected Sub __ComClassTest2(x As Integer) End Sub End Class <Microsoft.VisualBasic.ComClass(InterfaceShadows:=True)> Public Class ComClassTest3 Public Sub Goo() End Sub Public Event E1() WithEvents ComClassTest3 As ComClassTest3 Private Sub __ComClassTest3() End Sub Protected Sub __ComClassTest3(x As Integer) End Sub End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll) Dim expected = <expected> BC31058: Conflicts with 'Interface _ComClassTest1', which is implicitly declared for 'ComClassAttribute' in Class 'ComClassTest1'. WithEvents ComClassTest1 As ComClassTest1 ~~~~~~~~~~~~~ BC31058: Conflicts with 'Interface __ComClassTest1', which is implicitly declared for 'ComClassAttribute' in Class 'ComClassTest1'. Private Sub __ComClassTest1() ~~~~~~~~~~~~~~~ BC31058: Conflicts with 'Interface __ComClassTest1', which is implicitly declared for 'ComClassAttribute' in Class 'ComClassTest1'. Protected Sub __ComClassTest1(x As Integer) ~~~~~~~~~~~~~~~ BC31058: Conflicts with 'Interface _ComClassTest2', which is implicitly declared for 'ComClassAttribute' in Class 'ComClassTest2'. WithEvents ComClassTest2 As ComClassTest2 ~~~~~~~~~~~~~ BC31058: Conflicts with 'Interface __ComClassTest2', which is implicitly declared for 'ComClassAttribute' in Class 'ComClassTest2'. Private Sub __ComClassTest2() ~~~~~~~~~~~~~~~ BC31058: Conflicts with 'Interface __ComClassTest2', which is implicitly declared for 'ComClassAttribute' in Class 'ComClassTest2'. Protected Sub __ComClassTest2(x As Integer) ~~~~~~~~~~~~~~~ BC31058: Conflicts with 'Interface _ComClassTest3', which is implicitly declared for 'ComClassAttribute' in Class 'ComClassTest3'. WithEvents ComClassTest3 As ComClassTest3 ~~~~~~~~~~~~~ BC31058: Conflicts with 'Interface __ComClassTest3', which is implicitly declared for 'ComClassAttribute' in Class 'ComClassTest3'. Private Sub __ComClassTest3() ~~~~~~~~~~~~~~~ BC31058: Conflicts with 'Interface __ComClassTest3', which is implicitly declared for 'ComClassAttribute' in Class 'ComClassTest3'. Protected Sub __ComClassTest3(x As Integer) ~~~~~~~~~~~~~~~ </expected> AssertTheseDeclarationDiagnostics(compilation, expected) AssertTheseDiagnostics(compilation, expected) End Sub <Fact> Public Sub Test_WRN_ComClassInterfaceShadows5_1() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Public Class ComClassBase Private Sub _ComClassTest1() End Sub Private Sub __ComClassTest1() End Sub Protected Sub _ComClassTest1(x As Integer) End Sub Protected Sub __ComClassTest1(x As Integer) End Sub Friend Sub _ComClassTest1(x As Integer, y As Integer) End Sub Friend Sub __ComClassTest1(x As Integer, y As Integer) End Sub Protected Friend Sub _ComClassTest1(x As Integer, y As Integer, z As Integer) End Sub Protected Friend Sub __ComClassTest1(x As Integer, y As Integer, z As Integer) End Sub Public Sub _ComClassTest1(x As Long) End Sub Public Sub __ComClassTest1(x As Long) End Sub End Class <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest1 Inherits ComClassBase Public Sub Goo() End Sub Public Event E1() End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll) Dim expected = <expected> BC42101: 'Microsoft.VisualBasic.ComClassAttribute' on class 'ComClassTest1' implicitly declares Interface '_ComClassTest1', which conflicts with a member of the same name in Class 'ComClassBase'. Use 'Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)' if you want to hide the name on the base ComClassBase. Public Class ComClassTest1 ~~~~~~~~~~~~~ BC42101: 'Microsoft.VisualBasic.ComClassAttribute' on class 'ComClassTest1' implicitly declares Interface '_ComClassTest1', which conflicts with a member of the same name in Class 'ComClassBase'. Use 'Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)' if you want to hide the name on the base ComClassBase. Public Class ComClassTest1 ~~~~~~~~~~~~~ BC42101: 'Microsoft.VisualBasic.ComClassAttribute' on class 'ComClassTest1' implicitly declares Interface '_ComClassTest1', which conflicts with a member of the same name in Class 'ComClassBase'. Use 'Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)' if you want to hide the name on the base ComClassBase. Public Class ComClassTest1 ~~~~~~~~~~~~~ BC42101: 'Microsoft.VisualBasic.ComClassAttribute' on class 'ComClassTest1' implicitly declares Interface '_ComClassTest1', which conflicts with a member of the same name in Class 'ComClassBase'. Use 'Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)' if you want to hide the name on the base ComClassBase. Public Class ComClassTest1 ~~~~~~~~~~~~~ BC42101: 'Microsoft.VisualBasic.ComClassAttribute' on class 'ComClassTest1' implicitly declares Interface '__ComClassTest1', which conflicts with a member of the same name in Class 'ComClassBase'. Use 'Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)' if you want to hide the name on the base ComClassBase. Public Class ComClassTest1 ~~~~~~~~~~~~~ BC42101: 'Microsoft.VisualBasic.ComClassAttribute' on class 'ComClassTest1' implicitly declares Interface '__ComClassTest1', which conflicts with a member of the same name in Class 'ComClassBase'. Use 'Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)' if you want to hide the name on the base ComClassBase. Public Class ComClassTest1 ~~~~~~~~~~~~~ BC42101: 'Microsoft.VisualBasic.ComClassAttribute' on class 'ComClassTest1' implicitly declares Interface '__ComClassTest1', which conflicts with a member of the same name in Class 'ComClassBase'. Use 'Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)' if you want to hide the name on the base ComClassBase. Public Class ComClassTest1 ~~~~~~~~~~~~~ BC42101: 'Microsoft.VisualBasic.ComClassAttribute' on class 'ComClassTest1' implicitly declares Interface '__ComClassTest1', which conflicts with a member of the same name in Class 'ComClassBase'. Use 'Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)' if you want to hide the name on the base ComClassBase. Public Class ComClassTest1 ~~~~~~~~~~~~~ </expected> AssertTheseDeclarationDiagnostics(compilation, expected) AssertTheseDiagnostics(compilation, expected) End Sub <Fact> Public Sub Test_WRN_ComClassInterfaceShadows5_2() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Public Class ComClassBase Private Sub _ComClassTest1() End Sub Private Sub __ComClassTest1() End Sub Protected Sub _ComClassTest1(x As Integer) End Sub Protected Sub __ComClassTest1(x As Integer) End Sub Friend Sub _ComClassTest1(x As Integer, y As Integer) End Sub Friend Sub __ComClassTest1(x As Integer, y As Integer) End Sub Protected Friend Sub _ComClassTest1(x As Integer, y As Integer, z As Integer) End Sub Protected Friend Sub __ComClassTest1(x As Integer, y As Integer, z As Integer) End Sub Public Sub _ComClassTest1(x As Long) End Sub Public Sub __ComClassTest1(x As Long) End Sub End Class <Microsoft.VisualBasic.ComClass(InterfaceShadows:=False)> Public Class ComClassTest1 Inherits ComClassBase Public Sub Goo() End Sub Public Event E1() End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll) Dim expected = <expected> BC42101: 'Microsoft.VisualBasic.ComClassAttribute' on class 'ComClassTest1' implicitly declares Interface '_ComClassTest1', which conflicts with a member of the same name in Class 'ComClassBase'. Use 'Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)' if you want to hide the name on the base ComClassBase. Public Class ComClassTest1 ~~~~~~~~~~~~~ BC42101: 'Microsoft.VisualBasic.ComClassAttribute' on class 'ComClassTest1' implicitly declares Interface '_ComClassTest1', which conflicts with a member of the same name in Class 'ComClassBase'. Use 'Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)' if you want to hide the name on the base ComClassBase. Public Class ComClassTest1 ~~~~~~~~~~~~~ BC42101: 'Microsoft.VisualBasic.ComClassAttribute' on class 'ComClassTest1' implicitly declares Interface '_ComClassTest1', which conflicts with a member of the same name in Class 'ComClassBase'. Use 'Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)' if you want to hide the name on the base ComClassBase. Public Class ComClassTest1 ~~~~~~~~~~~~~ BC42101: 'Microsoft.VisualBasic.ComClassAttribute' on class 'ComClassTest1' implicitly declares Interface '_ComClassTest1', which conflicts with a member of the same name in Class 'ComClassBase'. Use 'Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)' if you want to hide the name on the base ComClassBase. Public Class ComClassTest1 ~~~~~~~~~~~~~ BC42101: 'Microsoft.VisualBasic.ComClassAttribute' on class 'ComClassTest1' implicitly declares Interface '__ComClassTest1', which conflicts with a member of the same name in Class 'ComClassBase'. Use 'Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)' if you want to hide the name on the base ComClassBase. Public Class ComClassTest1 ~~~~~~~~~~~~~ BC42101: 'Microsoft.VisualBasic.ComClassAttribute' on class 'ComClassTest1' implicitly declares Interface '__ComClassTest1', which conflicts with a member of the same name in Class 'ComClassBase'. Use 'Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)' if you want to hide the name on the base ComClassBase. Public Class ComClassTest1 ~~~~~~~~~~~~~ BC42101: 'Microsoft.VisualBasic.ComClassAttribute' on class 'ComClassTest1' implicitly declares Interface '__ComClassTest1', which conflicts with a member of the same name in Class 'ComClassBase'. Use 'Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)' if you want to hide the name on the base ComClassBase. Public Class ComClassTest1 ~~~~~~~~~~~~~ BC42101: 'Microsoft.VisualBasic.ComClassAttribute' on class 'ComClassTest1' implicitly declares Interface '__ComClassTest1', which conflicts with a member of the same name in Class 'ComClassBase'. Use 'Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)' if you want to hide the name on the base ComClassBase. Public Class ComClassTest1 ~~~~~~~~~~~~~ </expected> AssertTheseDeclarationDiagnostics(compilation, expected) AssertTheseDiagnostics(compilation, expected) End Sub <Fact> Public Sub Test_WRN_ComClassInterfaceShadows5_3() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Public Class ComClassBase Private Sub _ComClassTest1() End Sub Private Sub __ComClassTest1() End Sub Protected Sub _ComClassTest1(x As Integer) End Sub Protected Sub __ComClassTest1(x As Integer) End Sub Friend Sub _ComClassTest1(x As Integer, y As Integer) End Sub Friend Sub __ComClassTest1(x As Integer, y As Integer) End Sub Protected Friend Sub _ComClassTest1(x As Integer, y As Integer, z As Integer) End Sub Protected Friend Sub __ComClassTest1(x As Integer, y As Integer, z As Integer) End Sub Public Sub _ComClassTest1(x As Long) End Sub Public Sub __ComClassTest1(x As Long) End Sub End Class <Microsoft.VisualBasic.ComClass(InterfaceShadows:=True)> Public Class ComClassTest1 Inherits ComClassBase Public Sub Goo() End Sub Public Event E1() End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll) Dim expected = <expected> </expected> AssertTheseDeclarationDiagnostics(compilation, expected) AssertTheseDiagnostics(compilation, expected) End Sub <Fact> Public Sub Test_WRN_ComClassPropertySetObject1() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest1 Public Property P1 As Object Get Return Nothing End Get Set(value As Object) End Set End Property Public WriteOnly Property P2 As Object Set(value As Object) End Set End Property Public ReadOnly Property P3 As Object Get Return Nothing End Get End Property End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll) Dim expected = <expected> BC42102: 'Public Property P1 As Object' cannot be exposed to COM as a property 'Let'. You will not be able to assign non-object values (such as numbers or strings) to this property from Visual Basic 6.0 using a 'Let' statement. Public Property P1 As Object ~~ BC42102: 'Public WriteOnly Property P2 As Object' cannot be exposed to COM as a property 'Let'. You will not be able to assign non-object values (such as numbers or strings) to this property from Visual Basic 6.0 using a 'Let' statement. Public WriteOnly Property P2 As Object ~~ </expected> AssertTheseDeclarationDiagnostics(compilation, expected) AssertTheseDiagnostics(compilation, expected) End Sub <Fact> Public Sub Test_ERR_ComClassGenericMethod() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest1 Public Sub Goo(Of T)() End Sub End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll) Dim expected = <expected> BC30943: Generic methods cannot be exposed to COM. Public Sub Goo(Of T)() ~~~ </expected> AssertTheseDeclarationDiagnostics(compilation, expected) AssertTheseDiagnostics(compilation, expected) End Sub <Fact()> Public Sub ComClassWithWarnings() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Public Class ComClassBase Public Sub _ComClassTest1() End Sub Public Sub __ComClassTest1() End Sub End Class <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest1 Inherits ComClassBase Public Sub M1() End Sub Public Event E1() Public WriteOnly Property P2 As Object Set(value As Object) End Set End Property End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest1"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <System.Runtime.InteropServices.ComSourceInterfacesAttribute> <ctor>Sub System.Runtime.InteropServices.ComSourceInterfacesAttribute..ctor(sourceInterfaces As System.String)</ctor> <a>ComClassTest1+__ComClassTest1</a> </System.Runtime.InteropServices.ComSourceInterfacesAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest1._ComClassTest1</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest1._ComClassTest1.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="add_E1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>ComClassTest1.E1EventHandler</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="remove_E1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>ComClassTest1.E1EventHandler</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="set_P2" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest1._ComClassTest1.set_P2(value As System.Object)</Implements> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Object</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P2"> <PropertyFlags></PropertyFlags> <Set>Sub ComClassTest1.set_P2(value As System.Object)</Set> </Property> <Event Name="E1"> <EventFlags></EventFlags> <Add>Sub ComClassTest1.add_E1(obj As ComClassTest1.E1EventHandler)</Add> <Remove>Sub ComClassTest1.remove_E1(obj As ComClassTest1.E1EventHandler)</Remove> </Event> <Interface Name="_ComClassTest1"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="set_P2" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Object</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P2"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Set>Sub ComClassTest1._ComClassTest1.set_P2(value As System.Object)</Set> </Property> </Interface> <Interface Name="__ComClassTest1"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.InterfaceTypeAttribute> <ctor>Sub System.Runtime.InteropServices.InterfaceTypeAttribute..ctor(interfaceType As System.Int16)</ctor> <a>2</a> </System.Runtime.InteropServices.InterfaceTypeAttribute> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="E1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest1")) End Sub) Dim warnings = <expected> BC42101: 'Microsoft.VisualBasic.ComClassAttribute' on class 'ComClassTest1' implicitly declares Interface '_ComClassTest1', which conflicts with a member of the same name in Class 'ComClassBase'. Use 'Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)' if you want to hide the name on the base ComClassBase. Public Class ComClassTest1 ~~~~~~~~~~~~~ BC42101: 'Microsoft.VisualBasic.ComClassAttribute' on class 'ComClassTest1' implicitly declares Interface '__ComClassTest1', which conflicts with a member of the same name in Class 'ComClassBase'. Use 'Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)' if you want to hide the name on the base ComClassBase. Public Class ComClassTest1 ~~~~~~~~~~~~~ BC42102: 'Public WriteOnly Property P2 As Object' cannot be exposed to COM as a property 'Let'. You will not be able to assign non-object values (such as numbers or strings) to this property from Visual Basic 6.0 using a 'Let' statement. Public WriteOnly Property P2 As Object ~~ </expected> AssertTheseDiagnostics(verifier.Compilation, warnings) End Sub <Fact> Public Sub Test_ERR_InvalidAttributeUsage2() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Module ComClassTest1 Public Sub M1() End Sub End Module ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll) Dim expected = <expected> BC30662: Attribute 'ComClassAttribute' cannot be applied to 'ComClassTest1' because the attribute is not valid on this declaration type. Public Module ComClassTest1 ~~~~~~~~~~~~~ </expected> AssertTheseDeclarationDiagnostics(compilation, expected) AssertTheseDiagnostics(compilation, expected) End Sub <Fact()> Public Sub ComInvisibleMembers() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest <ComVisible(False)> Public Sub M1(Of T)() End Sub Public Sub M2() End Sub <ComVisible(False)> Public Property P1 As Integer Get Return 0 End Get Set(value As Integer) End Set End Property Public Property P2 As Integer <ComVisible(False)> Get Return 0 End Get Set(value As Integer) End Set End Property Public Property P3 As Integer Get Return 0 End Get <ComVisible(False)> Set(value As Integer) End Set End Property Public ReadOnly Property P4 As Integer <ComVisible(False)> Get Return 0 End Get End Property Public WriteOnly Property P5 As Integer <ComVisible(False)> Set(value As Integer) End Set End Property End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="Generic, HasThis"> <MethodFlags>public instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>False</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M2" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M2()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P2" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>False</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P2" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.set_P2(value As System.Int32)</Implements> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P3" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Function ComClassTest._ComClassTest.get_P3() As System.Int32</Implements> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P3" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>False</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P4" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>False</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P5" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>False</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>False</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Get>Function ComClassTest.get_P1() As System.Int32</Get> <Set>Sub ComClassTest.set_P1(value As System.Int32)</Set> </Property> <Property Name="P2"> <PropertyFlags></PropertyFlags> <Get>Function ComClassTest.get_P2() As System.Int32</Get> <Set>Sub ComClassTest.set_P2(value As System.Int32)</Set> </Property> <Property Name="P3"> <PropertyFlags></PropertyFlags> <Get>Function ComClassTest.get_P3() As System.Int32</Get> <Set>Sub ComClassTest.set_P3(value As System.Int32)</Set> </Property> <Property Name="P4"> <PropertyFlags></PropertyFlags> <Get>Function ComClassTest.get_P4() As System.Int32</Get> </Property> <Property Name="P5"> <PropertyFlags></PropertyFlags> <Set>Sub ComClassTest.set_P5(value As System.Int32)</Set> </Property> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="M2" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="set_P2" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P3" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>3</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Integer</Type> </Return> </Method> <Property Name="P2"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Set>Sub ComClassTest._ComClassTest.set_P2(value As System.Int32)</Set> </Property> <Property Name="P3"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>3</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest._ComClassTest.get_P3() As System.Int32</Get> </Property> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub).VerifyDiagnostics() End Sub <Fact()> Public Sub GuidAttributeTest1() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ <Microsoft.VisualBasic.ComClass("", "7666AC25-855F-4534-BC55-27BF09D49D46", "")> Public Class ComClassTest Public Sub M1() End Sub Public Event E1() End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <System.Runtime.InteropServices.ComSourceInterfacesAttribute> <ctor>Sub System.Runtime.InteropServices.ComSourceInterfacesAttribute..ctor(sourceInterfaces As System.String)</ctor> <a>ComClassTest+__ComClassTest</a> </System.Runtime.InteropServices.ComSourceInterfacesAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor(_ClassID As System.String, _InterfaceID As System.String, _EventId As System.String)</ctor> <a></a> <a>7666AC25-855F-4534-BC55-27BF09D49D46</a> <a></a> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="add_E1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>ComClassTest.E1EventHandler</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="remove_E1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>ComClassTest.E1EventHandler</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Event Name="E1"> <EventFlags></EventFlags> <Add>Sub ComClassTest.add_E1(obj As ComClassTest.E1EventHandler)</Add> <Remove>Sub ComClassTest.remove_E1(obj As ComClassTest.E1EventHandler)</Remove> </Event> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.GuidAttribute> <ctor>Sub System.Runtime.InteropServices.GuidAttribute..ctor(guid As System.String)</ctor> <a>7666AC25-855F-4534-BC55-27BF09D49D46</a> </System.Runtime.InteropServices.GuidAttribute> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> </Interface> <Interface Name="__ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.InterfaceTypeAttribute> <ctor>Sub System.Runtime.InteropServices.InterfaceTypeAttribute..ctor(interfaceType As System.Int16)</ctor> <a>2</a> </System.Runtime.InteropServices.InterfaceTypeAttribute> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="E1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub).VerifyDiagnostics() End Sub <Fact()> Public Sub GuidAttributeTest2() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ <Microsoft.VisualBasic.ComClass("", "", "7666AC25-855F-4534-BC55-27BF09D49D46")> Public Class ComClassTest Public Sub M1() End Sub Public Event E1() End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <System.Runtime.InteropServices.ComSourceInterfacesAttribute> <ctor>Sub System.Runtime.InteropServices.ComSourceInterfacesAttribute..ctor(sourceInterfaces As System.String)</ctor> <a>ComClassTest+__ComClassTest</a> </System.Runtime.InteropServices.ComSourceInterfacesAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor(_ClassID As System.String, _InterfaceID As System.String, _EventId As System.String)</ctor> <a></a> <a></a> <a>7666AC25-855F-4534-BC55-27BF09D49D46</a> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="add_E1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>ComClassTest.E1EventHandler</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="remove_E1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>ComClassTest.E1EventHandler</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Event Name="E1"> <EventFlags></EventFlags> <Add>Sub ComClassTest.add_E1(obj As ComClassTest.E1EventHandler)</Add> <Remove>Sub ComClassTest.remove_E1(obj As ComClassTest.E1EventHandler)</Remove> </Event> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> </Interface> <Interface Name="__ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.GuidAttribute> <ctor>Sub System.Runtime.InteropServices.GuidAttribute..ctor(guid As System.String)</ctor> <a>7666AC25-855F-4534-BC55-27BF09D49D46</a> </System.Runtime.InteropServices.GuidAttribute> <System.Runtime.InteropServices.InterfaceTypeAttribute> <ctor>Sub System.Runtime.InteropServices.InterfaceTypeAttribute..ctor(interfaceType As System.Int16)</ctor> <a>2</a> </System.Runtime.InteropServices.InterfaceTypeAttribute> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="E1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub).VerifyDiagnostics() End Sub <Fact()> Public Sub GuidAttributeTest3() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass("{7666AC25-855F-4534-BC55-27BF09D49D44}", "(7666AC25-855F-4534-BC55-27BF09D49D45)", "7666AC25855F4534BC5527BF09D49D46")> Public Class ComClassTest Public Sub M1() End Sub Public Event E1() End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll) Dim expected = <expected> BC32500: 'ComClassAttribute' cannot be applied because the format of the GUID '(7666AC25-855F-4534-BC55-27BF09D49D45)' is not correct. Public Class ComClassTest ~~~~~~~~~~~~ BC32500: 'ComClassAttribute' cannot be applied because the format of the GUID '7666AC25855F4534BC5527BF09D49D46' is not correct. Public Class ComClassTest ~~~~~~~~~~~~ BC32500: 'ComClassAttribute' cannot be applied because the format of the GUID '{7666AC25-855F-4534-BC55-27BF09D49D44}' is not correct. Public Class ComClassTest ~~~~~~~~~~~~ </expected> AssertTheseDeclarationDiagnostics(compilation, expected) AssertTheseDiagnostics(compilation, expected) End Sub <Fact()> Public Sub ComSourceInterfacesAttribute1() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Namespace nS Class Test2 End Class End Namespace Namespace NS Public Class ComClassTest1 Class ComClassTest2 <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest3 Public Event E1() End Class End Class End Class End Namespace Namespace ns Class Test1 End Class End Namespace ]]></file> </compilation> Dim expected = <Class Name="ComClassTest3"> <TypeDefFlags>nested public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <System.Runtime.InteropServices.ComSourceInterfacesAttribute> <ctor>Sub System.Runtime.InteropServices.ComSourceInterfacesAttribute..ctor(sourceInterfaces As System.String)</ctor> <a>NS.ComClassTest1+ComClassTest2+ComClassTest3+__ComClassTest3</a> </System.Runtime.InteropServices.ComSourceInterfacesAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>NS.ComClassTest1.ComClassTest2.ComClassTest3._ComClassTest3</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="add_E1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>NS.ComClassTest1.ComClassTest2.ComClassTest3.E1EventHandler</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="remove_E1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>NS.ComClassTest1.ComClassTest2.ComClassTest3.E1EventHandler</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Event Name="E1"> <EventFlags></EventFlags> <Add>Sub NS.ComClassTest1.ComClassTest2.ComClassTest3.add_E1(obj As NS.ComClassTest1.ComClassTest2.ComClassTest3.E1EventHandler)</Add> <Remove>Sub NS.ComClassTest1.ComClassTest2.ComClassTest3.remove_E1(obj As NS.ComClassTest1.ComClassTest2.ComClassTest3.E1EventHandler)</Remove> </Event> <Interface Name="_ComClassTest3"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> </Interface> <Interface Name="__ComClassTest3"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.InterfaceTypeAttribute> <ctor>Sub System.Runtime.InteropServices.InterfaceTypeAttribute..ctor(interfaceType As System.Int16)</ctor> <a>2</a> </System.Runtime.InteropServices.InterfaceTypeAttribute> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="E1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "NS.ComClassTest1+ComClassTest2+ComClassTest3")) End Sub) End Sub <Fact()> Public Sub OrderOfAccessors() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass("", "", "")> Public Class ComClassTest Property P1 As Integer Set(value As Integer) End Set Get Return Nothing End Get End Property End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor(_ClassID As System.String, _InterfaceID As System.String, _EventId As System.String)</ctor> <a></a> <a></a> <a></a> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.set_P1(value As System.Int32)</Implements> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Function ComClassTest._ComClassTest.get_P1() As System.Int32</Implements> <Return> <Type>Integer</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Get>Function ComClassTest.get_P1() As System.Int32</Get> <Set>Sub ComClassTest.set_P1(value As System.Int32)</Set> </Property> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Integer</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest._ComClassTest.get_P1() As System.Int32</Get> <Set>Sub ComClassTest._ComClassTest.set_P1(value As System.Int32)</Set> </Property> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub) End Sub <Fact()> Public Sub DispId1() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest Sub M1() End Sub <DispId(15)> Sub M2() End Sub Sub M3() End Sub Event E1 As Action <DispId(16)> Event E2 As Action Event E3 As Action End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <System.Runtime.InteropServices.ComSourceInterfacesAttribute> <ctor>Sub System.Runtime.InteropServices.ComSourceInterfacesAttribute..ctor(sourceInterfaces As System.String)</ctor> <a>ComClassTest+__ComClassTest</a> </System.Runtime.InteropServices.ComSourceInterfacesAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M2" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Implements>Sub ComClassTest._ComClassTest.M2()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M3()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="add_E1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>System.Action</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="remove_E1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>System.Action</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="add_E2" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>System.Action</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="remove_E2" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>System.Action</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="add_E3" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>System.Action</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="remove_E3" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>System.Action</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Event Name="E1"> <EventFlags></EventFlags> <Add>Sub ComClassTest.add_E1(obj As System.Action)</Add> <Remove>Sub ComClassTest.remove_E1(obj As System.Action)</Remove> </Event> <Event Name="E2"> <EventFlags></EventFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>16</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Add>Sub ComClassTest.add_E2(obj As System.Action)</Add> <Remove>Sub ComClassTest.remove_E2(obj As System.Action)</Remove> </Event> <Event Name="E3"> <EventFlags></EventFlags> <Add>Sub ComClassTest.add_E3(obj As System.Action)</Add> <Remove>Sub ComClassTest.remove_E3(obj As System.Action)</Remove> </Event> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M2" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> </Interface> <Interface Name="__ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.InterfaceTypeAttribute> <ctor>Sub System.Runtime.InteropServices.InterfaceTypeAttribute..ctor(interfaceType As System.Int16)</ctor> <a>2</a> </System.Runtime.InteropServices.InterfaceTypeAttribute> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="E1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="E2" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>16</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="E3" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub) End Sub <Fact()> Public Sub DispId2() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest Sub M1() End Sub <DispId(1)> Sub M2() End Sub <DispId(3)> Friend Sub M3() End Sub Sub M4() End Sub Event E1 As Action <DispId(2)> Event E2 As Action <DispId(3)> Friend Event E3 As Action Event E4 As Action End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <System.Runtime.InteropServices.ComSourceInterfacesAttribute> <ctor>Sub System.Runtime.InteropServices.ComSourceInterfacesAttribute..ctor(sourceInterfaces As System.String)</ctor> <a>ComClassTest+__ComClassTest</a> </System.Runtime.InteropServices.ComSourceInterfacesAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M2" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Implements>Sub ComClassTest._ComClassTest.M2()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>assembly instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>3</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M4" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M4()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="add_E1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>System.Action</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="remove_E1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>System.Action</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="add_E2" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>System.Action</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="remove_E2" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>System.Action</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="add_E3" CallingConvention="HasThis"> <MethodFlags>assembly specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>System.Action</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="remove_E3" CallingConvention="HasThis"> <MethodFlags>assembly specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>System.Action</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="add_E4" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>System.Action</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="remove_E4" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>System.Action</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Event Name="E1"> <EventFlags></EventFlags> <Add>Sub ComClassTest.add_E1(obj As System.Action)</Add> <Remove>Sub ComClassTest.remove_E1(obj As System.Action)</Remove> </Event> <Event Name="E2"> <EventFlags></EventFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Add>Sub ComClassTest.add_E2(obj As System.Action)</Add> <Remove>Sub ComClassTest.remove_E2(obj As System.Action)</Remove> </Event> <Event Name="E3"> <EventFlags></EventFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>3</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Add>Sub ComClassTest.add_E3(obj As System.Action)</Add> <Remove>Sub ComClassTest.remove_E3(obj As System.Action)</Remove> </Event> <Event Name="E4"> <EventFlags></EventFlags> <Add>Sub ComClassTest.add_E4(obj As System.Action)</Add> <Remove>Sub ComClassTest.remove_E4(obj As System.Action)</Remove> </Event> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M2" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M4" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>3</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> </Interface> <Interface Name="__ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.InterfaceTypeAttribute> <ctor>Sub System.Runtime.InteropServices.InterfaceTypeAttribute..ctor(interfaceType As System.Int16)</ctor> <a>2</a> </System.Runtime.InteropServices.InterfaceTypeAttribute> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="E1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="E2" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="E4" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>3</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub) End Sub <Fact()> Public Sub DispId3() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest Sub M1() End Sub <DispId(15)> Property P1 As Integer <DispId(16)> Get Return 0 End Get Set(value As Integer) End Set End Property Sub M3() End Sub End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>16</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Implements>Function ComClassTest._ComClassTest.get_P1() As System.Int32</Implements> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.set_P1(value As System.Int32)</Implements> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M3()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest.get_P1() As System.Int32</Get> <Set>Sub ComClassTest.set_P1(value As System.Int32)</Set> </Property> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>16</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>3</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest._ComClassTest.get_P1() As System.Int32</Get> <Set>Sub ComClassTest._ComClassTest.set_P1(value As System.Int32)</Set> </Property> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub) End Sub <Fact()> Public Sub DispId4() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest Sub M1() End Sub <DispId(15)> Property P1 As Integer Get Return 0 End Get <DispId(16)> Set(value As Integer) End Set End Property Sub M3() End Sub End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Function ComClassTest._ComClassTest.get_P1() As System.Int32</Implements> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>16</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Implements>Sub ComClassTest._ComClassTest.set_P1(value As System.Int32)</Implements> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M3()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest.get_P1() As System.Int32</Get> <Set>Sub ComClassTest.set_P1(value As System.Int32)</Set> </Property> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>16</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>3</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest._ComClassTest.get_P1() As System.Int32</Get> <Set>Sub ComClassTest._ComClassTest.set_P1(value As System.Int32)</Set> </Property> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub) End Sub <Fact()> Public Sub DispId5() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest Sub M1() End Sub Property P1 As Integer <DispId(15)> Get Return 0 End Get <DispId(16)> Set(value As Integer) End Set End Property Sub M3() End Sub End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Implements>Function ComClassTest._ComClassTest.get_P1() As System.Int32</Implements> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>16</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Implements>Sub ComClassTest._ComClassTest.set_P1(value As System.Int32)</Implements> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M3()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Get>Function ComClassTest.get_P1() As System.Int32</Get> <Set>Sub ComClassTest.set_P1(value As System.Int32)</Set> </Property> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>16</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>3</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest._ComClassTest.get_P1() As System.Int32</Get> <Set>Sub ComClassTest._ComClassTest.set_P1(value As System.Int32)</Set> </Property> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub) End Sub <Fact()> Public Sub DispId6() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest Sub M1() End Sub <DispId(17)> Property P1 As Integer <DispId(15)> Get Return 0 End Get <DispId(16)> Set(value As Integer) End Set End Property Sub M3() End Sub End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Implements>Function ComClassTest._ComClassTest.get_P1() As System.Int32</Implements> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>16</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Implements>Sub ComClassTest._ComClassTest.set_P1(value As System.Int32)</Implements> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M3()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>17</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest.get_P1() As System.Int32</Get> <Set>Sub ComClassTest.set_P1(value As System.Int32)</Set> </Property> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>16</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>17</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest._ComClassTest.get_P1() As System.Int32</Get> <Set>Sub ComClassTest._ComClassTest.set_P1(value As System.Int32)</Set> </Property> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub) End Sub <Fact()> Public Sub DispId7() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest Sub M1() End Sub <DispId(15)> Default Property P1(x As Integer) As Integer <DispId(16)> Get Return 0 End Get Set(value As Integer) End Set End Property Sub M3() End Sub End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Reflection.DefaultMemberAttribute> <ctor>Sub System.Reflection.DefaultMemberAttribute..ctor(memberName As System.String)</ctor> <a>P1</a> </System.Reflection.DefaultMemberAttribute> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>16</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Implements>Function ComClassTest._ComClassTest.get_P1(x As System.Int32) As System.Int32</Implements> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.set_P1(x As System.Int32, value As System.Int32)</Implements> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M3()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest.get_P1(x As System.Int32) As System.Int32</Get> <Set>Sub ComClassTest.set_P1(x As System.Int32, value As System.Int32)</Set> </Property> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> <System.Reflection.DefaultMemberAttribute> <ctor>Sub System.Reflection.DefaultMemberAttribute..ctor(memberName As System.String)</ctor> <a>P1</a> </System.Reflection.DefaultMemberAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>16</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>0</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>3</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest._ComClassTest.get_P1(x As System.Int32) As System.Int32</Get> <Set>Sub ComClassTest._ComClassTest.set_P1(x As System.Int32, value As System.Int32)</Set> </Property> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub) End Sub <Fact()> Public Sub DispId8() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest Sub M1() End Sub <DispId(15)> Default Property P1(x As Integer) As Integer Get Return 0 End Get <DispId(16)> Set(value As Integer) End Set End Property Sub M3() End Sub End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Reflection.DefaultMemberAttribute> <ctor>Sub System.Reflection.DefaultMemberAttribute..ctor(memberName As System.String)</ctor> <a>P1</a> </System.Reflection.DefaultMemberAttribute> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Function ComClassTest._ComClassTest.get_P1(x As System.Int32) As System.Int32</Implements> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>16</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Implements>Sub ComClassTest._ComClassTest.set_P1(x As System.Int32, value As System.Int32)</Implements> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M3()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest.get_P1(x As System.Int32) As System.Int32</Get> <Set>Sub ComClassTest.set_P1(x As System.Int32, value As System.Int32)</Set> </Property> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> <System.Reflection.DefaultMemberAttribute> <ctor>Sub System.Reflection.DefaultMemberAttribute..ctor(memberName As System.String)</ctor> <a>P1</a> </System.Reflection.DefaultMemberAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>0</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>16</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>3</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest._ComClassTest.get_P1(x As System.Int32) As System.Int32</Get> <Set>Sub ComClassTest._ComClassTest.set_P1(x As System.Int32, value As System.Int32)</Set> </Property> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub) End Sub <Fact()> Public Sub DispId9() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest Sub M1() End Sub Default Property P1(x As Integer) As Integer <DispId(15)> Get Return 0 End Get <DispId(16)> Set(value As Integer) End Set End Property Sub M3() End Sub End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Reflection.DefaultMemberAttribute> <ctor>Sub System.Reflection.DefaultMemberAttribute..ctor(memberName As System.String)</ctor> <a>P1</a> </System.Reflection.DefaultMemberAttribute> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Implements>Function ComClassTest._ComClassTest.get_P1(x As System.Int32) As System.Int32</Implements> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>16</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Implements>Sub ComClassTest._ComClassTest.set_P1(x As System.Int32, value As System.Int32)</Implements> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M3()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Get>Function ComClassTest.get_P1(x As System.Int32) As System.Int32</Get> <Set>Sub ComClassTest.set_P1(x As System.Int32, value As System.Int32)</Set> </Property> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> <System.Reflection.DefaultMemberAttribute> <ctor>Sub System.Reflection.DefaultMemberAttribute..ctor(memberName As System.String)</ctor> <a>P1</a> </System.Reflection.DefaultMemberAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>16</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>3</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>0</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest._ComClassTest.get_P1(x As System.Int32) As System.Int32</Get> <Set>Sub ComClassTest._ComClassTest.set_P1(x As System.Int32, value As System.Int32)</Set> </Property> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub) End Sub <Fact()> Public Sub DispId10() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest Sub M1() End Sub <DispId(17)> Default Property P1(x As Integer) As Integer <DispId(15)> Get Return 0 End Get <DispId(16)> Set(value As Integer) End Set End Property Sub M3() End Sub End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Reflection.DefaultMemberAttribute> <ctor>Sub System.Reflection.DefaultMemberAttribute..ctor(memberName As System.String)</ctor> <a>P1</a> </System.Reflection.DefaultMemberAttribute> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Implements>Function ComClassTest._ComClassTest.get_P1(x As System.Int32) As System.Int32</Implements> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>16</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Implements>Sub ComClassTest._ComClassTest.set_P1(x As System.Int32, value As System.Int32)</Implements> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M3()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>17</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest.get_P1(x As System.Int32) As System.Int32</Get> <Set>Sub ComClassTest.set_P1(x As System.Int32, value As System.Int32)</Set> </Property> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> <System.Reflection.DefaultMemberAttribute> <ctor>Sub System.Reflection.DefaultMemberAttribute..ctor(memberName As System.String)</ctor> <a>P1</a> </System.Reflection.DefaultMemberAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>16</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>17</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest._ComClassTest.get_P1(x As System.Int32) As System.Int32</Get> <Set>Sub ComClassTest._ComClassTest.set_P1(x As System.Int32, value As System.Int32)</Set> </Property> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub) End Sub <Fact()> Public Sub DispId11() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest Sub M1() End Sub <DispId(17)> Default ReadOnly Property P1(x As Integer) As Integer <DispId(15)> Get Return 0 End Get End Property Sub M3() End Sub End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Reflection.DefaultMemberAttribute> <ctor>Sub System.Reflection.DefaultMemberAttribute..ctor(memberName As System.String)</ctor> <a>P1</a> </System.Reflection.DefaultMemberAttribute> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Implements>Function ComClassTest._ComClassTest.get_P1(x As System.Int32) As System.Int32</Implements> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M3()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>17</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest.get_P1(x As System.Int32) As System.Int32</Get> </Property> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> <System.Reflection.DefaultMemberAttribute> <ctor>Sub System.Reflection.DefaultMemberAttribute..ctor(memberName As System.String)</ctor> <a>P1</a> </System.Reflection.DefaultMemberAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>17</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest._ComClassTest.get_P1(x As System.Int32) As System.Int32</Get> </Property> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub) End Sub <Fact()> Public Sub DispId12() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest Sub M1() End Sub <DispId(17)> Default WriteOnly Property P1(x As Integer) As Integer <DispId(16)> Set(value As Integer) End Set End Property Sub M3() End Sub End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Reflection.DefaultMemberAttribute> <ctor>Sub System.Reflection.DefaultMemberAttribute..ctor(memberName As System.String)</ctor> <a>P1</a> </System.Reflection.DefaultMemberAttribute> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>16</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Implements>Sub ComClassTest._ComClassTest.set_P1(x As System.Int32, value As System.Int32)</Implements> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M3()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>17</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Set>Sub ComClassTest.set_P1(x As System.Int32, value As System.Int32)</Set> </Property> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> <System.Reflection.DefaultMemberAttribute> <ctor>Sub System.Reflection.DefaultMemberAttribute..ctor(memberName As System.String)</ctor> <a>P1</a> </System.Reflection.DefaultMemberAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>16</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>17</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Set>Sub ComClassTest._ComClassTest.set_P1(x As System.Int32, value As System.Int32)</Set> </Property> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub) End Sub <Fact()> Public Sub DispId13() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest Sub M1() End Sub Function GetEnumerator() As Collections.IEnumerator Return Nothing End Function Sub M3() End Sub End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="GetEnumerator" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Function ComClassTest._ComClassTest.GetEnumerator() As System.Collections.IEnumerator</Implements> <Return> <Type>System.Collections.IEnumerator</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M3()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="GetEnumerator" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>-4</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>System.Collections.IEnumerator</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>3</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub) End Sub <Fact()> Public Sub DispId14() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest Sub M1() End Sub <DispId(13)> Function GetEnumerator() As Collections.IEnumerator Return Nothing End Function Sub M3() End Sub End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="GetEnumerator" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>13</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Implements>Function ComClassTest._ComClassTest.GetEnumerator() As System.Collections.IEnumerator</Implements> <Return> <Type>System.Collections.IEnumerator</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M3()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="GetEnumerator" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>13</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>System.Collections.IEnumerator</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub) End Sub <Fact()> Public Sub DispId15() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest Function GetEnumerator(Optional x As Integer = 0) As Collections.IEnumerator Return Nothing End Function Sub GetEnumerator() End Sub End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="GetEnumerator" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Function ComClassTest._ComClassTest.GetEnumerator([x As System.Int32 = 0]) As System.Collections.IEnumerator</Implements> <Parameter Name="x"> <ParamFlags>[opt] default</ParamFlags> <Type>Integer</Type> <Default>0</Default> </Parameter> <Return> <Type>System.Collections.IEnumerator</Type> </Return> </Method> <Method Name="GetEnumerator" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.GetEnumerator()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="GetEnumerator" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="x"> <ParamFlags>[opt] default</ParamFlags> <Type>Integer</Type> <Default>0</Default> </Parameter> <Return> <Type>System.Collections.IEnumerator</Type> </Return> </Method> <Method Name="GetEnumerator" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub) End Sub <Fact()> Public Sub DispId16() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest Function GetEnumerator() As Integer Return Nothing End Function End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="GetEnumerator" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Function ComClassTest._ComClassTest.GetEnumerator() As System.Int32</Implements> <Return> <Type>Integer</Type> </Return> </Method> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="GetEnumerator" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Integer</Type> </Return> </Method> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub) End Sub <Fact()> Public Sub DispId17() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest ReadOnly Property GetEnumerator() As Collections.IEnumerator Get Return Nothing End Get End Property ReadOnly Property GetEnumerator(Optional x As Integer = 0) As Collections.IEnumerator Get Return Nothing End Get End Property End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_GetEnumerator" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Function ComClassTest._ComClassTest.get_GetEnumerator() As System.Collections.IEnumerator</Implements> <Return> <Type>System.Collections.IEnumerator</Type> </Return> </Method> <Method Name="get_GetEnumerator" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Function ComClassTest._ComClassTest.get_GetEnumerator([x As System.Int32 = 0]) As System.Collections.IEnumerator</Implements> <Parameter Name="x"> <ParamFlags>[opt] default</ParamFlags> <Type>Integer</Type> <Default>0</Default> </Parameter> <Return> <Type>System.Collections.IEnumerator</Type> </Return> </Method> <Property Name="GetEnumerator"> <PropertyFlags></PropertyFlags> <Get>Function ComClassTest.get_GetEnumerator() As System.Collections.IEnumerator</Get> </Property> <Property Name="GetEnumerator"> <PropertyFlags></PropertyFlags> <Get>Function ComClassTest.get_GetEnumerator([x As System.Int32 = 0]) As System.Collections.IEnumerator</Get> </Property> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="get_GetEnumerator" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>-4</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>System.Collections.IEnumerator</Type> </Return> </Method> <Method Name="get_GetEnumerator" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="x"> <ParamFlags>[opt] default</ParamFlags> <Type>Integer</Type> <Default>0</Default> </Parameter> <Return> <Type>System.Collections.IEnumerator</Type> </Return> </Method> <Property Name="GetEnumerator"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>-4</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest._ComClassTest.get_GetEnumerator() As System.Collections.IEnumerator</Get> </Property> <Property Name="GetEnumerator"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest._ComClassTest.get_GetEnumerator([x As System.Int32 = 0]) As System.Collections.IEnumerator</Get> </Property> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub) End Sub <Fact()> Public Sub DefaultProperty1() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System <Microsoft.VisualBasic.ComClass()> <Reflection.DefaultMember("p1")> Public Class ComClassTest Default ReadOnly Property P1(x As Integer) As Integer Get Return Nothing End Get End Property Event E1 As Action End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <System.Runtime.InteropServices.ComSourceInterfacesAttribute> <ctor>Sub System.Runtime.InteropServices.ComSourceInterfacesAttribute..ctor(sourceInterfaces As System.String)</ctor> <a>ComClassTest+__ComClassTest</a> </System.Runtime.InteropServices.ComSourceInterfacesAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> <System.Reflection.DefaultMemberAttribute> <ctor>Sub System.Reflection.DefaultMemberAttribute..ctor(memberName As System.String)</ctor> <a>p1</a> </System.Reflection.DefaultMemberAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Function ComClassTest._ComClassTest.get_P1(x As System.Int32) As System.Int32</Implements> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="add_E1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>System.Action</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="remove_E1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>System.Action</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Get>Function ComClassTest.get_P1(x As System.Int32) As System.Int32</Get> </Property> <Event Name="E1"> <EventFlags></EventFlags> <Add>Sub ComClassTest.add_E1(obj As System.Action)</Add> <Remove>Sub ComClassTest.remove_E1(obj As System.Action)</Remove> </Event> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> <System.Reflection.DefaultMemberAttribute> <ctor>Sub System.Reflection.DefaultMemberAttribute..ctor(memberName As System.String)</ctor> <a>P1</a> </System.Reflection.DefaultMemberAttribute> </Attributes> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>0</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Integer</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>0</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest._ComClassTest.get_P1(x As System.Int32) As System.Int32</Get> </Property> </Interface> <Interface Name="__ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.InterfaceTypeAttribute> <ctor>Sub System.Runtime.InteropServices.InterfaceTypeAttribute..ctor(interfaceType As System.Int16)</ctor> <a>2</a> </System.Runtime.InteropServices.InterfaceTypeAttribute> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="E1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub).VerifyDiagnostics() End Sub <Fact()> Public Sub DispId18() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest <DispId(0)> ReadOnly Property P1(x As Integer) As Integer Get Return Nothing End Get End Property <DispId(-1)> Sub M1() End Sub <DispId(-2)> Event E1 As Action End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll) AssertTheseDeclarationDiagnostics(compilation, <expected> BC32505: 'System.Runtime.InteropServices.DispIdAttribute' cannot be applied to 'P1' because 'Microsoft.VisualBasic.ComClassAttribute' reserves zero for the default property. ReadOnly Property P1(x As Integer) As Integer ~~ BC32506: 'System.Runtime.InteropServices.DispIdAttribute' cannot be applied to 'M1' because 'Microsoft.VisualBasic.ComClassAttribute' reserves values less than zero. Sub M1() ~~ BC32506: 'System.Runtime.InteropServices.DispIdAttribute' cannot be applied to 'E1' because 'Microsoft.VisualBasic.ComClassAttribute' reserves values less than zero. Event E1 As Action ~~ </expected>) End Sub <Fact()> Public Sub DispId19() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest <DispId(0)> Sub M1() End Sub <DispId(0)> Event E1 As Action End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll) AssertTheseDeclarationDiagnostics(compilation, <expected> BC32505: 'System.Runtime.InteropServices.DispIdAttribute' cannot be applied to 'M1' because 'Microsoft.VisualBasic.ComClassAttribute' reserves zero for the default property. Sub M1() ~~ BC32505: 'System.Runtime.InteropServices.DispIdAttribute' cannot be applied to 'E1' because 'Microsoft.VisualBasic.ComClassAttribute' reserves zero for the default property. Event E1 As Action ~~ </expected>) End Sub <Fact()> Public Sub DefaultProperty2() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest <DispId(0)> Default ReadOnly Property P1(x As Integer) As Integer Get Return Nothing End Get End Property End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Reflection.DefaultMemberAttribute> <ctor>Sub System.Reflection.DefaultMemberAttribute..ctor(memberName As System.String)</ctor> <a>P1</a> </System.Reflection.DefaultMemberAttribute> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Function ComClassTest._ComClassTest.get_P1(x As System.Int32) As System.Int32</Implements> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Integer</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>0</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest.get_P1(x As System.Int32) As System.Int32</Get> </Property> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> <System.Reflection.DefaultMemberAttribute> <ctor>Sub System.Reflection.DefaultMemberAttribute..ctor(memberName As System.String)</ctor> <a>P1</a> </System.Reflection.DefaultMemberAttribute> </Attributes> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>0</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Integer</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>0</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest._ComClassTest.get_P1(x As System.Int32) As System.Int32</Get> </Property> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub).VerifyDiagnostics() End Sub <Fact()> Public Sub Serializable_and_SpecialName() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System <Microsoft.VisualBasic.ComClass()> <Serializable()> <System.Runtime.CompilerServices.SpecialName()> Public Class ComClassTest <System.Runtime.CompilerServices.SpecialName()> Sub M1() End Sub <System.Runtime.CompilerServices.SpecialName()> Event E1 As Action <System.Runtime.CompilerServices.SpecialName()> Property P1 As Integer Get Return 0 End Get Set(value As Integer) End Set End Property Property P2 As Integer <System.Runtime.CompilerServices.SpecialName()> Get Return 0 End Get <System.Runtime.CompilerServices.SpecialName()> Set(value As Integer) End Set End Property End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi serializable specialname</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <System.Runtime.InteropServices.ComSourceInterfacesAttribute> <ctor>Sub System.Runtime.InteropServices.ComSourceInterfacesAttribute..ctor(sourceInterfaces As System.String)</ctor> <a>ComClassTest+__ComClassTest</a> </System.Runtime.InteropServices.ComSourceInterfacesAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="add_E1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>System.Action</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="remove_E1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>System.Action</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Function ComClassTest._ComClassTest.get_P1() As System.Int32</Implements> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.set_P1(value As System.Int32)</Implements> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P2" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Function ComClassTest._ComClassTest.get_P2() As System.Int32</Implements> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P2" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.set_P2(value As System.Int32)</Implements> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags>specialname</PropertyFlags> <Get>Function ComClassTest.get_P1() As System.Int32</Get> <Set>Sub ComClassTest.set_P1(value As System.Int32)</Set> </Property> <Property Name="P2"> <PropertyFlags></PropertyFlags> <Get>Function ComClassTest.get_P2() As System.Int32</Get> <Set>Sub ComClassTest.set_P2(value As System.Int32)</Set> </Property> <Event Name="E1"> <EventFlags>specialname</EventFlags> <Add>Sub ComClassTest.add_E1(obj As System.Action)</Add> <Remove>Sub ComClassTest.remove_E1(obj As System.Action)</Remove> </Event> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P2" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>3</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P2" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>3</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags>specialname</PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest._ComClassTest.get_P1() As System.Int32</Get> <Set>Sub ComClassTest._ComClassTest.set_P1(value As System.Int32)</Set> </Property> <Property Name="P2"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>3</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest._ComClassTest.get_P2() As System.Int32</Get> <Set>Sub ComClassTest._ComClassTest.set_P2(value As System.Int32)</Set> </Property> </Interface> <Interface Name="__ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.InterfaceTypeAttribute> <ctor>Sub System.Runtime.InteropServices.InterfaceTypeAttribute..ctor(interfaceType As System.Int16)</ctor> <a>2</a> </System.Runtime.InteropServices.InterfaceTypeAttribute> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="E1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub).VerifyDiagnostics() End Sub <Fact(), WorkItem(531506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531506")> Public Sub Bug18218() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System.Runtime.InteropServices <Assembly: GuidAttribute("5F025F24-FAEA-4C2F-9EF6-C89A8FC90101")> <Assembly: ComVisible(True)> <Microsoft.VisualBasic.ComClass(ComClass1.ClassId, ComClass1.InterfaceId, ComClass1.EventsId)> Public Class ComClass1 Implements I6 #Region "COM GUIDs" ' These GUIDs provide the COM identity for this class ' and its COM interfaces. If you change them, existing ' clients will no longer be able to access the class. Public Const ClassId As String = "5D025F24-FAEA-4C2F-9EF6-C89A8FC9667F" Public Const InterfaceId As String = "5FDA4272-D6AD-4FA4-AD89-FAB8F0A04512" Public Const EventsId As String = "33241EB2-DFC5-4164-998E-A6577B0DA960" #End Region Public Interface I6 End Interface Public Property Scen1 As String Get Return Nothing End Get Set(ByVal Value As String) End Set End Property End Class ]]></file> </compilation> Dim expected = <Class Name="ComClass1"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.GuidAttribute> <ctor>Sub System.Runtime.InteropServices.GuidAttribute..ctor(guid As System.String)</ctor> <a>5D025F24-FAEA-4C2F-9EF6-C89A8FC9667F</a> </System.Runtime.InteropServices.GuidAttribute> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor(_ClassID As System.String, _InterfaceID As System.String, _EventId As System.String)</ctor> <a>5D025F24-FAEA-4C2F-9EF6-C89A8FC9667F</a> <a>5FDA4272-D6AD-4FA4-AD89-FAB8F0A04512</a> <a>33241EB2-DFC5-4164-998E-A6577B0DA960</a> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClass1._ComClass1</Implements> <Implements>ComClass1.I6</Implements> <Field Name="ClassId"> <FieldFlags>public static literal default</FieldFlags> <Type>String</Type> </Field> <Field Name="InterfaceId"> <FieldFlags>public static literal default</FieldFlags> <Type>String</Type> </Field> <Field Name="EventsId"> <FieldFlags>public static literal default</FieldFlags> <Type>String</Type> </Field> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_Scen1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Function ComClass1._ComClass1.get_Scen1() As System.String</Implements> <Return> <Type>String</Type> </Return> </Method> <Method Name="set_Scen1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClass1._ComClass1.set_Scen1(Value As System.String)</Implements> <Parameter Name="Value"> <ParamFlags></ParamFlags> <Type>String</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Property Name="Scen1"> <PropertyFlags></PropertyFlags> <Get>Function ComClass1.get_Scen1() As System.String</Get> <Set>Sub ComClass1.set_Scen1(Value As System.String)</Set> </Property> <Interface Name="I6"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> </Interface> <Interface Name="_ComClass1"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.GuidAttribute> <ctor>Sub System.Runtime.InteropServices.GuidAttribute..ctor(guid As System.String)</ctor> <a>5FDA4272-D6AD-4FA4-AD89-FAB8F0A04512</a> </System.Runtime.InteropServices.GuidAttribute> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="get_Scen1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>String</Type> </Return> </Method> <Method Name="set_Scen1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="Value"> <ParamFlags></ParamFlags> <Type>String</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Property Name="Scen1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClass1._ComClass1.get_Scen1() As System.String</Get> <Set>Sub ComClass1._ComClass1.set_Scen1(Value As System.String)</Set> </Property> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClass1")) End Sub).VerifyDiagnostics() End Sub <Fact, WorkItem(664574, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/664574")> Public Sub Bug664574() Dim compilationDef = <compilation> <file name="a.vb"><![CDATA[ Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass(ComClass1.ClassId, ComClass1.InterfaceId, ComClass1.EventsId)> Public Class ComClass1 #Region "COM GUIDs" ' These GUIDs provide the COM identity for this class ' and its COM interfaces. If you change them, existing ' clients will no longer be able to access the class. Public Const ClassId As String = "C1F1CEC8-2BDD-4AFC-8E86-FDC8DBEE951B" Public Const InterfaceId As String = "E4174EC8-7EDD-4672-90BA-3D1CFFF76C14" Public Const EventsId As String = "8F12C15B-4CA9-450C-9C85-37E9B74164B8" #End Region Public Function dfoo(<MarshalAs(UnmanagedType.Currency)> ByVal x As Decimal) As <MarshalAs(UnmanagedType.Currency)> Decimal Return x + 1.1D End Function End Class ]]></file> </compilation> Dim expected = <Class Name="ComClass1"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.GuidAttribute> <ctor>Sub System.Runtime.InteropServices.GuidAttribute..ctor(guid As System.String)</ctor> <a>C1F1CEC8-2BDD-4AFC-8E86-FDC8DBEE951B</a> </System.Runtime.InteropServices.GuidAttribute> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor(_ClassID As System.String, _InterfaceID As System.String, _EventId As System.String)</ctor> <a>C1F1CEC8-2BDD-4AFC-8E86-FDC8DBEE951B</a> <a>E4174EC8-7EDD-4672-90BA-3D1CFFF76C14</a> <a>8F12C15B-4CA9-450C-9C85-37E9B74164B8</a> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClass1._ComClass1</Implements> <Method Name="dfoo" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Function ComClass1._ComClass1.dfoo(x As System.Decimal) As System.Decimal</Implements> <Parameter Name="x"> <ParamFlags>marshal</ParamFlags> <Type>Decimal</Type> </Parameter> <Return> <Type>Decimal</Type> <ParamFlags>marshal</ParamFlags> </Return> </Method> <Interface Name="_ComClass1"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.GuidAttribute> <ctor>Sub System.Runtime.InteropServices.GuidAttribute..ctor(guid As System.String)</ctor> <a>E4174EC8-7EDD-4672-90BA-3D1CFFF76C14</a> </System.Runtime.InteropServices.GuidAttribute> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="dfoo" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="x"> <ParamFlags>marshal</ParamFlags> <Type>Decimal</Type> </Parameter> <Return> <Type>Decimal</Type> <ParamFlags>marshal</ParamFlags> </Return> </Method> </Interface> </Class> ' Strip TODO comments from the base-line. For Each d In expected.DescendantNodes.ToArray() Dim comment = TryCast(d, XComment) If comment IsNot Nothing Then comment.Remove() End If Next Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClass1", Function(s) Return s.Kind = SymbolKind.NamedType OrElse s.Name = "dfoo" End Function)) End Sub).VerifyDiagnostics() End Sub <Fact, WorkItem(664583, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/664583")> Public Sub Bug664583() Dim compilationDef = <compilation> <file name="a.vb"><![CDATA[ <Microsoft.VisualBasic.ComClass(ComClass1.ClassId, ComClass1.InterfaceId, ComClass1.EventsId)> Public Class ComClass1 #Region "COM GUIDs" ' These GUIDs provide the COM identity for this class ' and its COM interfaces. If you change them, existing ' clients will no longer be able to access the class. Public Const ClassId As String = "C1F1CEC8-2BDD-4AFC-8E86-FDC8DBEE951B" Public Const InterfaceId As String = "E4174EC8-7EDD-4672-90BA-3D1CFFF76C14" Public Const EventsId As String = "8F12C15B-4CA9-450C-9C85-37E9B74164B8" #End Region Public Readonly Property Goo As Integer Get Return 0 End Get End Property Structure Struct1 Public member1 As Integer Structure Struct2 Public member12 As Integer End Structure End Structure Structure struct2 Public member2 As Integer End Structure End Class ]]></file> </compilation> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim ComClass1_Struct1 = DirectCast(m.ContainingAssembly.GetTypeByMetadataName("ComClass1+Struct1"), PENamedTypeSymbol) Dim ComClass1_Struct1_Struct2 = DirectCast(m.ContainingAssembly.GetTypeByMetadataName("ComClass1+Struct1+Struct2"), PENamedTypeSymbol) Dim ComClass1_struct2 = DirectCast(m.ContainingAssembly.GetTypeByMetadataName("ComClass1+struct2"), PENamedTypeSymbol) Assert.True(MetadataTokens.GetRowNumber(ComClass1_Struct1.Handle) < MetadataTokens.GetRowNumber(ComClass1_Struct1_Struct2.Handle)) Assert.True(MetadataTokens.GetRowNumber(ComClass1_Struct1.Handle) < MetadataTokens.GetRowNumber(ComClass1_struct2.Handle)) Assert.True(MetadataTokens.GetRowNumber(ComClass1_struct2.Handle) < MetadataTokens.GetRowNumber(ComClass1_Struct1_Struct2.Handle)) End Sub).VerifyDiagnostics() End Sub <Fact, WorkItem(700050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700050")> Public Sub Bug700050() Dim compilationDef = <compilation> <file name="a.vb"><![CDATA[ Module Module1 Sub Main() End Sub End Module <Microsoft.VisualBasic.ComClass(ComClass1.ClassId, ComClass1.InterfaceId, ComClass1.EventsId)> Public Class ComClass1 Public Const ClassId As String = "" Public Const InterfaceId As String = "" Public Const EventsId As String = "" Public Sub New() End Sub Public Sub Goo() End Sub Public Property oBrowser As Object ' cannot be exposed to COM as a property 'Let'. You will not be able to assign non-object values (such as numbers or strings) to this property from Visual Basic 6.0 using a 'Let' statement. End Class ]]></file> </compilation> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim _ComClass1 = DirectCast(m.ContainingAssembly.GetTypeByMetadataName("ComClass1+_ComClass1"), PENamedTypeSymbol) Assert.Equal(0, _ComClass1.GetMembers("oBrowser").Length) End Sub).VerifyDiagnostics() End Sub End Class End Namespace
1
dotnet/roslyn
56,011
React to string comparison changing on .NET Core
The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
jaredpar
"2021-08-30T17:18:52Z"
"2021-08-30T20:20:04Z"
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
4d99cda6e446e77dbb302e26388c1093bd3ef569
React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
./src/Compilers/VisualBasic/Test/Semantic/Semantics/FieldInitializerBindingTests.vb
' 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.Reflection.Metadata Imports System.Reflection.Metadata.Ecma335 Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Public Class FieldInitializerBindingTests Inherits BasicTestBase <Fact> Public Sub NoInitializers() Dim source = <compilation name="NoInitializers"> <file name="fi.vb"> Class C Shared s1 as String Dim i1 As Integer End Class </file> </compilation> Dim expectedStaticInitializers As IEnumerable(Of ExpectedInitializer) = Nothing Dim expectedInstanceInitializers As IEnumerable(Of ExpectedInitializer) = Nothing CompileAndCheckInitializers(source, expectedInstanceInitializers, expectedStaticInitializers) End Sub <Fact> Public Sub ConstantInstanceInitializer() Dim source = <compilation name="ConstantInstanceInitializer"> <file name="fi.vb"> Class C Shared s1 as String Dim i1 As Integer = 1 End Class </file> </compilation> Dim expectedStaticInitializers As IEnumerable(Of ExpectedInitializer) = Nothing Dim expectedInstanceInitializers As IEnumerable(Of ExpectedInitializer) = New ExpectedInitializer() {New ExpectedInitializer("i1", "1", lineNumber:=2)} CompileAndCheckInitializers(source, expectedInstanceInitializers, expectedStaticInitializers) End Sub <Fact> Public Sub ConstantStaticInitializer() Dim source = <compilation name="ConstantStaticInitializer"> <file name="fi.vb"> Class C Shared s1 as String = "1" Dim i1 As Integer End Class </file> </compilation> Dim expectedStaticInitializers As IEnumerable(Of ExpectedInitializer) = New ExpectedInitializer() {New ExpectedInitializer("s1", """1""", lineNumber:=1)} Dim expectedInstanceInitializers As IEnumerable(Of ExpectedInitializer) = Nothing CompileAndCheckInitializers(source, expectedInstanceInitializers, expectedStaticInitializers) End Sub <Fact> Public Sub ExpressionInstanceInitializer() Dim source = <compilation name="ExpressionInstanceInitializer"> <file name="fi.vb"> Class C Shared s1 As String Dim i1 As Integer = 1 + Goo() Dim i2 As New C() Shared Function Goo() As Integer Return 1 End Function End Class </file> </compilation> Dim expectedStaticInitializers As IEnumerable(Of ExpectedInitializer) = Nothing Dim expectedInstanceInitializers As IEnumerable(Of ExpectedInitializer) = New ExpectedInitializer() {New ExpectedInitializer("i1", "1 + Goo()", lineNumber:=2), New ExpectedInitializer("i2", "As New C()", lineNumber:=3)} CompileAndCheckInitializers(source, expectedInstanceInitializers, expectedStaticInitializers) End Sub <Fact> Public Sub ExpressionStaticInitializer() Dim source = <compilation name="ExpressionStaticInitializer"> <file name="fi.vb"> Class C Shared s1 As Integer = 1 + Goo() Dim i1 As Integer Shared Function Goo() As Integer Return 1 End Function End Class </file> </compilation> Dim expectedStaticInitializers As IEnumerable(Of ExpectedInitializer) = New ExpectedInitializer() {New ExpectedInitializer("s1", "1 + Goo()", lineNumber:=1)} Dim expectedInstanceInitializers As IEnumerable(Of ExpectedInitializer) = Nothing CompileAndCheckInitializers(source, expectedInstanceInitializers, expectedStaticInitializers) End Sub <Fact> Public Sub InitializerOrder() Dim source = <compilation name="InitializerOrder"> <file name="fi.vb"> Class C Shared s1 As Integer = 1 Shared s2 As Integer = 2 Shared s3 As Integer = 3 Dim i1 As Integer = 1 Dim i2 As Integer = 2 Dim i3 As Integer = 3 End Class </file> </compilation> Dim expectedStaticInitializers As IEnumerable(Of ExpectedInitializer) = New ExpectedInitializer() {New ExpectedInitializer("s1", "1", lineNumber:=1), New ExpectedInitializer("s2", "2", lineNumber:=2), New ExpectedInitializer("s3", "3", lineNumber:=3)} Dim expectedInstanceInitializers As IEnumerable(Of ExpectedInitializer) = New ExpectedInitializer() {New ExpectedInitializer("i1", "1", lineNumber:=4), New ExpectedInitializer("i2", "2", lineNumber:=5), New ExpectedInitializer("i3", "3", lineNumber:=6)} CompileAndCheckInitializers(source, expectedInstanceInitializers, expectedStaticInitializers) End Sub <Fact> Public Sub AllPartialClasses() Dim source = <compilation name="AllPartialClasses"> <file name="fi.vb"> Partial Class C Shared s1 As Integer = 1 Dim i1 As Integer = 1 End Class Partial Class C Shared s2 As Integer = 2 Dim i2 As Integer = 2 End Class </file> </compilation> Dim expectedStaticInitializers As IEnumerable(Of ExpectedInitializer) = New ExpectedInitializer() {New ExpectedInitializer("s1", "1", lineNumber:=1), New ExpectedInitializer("s2", "2", lineNumber:=5)} Dim expectedInstanceInitializers As IEnumerable(Of ExpectedInitializer) = New ExpectedInitializer() {New ExpectedInitializer("i1", "1", lineNumber:=2), New ExpectedInitializer("i2", "2", lineNumber:=6)} CompileAndCheckInitializers(source, expectedInstanceInitializers, expectedStaticInitializers) End Sub <Fact> Public Sub SomePartialClasses() Dim source = <compilation name="SomePartialClasses"> <file name="fi.vb"> Partial Class C Shared s1 As Integer = 1 Dim i1 As Integer = 1 End Class Partial Class C Shared s2 As Integer = 2 Dim i2 As Integer = 2 End Class Partial Class C Shared s3 As Integer Dim i3 As Integer End Class </file> </compilation> Dim expectedStaticInitializers As IEnumerable(Of ExpectedInitializer) = New ExpectedInitializer() {New ExpectedInitializer("s1", "1", lineNumber:=1), New ExpectedInitializer("s2", "2", lineNumber:=5)} Dim expectedInstanceInitializers As IEnumerable(Of ExpectedInitializer) = New ExpectedInitializer() {New ExpectedInitializer("i1", "1", lineNumber:=2), New ExpectedInitializer("i2", "2", lineNumber:=6)} CompileAndCheckInitializers(source, expectedInstanceInitializers, expectedStaticInitializers) End Sub <Fact> Public Sub NoStaticMembers() Dim source = <compilation name="NoStaticMembers"> <file name="fi.vb"> Class C Dim i1 As Integer End Class </file> </compilation> Dim typeSymbol = CompileAndExtractTypeSymbol(source) Assert.False(HasSynthesizedStaticConstructor(typeSymbol)) Assert.False(IsBeforeFieldInit(typeSymbol)) Assert.False(IsStatic(GetMember(source, "i1"))) End Sub <Fact> Public Sub NoStaticFields() Dim source = <compilation name="NoStaticFields"> <file name="fi.vb"> Class C Dim i1 As Integer Shared Sub Goo() End Sub End Class </file> </compilation> Dim typeSymbol = CompileAndExtractTypeSymbol(source) Assert.False(HasSynthesizedStaticConstructor(typeSymbol)) Assert.False(IsBeforeFieldInit(typeSymbol)) Assert.False(IsStatic(GetMember(source, "i1"))) End Sub <Fact> Public Sub NoStaticInitializers() Dim source = <compilation name="NoStaticInitializers"> <file name="fi.vb"> Class C Dim i1 As Integer Shared s1 As Integer Shared Sub Goo() End Sub End Class </file> </compilation> Dim typeSymbol = CompileAndExtractTypeSymbol(source) Assert.False(HasSynthesizedStaticConstructor(typeSymbol)) Assert.False(IsBeforeFieldInit(typeSymbol)) Assert.False(IsStatic(GetMember(source, "i1"))) Assert.True(IsStatic(GetMember(source, "s1"))) End Sub <Fact> Public Sub StaticInitializers() Dim source = <compilation name="StaticInitializers"> <file name="fi.vb"> Class C Dim i1 As Integer Shared s1 As Integer = 1 Shared Sub Goo() End Sub End Class </file> </compilation> Dim typeSymbol = CompileAndExtractTypeSymbol(source) Assert.True(HasSynthesizedStaticConstructor(typeSymbol)) Assert.True(IsBeforeFieldInit(typeSymbol)) Assert.False(IsStatic(GetMember(source, "i1"))) Assert.True(IsStatic(GetMember(source, "s1"))) End Sub <Fact> Public Sub ConstantInitializers() Dim source = <compilation name="ConstantInitializers"> <file name="fi.vb"> Class C Dim i1 As Integer Const s1 As Integer = 1 Shared Sub Goo() End Sub End Class </file> </compilation> Dim typeSymbol = CompileAndExtractTypeSymbol(source) Assert.False(HasSynthesizedStaticConstructor(typeSymbol)) Assert.False(IsBeforeFieldInit(typeSymbol)) Assert.False(IsStatic(GetMember(source, "i1"))) Assert.True(IsStatic(GetMember(source, "s1"))) End Sub <Fact> Public Sub SourceStaticConstructorNoStaticMembers() Dim source = <compilation name="SourceStaticConstructorNoStaticMembers"> <file name="fi.vb"> Class C Shared Sub New() End Sub Dim i1 As Integer End Class </file> </compilation> Dim typeSymbol = CompileAndExtractTypeSymbol(source) Assert.False(HasSynthesizedStaticConstructor(typeSymbol)) Assert.False(IsBeforeFieldInit(typeSymbol)) End Sub <Fact> Public Sub SourceStaticConstructorNoStaticFields() Dim source = <compilation name="SourceStaticConstructorNoStaticFields"> <file name="fi.vb"> Class C Shared Sub New() End Sub Dim i1 As Integer Shared Sub Goo() End Sub End Class </file> </compilation> Dim typeSymbol = CompileAndExtractTypeSymbol(source) Assert.False(HasSynthesizedStaticConstructor(typeSymbol)) Assert.False(IsBeforeFieldInit(typeSymbol)) End Sub <Fact> Public Sub SourceStaticConstructorNoStaticInitializers() Dim source = <compilation name="SourceStaticConstructorNoStaticInitializers"> <file name="fi.vb"> Class C Shared Sub New() End Sub Dim i1 As Integer Shared s1 As Integer Shared Sub Goo() End Sub End Class </file> </compilation> Dim typeSymbol = CompileAndExtractTypeSymbol(source) Assert.False(HasSynthesizedStaticConstructor(typeSymbol)) Assert.False(IsBeforeFieldInit(typeSymbol)) End Sub <Fact> Public Sub SourceStaticConstructorStaticInitializers() Dim source = <compilation name="SourceStaticConstructorStaticInitializers"> <file name="fi.vb"> Class C Shared Sub New() End Sub Dim i1 As Integer Shared s1 As Integer = 1 Shared Sub Goo() End Sub End Class </file> </compilation> Dim typeSymbol = CompileAndExtractTypeSymbol(source) Assert.False(HasSynthesizedStaticConstructor(typeSymbol)) Assert.False(IsBeforeFieldInit(typeSymbol)) End Sub <Fact> Public Sub SourceStaticConstructorConstantInitializers() Dim source = <compilation name="SourceStaticConstructorConstantInitializers"> <file name="fi.vb"> Class C Shared Sub New() End Sub Dim i1 As Integer Const s1 As Integer = 1 Shared Sub Goo() End Sub End Class </file> </compilation> Dim typeSymbol = CompileAndExtractTypeSymbol(source) Assert.False(HasSynthesizedStaticConstructor(typeSymbol)) Assert.False(IsBeforeFieldInit(typeSymbol)) End Sub <Fact> Public Sub SourceSingleDimensionArrayWithInitializers() Dim source = <compilation name="Array1D.vb"> <file name="a.cs">Imports System Class Test Friend Shared ary01 As Short() = {+1, -2, 0}, ary02() As Single = {Math.Sqrt(2.0), 1.234!} ReadOnly ary03() = {"1", ary01(0).ToString(), Nothing, ""}, ary04 = {1, F(Nothing)} Function F(o As Object) As String If (o Is Nothing) Then Return Nothing End If Return o.ToString() End Function End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(source) Dim tree = compilation.SyntaxTrees(0) Dim typeSymbol = DirectCast(compilation.SourceModule.GlobalNamespace.GetTypeMembers("Test").Single(), SourceNamedTypeSymbol) Dim ary = DirectCast(typeSymbol.GetMembers("ary01").FirstOrDefault(), FieldSymbol) Assert.True(ary.IsShared) Assert.Equal(TypeKind.Array, ary.Type.TypeKind) Assert.Equal("System.Int16()", ary.Type.ToDisplayString(SymbolDisplayFormat.TestFormat)) ary = DirectCast(typeSymbol.GetMembers("ary02").FirstOrDefault(), FieldSymbol) Assert.True(ary.IsShared) Assert.Equal(TypeKind.Array, ary.Type.TypeKind) Assert.Equal("System.Single()", ary.Type.ToDisplayString(SymbolDisplayFormat.TestFormat)) ary = DirectCast(typeSymbol.GetMembers("ary03").FirstOrDefault(), FieldSymbol) Assert.True(ary.IsReadOnly) Assert.Equal(TypeKind.Array, ary.Type.TypeKind) Assert.Equal("System.Object()", ary.Type.ToDisplayString(SymbolDisplayFormat.TestFormat)) ary = DirectCast(typeSymbol.GetMembers("ary04").FirstOrDefault(), FieldSymbol) Assert.True(ary.IsReadOnly) Assert.Equal(TypeKind.Class, ary.Type.TypeKind) Assert.Equal("System.Object", ary.Type.ToDisplayString(SymbolDisplayFormat.TestFormat)) '''' NYI: collection initializer 'Dim expectedInitializers As IEnumerable(Of ExpectedInitializer) = _ 'New ExpectedInitializer() {New ExpectedInitializer("ary01", "{+1, -2, 0}", lineNumber:=2), ' New ExpectedInitializer("ary02", "{Math.Sqrt(2.0), 1.234!}", lineNumber:=2)} 'Dim boundInitializers = BindInitializersWithoutDiagnostics(typeSymbol, typeSymbol.StaticInitializers) 'CheckBoundInitializers(expectedInitializers, tree, boundInitializers, isStatic:=True) 'expectedInitializers = New ExpectedInitializer() { ' New ExpectedInitializer("ary03", "{""1"", ary01(0).ToString(), Nothing, """"}", lineNumber:=3), ' New ExpectedInitializer("ary04", "{1, F(Nothing)}", lineNumber:=3)} 'boundInitializers = BindInitializersWithoutDiagnostics(typeSymbol, typeSymbol.InstanceInitializers) 'CheckBoundInitializers(expectedInitializers, tree, boundInitializers, isStatic:=False) End Sub <Fact> Public Sub SourceFieldInitializers007() Dim source = <compilation name="FieldInit.dll"> <file name="aaa.cs.vb">Imports System Class Test Friend Shared field01 As New Double() Const field02 = -2147483648 - 1, field03 = True + True ' -2 ReadOnly field04 = F(Nothing), field05 As New Func(Of String, ULong)(Function(s) s.Length) Function F(o As Object) As String Return Nothing End Function End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(source) Dim tree = compilation.SyntaxTrees(0) Dim typeSymbol = DirectCast(compilation.SourceModule.GlobalNamespace.GetTypeMembers("Test").Single(), SourceNamedTypeSymbol) Dim field = DirectCast(typeSymbol.GetMembers("field01").FirstOrDefault(), FieldSymbol) Assert.True(field.IsShared) Assert.Equal(TypeKind.Structure, field.Type.TypeKind) Assert.Equal("System.Double", field.Type.ToDisplayString(SymbolDisplayFormat.TestFormat)) field = DirectCast(typeSymbol.GetMembers("field02").FirstOrDefault(), FieldSymbol) Assert.True(field.IsConst) Assert.Equal(-2147483649, field.ConstantValue) Assert.Equal(TypeKind.Structure, field.Type.TypeKind) Assert.Equal("System.Int64", field.Type.ToDisplayString(SymbolDisplayFormat.TestFormat)) field = DirectCast(typeSymbol.GetMembers("field03").FirstOrDefault(), FieldSymbol) Assert.True(field.IsConst) Assert.Equal(CShort(-2), field.ConstantValue) Assert.Equal(TypeKind.Structure, field.Type.TypeKind) Assert.Equal("System.Int16", field.Type.ToDisplayString(SymbolDisplayFormat.TestFormat)) field = DirectCast(typeSymbol.GetMembers("field04").FirstOrDefault(), FieldSymbol) Assert.True(field.IsReadOnly) Assert.Equal(TypeKind.Class, field.Type.TypeKind) Assert.Equal("System.Object", field.Type.ToDisplayString(SymbolDisplayFormat.TestFormat)) field = DirectCast(typeSymbol.GetMembers("field05").FirstOrDefault(), FieldSymbol) Assert.True(field.IsReadOnly) Assert.Equal(TypeKind.Delegate, field.Type.TypeKind) Assert.Equal("System.Func(Of System.String, System.UInt64)", field.Type.ToDisplayString(SymbolDisplayFormat.TestFormat)) Dim expectedInitializers As IEnumerable(Of ExpectedInitializer) = New ExpectedInitializer() {New ExpectedInitializer("field01", "New Double()", lineNumber:=2)} Dim boundInitializers = BindInitializersWithoutDiagnostics(typeSymbol, typeSymbol.StaticInitializers) CheckBoundInitializers(expectedInitializers, tree, boundInitializers, isStatic:=True) expectedInitializers = New ExpectedInitializer() { New ExpectedInitializer("field04", "F(Nothing)", lineNumber:=4), New ExpectedInitializer("field05", "New Func(Of String, ULong)(Function(s) s.Length)", lineNumber:=4)} boundInitializers = BindInitializersWithoutDiagnostics(typeSymbol, typeSymbol.InstanceInitializers) CheckBoundInitializers(expectedInitializers, tree, boundInitializers, isStatic:=False) End Sub <WorkItem(539286, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539286")> <Fact> Public Sub Bug5181() Dim source = <compilation name="Bug5181_1"> <file name="a.b"> Class Class1 Public Shared A As Integer = 10 Public B As Integer = 10 + A + Me.F() Public C As Func(Of Integer, Integer) = Function(p) 10 + A + p + Me.F() Public Function F() As Integer Return 10 + A + Me.F() End Function End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(source) Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim firstMeF = tree.FindNodeOrTokenByKind(SyntaxKind.SimpleMemberAccessExpression, 1) Dim secondMeF = tree.FindNodeOrTokenByKind(SyntaxKind.SimpleMemberAccessExpression, 2) Dim thirdMeF = tree.FindNodeOrTokenByKind(SyntaxKind.SimpleMemberAccessExpression, 3) Dim firstMeFSymbol = model.GetSemanticInfoSummary(CType(firstMeF.AsNode(), ExpressionSyntax)).Symbol Dim secondMeFSymbol = model.GetSemanticInfoSummary(CType(secondMeF.AsNode(), ExpressionSyntax)).Symbol Dim thirdMeFSymbol = model.GetSemanticInfoSummary(CType(thirdMeF.AsNode(), ExpressionSyntax)).Symbol Assert.NotNull(firstMeFSymbol) Assert.NotNull(secondMeFSymbol) Assert.NotNull(thirdMeFSymbol) Assert.Equal(firstMeFSymbol, secondMeFSymbol) Assert.Equal(firstMeFSymbol, thirdMeFSymbol) Dim firstMe = tree.FindNodeOrTokenByKind(SyntaxKind.MeExpression, 1) Dim secondMe = tree.FindNodeOrTokenByKind(SyntaxKind.MeExpression, 2) Dim thirdMe = tree.FindNodeOrTokenByKind(SyntaxKind.MeExpression, 3) Dim firstMeSymbol = model.GetSemanticInfoSummary(CType(firstMe.AsNode(), ExpressionSyntax)).Symbol Dim secondMeSymbol = model.GetSemanticInfoSummary(CType(secondMe.AsNode(), ExpressionSyntax)).Symbol Dim thirdMeSymbol = model.GetSemanticInfoSummary(CType(thirdMe.AsNode(), ExpressionSyntax)).Symbol 'Assert.Equal(1, firstMeSymbols.Count) returned 0 symbols 'Assert.Equal(1, secondMeSymbols.Count) 'Assert.Equal(1, thirdMeSymbols.Count) End Sub <Fact> Public Sub Bug6935() Dim source = <compilation name="Bug6935"> <file name="a.b"> Class C2 End C2 Class Class1 Public C2 As New C2() Public Function F() As Boolean Return Me.C2 IsNot Nothing End Function End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(source) Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim firstMeF = tree.FindNodeOrTokenByKind(SyntaxKind.SimpleMemberAccessExpression, 1) Dim firstMeFSymbol = model.GetSemanticInfoSummary(CType(firstMeF.AsNode(), ExpressionSyntax)).Symbol Assert.NotNull(firstMeFSymbol) Assert.Equal(firstMeFSymbol.Name, "C2") End Sub <WorkItem(542375, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542375")> <Fact> Public Sub ConstFieldNonConstValueAsArrayBoundary() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> <![CDATA[ Imports Microsoft.VisualBasic Module Module2 Const x As Integer = AscW(y) Const y As String = ChrW(z) Dim z As Integer = 123 Const Scen1 As Integer = z Sub Cnst100() Dim ArrScen9(Scen1) As Double End Sub End Module ]]> </file> </compilation>) 'BC30059: Constant expression is required. compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_RequiredConstExpr, "AscW(y)"), Diagnostic(ERRID.ERR_RequiredConstExpr, "ChrW(z)"), Diagnostic(ERRID.ERR_RequiredConstExpr, "z")) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub StaticLocalFields() 'As we can't easily get at fields which are non callable by user code such as 'the $STATIC$Goo$001$a we can simply determine that the count of items which 'we expect is present Dim source = <compilation name="StaticLocals"> <file name="a.vb"> Class C Private _Field as integer = 1 Shared Sub Goo() static a as integer = 1 End Sub End Class </file> </compilation> Dim typeSymbol = CompileAndExtractTypeSymbol(source) 'Perhaps we should verify that the members does not include the fields Assert.Equal(3, typeSymbol.GetMembers.Length) Dim Lst_members As New List(Of String) For Each i In typeSymbol.GetMembers Lst_members.Add(i.ToString) Next Assert.Contains("Private _Field As Integer", Lst_members) Assert.Contains("Public Sub New()", Lst_members) Assert.Contains("Public Shared Sub Goo()", Lst_members) End Sub <Fact> Public Sub VbConstantFields_Error() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Interface I : End Interface Interface II : Inherits I : End Interface Interface III : Inherits II : End Interface Interface IV : Inherits III : End Interface Structure SomeStructure : Implements I : End Structure Class SomeClass : Implements I : End Class Class SomeClass2 : Inherits SomeClass : End Class Class Clazz Public Const F = CType(CType(Nothing, SomeStructure), I) Public Const F2 = CType(CType(Nothing, Integer), Object) End Class Class Clazz(Of T As I) Public Const F = CType(CType(Nothing, T), I) End Class Class Clazz3(Of T As {Structure, I}) Public Const F = CType(CType(Nothing, T), I) End Class Class Clazz6(Of T As {Structure}) Public Const F2 = CType(CType(CType(CType(Nothing, T), Object), Object), Object) ' Dev11 does not generate error, but it should Public Const F6 = CType(CType(CType(CType(Nothing, T), T), T), T) ' Dev11 does not generate error, but it should End Class Class Clazz7(Of T) Public Const F = CType(CType(CType(CType(Nothing, T), Object), Object), Object) ' Dev11 does not generate error, but it should End Class Class Clazz9(Of U As {Class, I}, V As U) Public Const F = CType(CType(CType(Nothing, U), V), I) End Class Class Clazz4 Public Const F4 = CType(CType(CType(Nothing, SomeStructure), SomeStructure), SomeStructure) End Class Class ClazzDateTimeDecimal Public Const F2 = CType(#12:00:00 AM#, Object) Public Const F4 = CType(CType(Nothing, Date), Object) Public Const F6 = CType(1.2345D, Object) Public Const F8 = CType(CType(Nothing, Decimal), Object) End Class Class ClazzNullable Public Const F1 = CType(Nothing, Integer?) Public Const F2 = CType(CType(Nothing, Object), Integer?) Public Const F3 = CType(CType(1, Integer), Integer?) Public Const F4 As Integer? = Nothing End Class Class ClazzNullable(Of T As Structure) Public Const F1 = CType(Nothing, T?) Public Const F2 = CType(CType(Nothing, Object), T?) Public Const F4 As T? = Nothing End Class Enum EI : AI : BI : End Enum Enum EB As Byte : AB : BB : End Enum Class ClazzWithEnums Public Const F1 = CType(CType(CType(CType(Nothing, EI), Object), Object), Object) Public Const F3 = CType(CType(CType(CType(Nothing, EB), Object), Object), Object) End Class Class StringConstants Const a As Object = "1" Const b As System.Object = "1" Const c = "1" End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30060: Conversion from 'Object' to 'SomeStructure' cannot occur in a constant expression. Public Const F = CType(CType(Nothing, SomeStructure), I) ~~~~~~~ BC30060: Conversion from 'Integer' to 'Object' cannot occur in a constant expression. Public Const F2 = CType(CType(Nothing, Integer), Object) ~~~~~~~~~~~~~~~~~~~~~~~ BC30060: Conversion from 'Object' to 'T' cannot occur in a constant expression. Public Const F = CType(CType(Nothing, T), I) ~~~~~~~ BC30060: Conversion from 'Object' to 'T' cannot occur in a constant expression. Public Const F = CType(CType(Nothing, T), I) ~~~~~~~ BC30060: Conversion from 'Object' to 'T' cannot occur in a constant expression. Public Const F2 = CType(CType(CType(CType(Nothing, T), Object), Object), Object) ' Dev11 does not generate error, but it should ~~~~~~~ BC30060: Conversion from 'Object' to 'T' cannot occur in a constant expression. Public Const F6 = CType(CType(CType(CType(Nothing, T), T), T), T) ' Dev11 does not generate error, but it should ~~~~~~~ BC30060: Conversion from 'Object' to 'T' cannot occur in a constant expression. Public Const F = CType(CType(CType(CType(Nothing, T), Object), Object), Object) ' Dev11 does not generate error, but it should ~~~~~~~ BC30060: Conversion from 'U' to 'V' cannot occur in a constant expression. Public Const F = CType(CType(CType(Nothing, U), V), I) ~~~~~~~~~~~~~~~~~ BC30060: Conversion from 'Object' to 'SomeStructure' cannot occur in a constant expression. Public Const F4 = CType(CType(CType(Nothing, SomeStructure), SomeStructure), SomeStructure) ~~~~~~~ BC30060: Conversion from 'Date' to 'Object' cannot occur in a constant expression. Public Const F2 = CType(#12:00:00 AM#, Object) ~~~~~~~~~~~~~ BC30060: Conversion from 'Date' to 'Object' cannot occur in a constant expression. Public Const F4 = CType(CType(Nothing, Date), Object) ~~~~~~~~~~~~~~~~~~~~ BC30060: Conversion from 'Decimal' to 'Object' cannot occur in a constant expression. Public Const F6 = CType(1.2345D, Object) ~~~~~~~ BC30060: Conversion from 'Decimal' to 'Object' cannot occur in a constant expression. Public Const F8 = CType(CType(Nothing, Decimal), Object) ~~~~~~~~~~~~~~~~~~~~~~~ BC30060: Conversion from 'Object' to 'Integer?' cannot occur in a constant expression. Public Const F1 = CType(Nothing, Integer?) ~~~~~~~ BC30060: Conversion from 'Object' to 'Integer?' cannot occur in a constant expression. Public Const F2 = CType(CType(Nothing, Object), Integer?) ~~~~~~~~~~~~~~~~~~~~~~ BC30060: Conversion from 'Integer' to 'Integer?' cannot occur in a constant expression. Public Const F3 = CType(CType(1, Integer), Integer?) ~~~~~~~~~~~~~~~~~ BC30424: Constants must be of an intrinsic or enumerated type, not a class, structure, type parameter, or array type. Public Const F4 As Integer? = Nothing ~~~~~~~~ BC30060: Conversion from 'Object' to 'T?' cannot occur in a constant expression. Public Const F1 = CType(Nothing, T?) ~~~~~~~ BC30060: Conversion from 'Object' to 'T?' cannot occur in a constant expression. Public Const F2 = CType(CType(Nothing, Object), T?) ~~~~~~~~~~~~~~~~~~~~~~ BC30424: Constants must be of an intrinsic or enumerated type, not a class, structure, type parameter, or array type. Public Const F4 As T? = Nothing ~~ BC30060: Conversion from 'EI' to 'Object' cannot occur in a constant expression. Public Const F1 = CType(CType(CType(CType(Nothing, EI), Object), Object), Object) ~~~~~~~~~~~~~~~~~~ BC30060: Conversion from 'EB' to 'Object' cannot occur in a constant expression. Public Const F3 = CType(CType(CType(CType(Nothing, EB), Object), Object), Object) ~~~~~~~~~~~~~~~~~~ BC30060: Conversion from 'String' to 'Object' cannot occur in a constant expression. Const b As System.Object = "1" ~~~ </expected>) End Sub Private Const s_ELEMENT_TYPE_U1 = 5 Private Const s_ELEMENT_TYPE_I4 = 8 Private Const s_ELEMENT_TYPE_VALUETYPE = 17 Private Const s_ELEMENT_TYPE_CLASS = 18 Private Const s_ELEMENT_TYPE_OBJECT = 28 Private Const s_FIELD_SIGNATURE_CALLING_CONVENTION = 6 Private ReadOnly _ZERO4 As Byte() = New Byte() {0, 0, 0, 0} Private ReadOnly _ONE4 As Byte() = New Byte() {1, 0, 0, 0} Private ReadOnly _ZERO1 As Byte() = New Byte() {0} Private ReadOnly _ONE1 As Byte() = New Byte() {1} <Fact> Public Sub VbConstantFields_NoError() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Interface I : End Interface Interface II : Inherits I : End Interface Interface III : Inherits II : End Interface Interface IV : Inherits III : End Interface Structure SomeStructure : Implements I : End Structure Class SomeClass : Implements I : End Class Class SomeClass2 : Inherits SomeClass : End Class Class Clazz9(Of T As IV) Public Const F9 = CType(CType(CType(CType(Nothing, IV), III), II), I) End Class Class Clazz3 Public Const F3 = CType(CType(CType(Nothing, SomeClass2), SomeClass), I) Public Const F33 = CType(CType(CType((((Nothing))), SomeClass2), SomeClass), I) End Class Class Clazz2(Of T As {Class, I}) Public Const F22 = CType(CType(Nothing, T), I) 'Dev11 - error, Roslyn - OK End Class Class Clazz7(Of T As {Class}) Public Const F7 = CType(CType(CType(CType(Nothing, T), Object), Object), Object) End Class Class Clazz8(Of T As {Class, IV}) Public Const F8 = CType(CType(CType(CType(CType(Nothing, T), IV), III), II), I) 'Dev11 - error, Roslyn - OK End Class </file> </compilation>, options:=TestOptions.ReleaseDll) CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) Dim bytes = compilation.EmitToArray() Using md = ModuleMetadata.CreateFromImage(bytes) Dim reader = md.MetadataReader Assert.Equal(6, reader.GetTableRowCount(TableIndex.Constant)) Assert.Equal(6, reader.FieldDefinitions.Count) For Each handle In reader.GetConstants() Dim constant = reader.GetConstant(handle) Dim field = reader.GetFieldDefinition(CType(constant.Parent, FieldDefinitionHandle)) Dim name = reader.GetString(field.Name) Dim actual = reader.GetBlobBytes(constant.Value) AssertEx.Equal(_ZERO4, actual) Dim constType = constant.TypeCode Select Case name Case "F9", "F3", "F33", "F22", "F7", "F8" Assert.Equal(s_ELEMENT_TYPE_CLASS, constType) Case Else Assert.True(False) End Select Next End Using End Sub <Fact> Public Sub VbConstantFields_NoError_DateDecimal() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class ClazzDateTimeDecimal Public Const F1 = #12:00:00 AM# Public Const F3 = CType(CType(#12:00:00 AM#, Date), Date) Public Const F5 = 1.2345D Public Const F7 = CType(CType(CType(1.2345D, Decimal), Decimal), Decimal) End Class </file> </compilation>, options:=TestOptions.ReleaseDll) CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) End Sub <Fact> Public Sub VbConstantFields_Enum() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Enum EI : AI : BI : End Enum Enum EB As Byte : AB : BB : End Enum Class Clazz Public Const F2 = CType(Nothing, EI) Public Const F4 = CType(Nothing, EB) Public Const F5 = EI.BI Public Const F6 = EB.BB Public Const F7 As EI = Nothing Public Const F8 As EB = Nothing End Class </file> </compilation>, options:=TestOptions.ReleaseDll) CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) Dim bytes = compilation.EmitToArray() Using md = ModuleMetadata.CreateFromImage(bytes) Dim reader = md.MetadataReader Assert.Equal(10, reader.GetTableRowCount(TableIndex.Constant)) Assert.Equal(10 + 2, reader.FieldDefinitions.Count) For Each handle In reader.GetConstants() Dim constant = reader.GetConstant(handle) Dim field = reader.GetFieldDefinition(CType(constant.Parent, FieldDefinitionHandle)) Dim name = reader.GetString(field.Name) Select Case name Case "F1" ' Constant: int32(0) Assert.Equal(s_ELEMENT_TYPE_I4, constant.TypeCode) AssertEx.Equal(_ZERO4, reader.GetBlobBytes(constant.Value)) ' Field type: System.Object AssertEx.Equal(New Byte() {s_FIELD_SIGNATURE_CALLING_CONVENTION, s_ELEMENT_TYPE_OBJECT}, reader.GetBlobBytes(field.Signature)) Case "F2" ' Constant: int32(0) Assert.Equal(s_ELEMENT_TYPE_I4, constant.TypeCode) AssertEx.Equal(_ZERO4, reader.GetBlobBytes(constant.Value)) ' Field type: int32 AssertEx.Equal(New Byte() {s_FIELD_SIGNATURE_CALLING_CONVENTION, s_ELEMENT_TYPE_I4}, reader.GetBlobBytes(field.Signature)) Case "F3" ' Constant: uint8(0) Assert.Equal(s_ELEMENT_TYPE_U1, constant.TypeCode) AssertEx.Equal(_ZERO1, reader.GetBlobBytes(constant.Value)) ' Field type: System.Object AssertEx.Equal(New Byte() {s_FIELD_SIGNATURE_CALLING_CONVENTION, s_ELEMENT_TYPE_OBJECT}, reader.GetBlobBytes(field.Signature)) Case "F4" ' Constant: uint8(0) Assert.Equal(s_ELEMENT_TYPE_U1, constant.TypeCode) AssertEx.Equal(_ZERO1, reader.GetBlobBytes(constant.Value)) ' Field type: uint8 AssertEx.Equal(New Byte() {s_FIELD_SIGNATURE_CALLING_CONVENTION, s_ELEMENT_TYPE_U1}, reader.GetBlobBytes(field.Signature)) Case "F5" ' Constant: int32(0) Assert.Equal(s_ELEMENT_TYPE_I4, constant.TypeCode) AssertEx.Equal(_ONE4, reader.GetBlobBytes(constant.Value)) ' Field type: int32 AssertEx.Equal(New Byte() {s_FIELD_SIGNATURE_CALLING_CONVENTION, s_ELEMENT_TYPE_I4}, reader.GetBlobBytes(field.Signature)) Case "F6" ' Constant: uint8(0) Assert.Equal(s_ELEMENT_TYPE_U1, constant.TypeCode) AssertEx.Equal(_ONE1, reader.GetBlobBytes(constant.Value)) ' Field type: uint8 AssertEx.Equal(New Byte() {s_FIELD_SIGNATURE_CALLING_CONVENTION, s_ELEMENT_TYPE_U1}, reader.GetBlobBytes(field.Signature)) Case "F7" ' Constant: int32(0) Assert.Equal(s_ELEMENT_TYPE_I4, constant.TypeCode) AssertEx.Equal(_ZERO4, reader.GetBlobBytes(constant.Value)) ' Field type: EI (valuetype) AssertAnyValueType(reader.GetBlobBytes(field.Signature)) Case "F8" ' Constant: uint8(0) Assert.Equal(s_ELEMENT_TYPE_U1, constant.TypeCode) AssertEx.Equal(_ZERO1, reader.GetBlobBytes(constant.Value)) ' Field type: EB (valuetype) AssertAnyValueType(reader.GetBlobBytes(field.Signature)) Case "AI" ' Constant: int32(0) Assert.Equal(s_ELEMENT_TYPE_I4, constant.TypeCode) AssertEx.Equal(_ZERO4, reader.GetBlobBytes(constant.Value)) ' Field type: EI (valuetype) AssertAnyValueType(reader.GetBlobBytes(field.Signature)) Case "BI" ' Constant: int32(0) Assert.Equal(s_ELEMENT_TYPE_I4, constant.TypeCode) AssertEx.Equal(_ONE4, reader.GetBlobBytes(constant.Value)) ' Field type: EI (valuetype) AssertAnyValueType(reader.GetBlobBytes(field.Signature)) Case "AB" ' Constant: uint8(0) Assert.Equal(s_ELEMENT_TYPE_U1, constant.TypeCode) AssertEx.Equal(_ZERO1, reader.GetBlobBytes(constant.Value)) ' Field type: EB (valuetype) AssertAnyValueType(reader.GetBlobBytes(field.Signature)) Case "BB" ' Constant: uint8(0) Assert.Equal(s_ELEMENT_TYPE_U1, constant.TypeCode) AssertEx.Equal(_ONE1, reader.GetBlobBytes(constant.Value)) ' Field type: EB (valuetype) AssertAnyValueType(reader.GetBlobBytes(field.Signature)) Case Else Assert.True(False) End Select Next End Using End Sub Private Sub AssertAnyValueType(actual As Byte()) Assert.Equal(3, actual.Length) Assert.Equal(s_FIELD_SIGNATURE_CALLING_CONVENTION, actual(0)) Assert.Equal(s_ELEMENT_TYPE_VALUETYPE, actual(1)) End Sub <Fact> Public Sub VbParameterDefaults_Error() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Interface I : End Interface Interface II : Inherits I : End Interface Interface III : Inherits II : End Interface Interface IV : Inherits III : End Interface Structure SomeStructure : Implements I : End Structure Class SomeClass : Implements I : End Class Class SomeClass2 : Inherits SomeClass : End Class Interface Clazz Sub s1(Optional F As Object = CType(CType(Nothing, SomeStructure), I)) Sub s2(Optional F As I = CType(CType(Nothing, SomeStructure), I)) Sub s3(Optional F As Object = CType(CType(CType(Nothing, SomeStructure), SomeStructure), SomeStructure)) End Interface Interface Clazz(Of T As I) Sub s1(Optional F As Object = CType(CType(Nothing, T), I)) Sub s2(Optional F As I = CType(CType(Nothing, T), I)) End Interface Interface Clazz3(Of T As {Structure, I}) Sub s1(Optional F As Object = CType(CType(Nothing, T), I)) Sub s2(Optional F As I = CType(CType(Nothing, T), I)) End Interface Interface Clazz6(Of T As Structure) Sub s1(Optional F As Object = CType(CType(CType(CType(Nothing, T), Object), Object), Object)) ' Dev11 - OK, Roslyn - ERROR Sub s2(Optional F As Object = CType(CType(CType(CType(Nothing, T), T), T), T)) ' Dev11 - OK, Roslyn - ERROR End Interface Interface Clazz7(Of T) Sub s1(Optional F As Object = CType(CType(CType(CType(Nothing, T), Object), Object), Object)) ' Dev11 - OK, Roslyn - ERROR Sub s2(Optional F As Object = CType(CType(CType(CType(Nothing, T), T), T), T)) ' Dev11 - OK, Roslyn - ERROR End Interface Interface Clazz9(Of U As {Class, I}, V As U) Sub s1(Optional F As Object = CType(CType(CType(Nothing, U), V), I)) Sub s2(Optional F As I = CType(CType(CType(Nothing, U), V), I)) Sub s3(Optional F As Object = CType(CType(CType(Nothing, V), U), I)) Sub s4(Optional F As I = CType(CType(CType(Nothing, V), U), I)) End Interface Interface ClazzMisc Sub s5(Optional F As Object = CType(Nothing, Integer?)) Sub s8(Optional F As Object = CType(CType(Nothing, Object), Integer?)) Sub s10(Optional F As Object = CType(CType(1, Integer), Integer?)) End Interface Interface ClazzMisc(Of T As Structure) Sub s5(Optional F As Object = CType(Nothing, T?)) Sub s8(Optional F As Object = CType(CType(Nothing, Object), T?)) End Interface Enum EI : AI : BI : End Enum Interface ClazzWithEnums Sub s7(Optional p7 As Object = CType(EI.BI, EI?)) End Interface </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30060: Conversion from 'SomeStructure' to 'I' cannot occur in a constant expression. Sub s1(Optional F As Object = CType(CType(Nothing, SomeStructure), I)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30060: Conversion from 'SomeStructure' to 'I' cannot occur in a constant expression. Sub s2(Optional F As I = CType(CType(Nothing, SomeStructure), I)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30060: Conversion from 'SomeStructure' to 'Object' cannot occur in a constant expression. Sub s3(Optional F As Object = CType(CType(CType(Nothing, SomeStructure), SomeStructure), SomeStructure)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30060: Conversion from 'T' to 'I' cannot occur in a constant expression. Sub s1(Optional F As Object = CType(CType(Nothing, T), I)) ~~~~~~~~~~~~~~~~~ BC30060: Conversion from 'T' to 'I' cannot occur in a constant expression. Sub s2(Optional F As I = CType(CType(Nothing, T), I)) ~~~~~~~~~~~~~~~~~ BC30060: Conversion from 'T' to 'I' cannot occur in a constant expression. Sub s1(Optional F As Object = CType(CType(Nothing, T), I)) ~~~~~~~~~~~~~~~~~ BC30060: Conversion from 'T' to 'I' cannot occur in a constant expression. Sub s2(Optional F As I = CType(CType(Nothing, T), I)) ~~~~~~~~~~~~~~~~~ BC30060: Conversion from 'T' to 'Object' cannot occur in a constant expression. Sub s1(Optional F As Object = CType(CType(CType(CType(Nothing, T), Object), Object), Object)) ' Dev11 - OK, Roslyn - ERROR ~~~~~~~~~~~~~~~~~ BC30060: Conversion from 'T' to 'Object' cannot occur in a constant expression. Sub s2(Optional F As Object = CType(CType(CType(CType(Nothing, T), T), T), T)) ' Dev11 - OK, Roslyn - ERROR ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30060: Conversion from 'T' to 'Object' cannot occur in a constant expression. Sub s1(Optional F As Object = CType(CType(CType(CType(Nothing, T), Object), Object), Object)) ' Dev11 - OK, Roslyn - ERROR ~~~~~~~~~~~~~~~~~ BC30060: Conversion from 'T' to 'Object' cannot occur in a constant expression. Sub s2(Optional F As Object = CType(CType(CType(CType(Nothing, T), T), T), T)) ' Dev11 - OK, Roslyn - ERROR ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30060: Conversion from 'V' to 'I' cannot occur in a constant expression. Sub s1(Optional F As Object = CType(CType(CType(Nothing, U), V), I)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30060: Conversion from 'V' to 'I' cannot occur in a constant expression. Sub s2(Optional F As I = CType(CType(CType(Nothing, U), V), I)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30060: Conversion from 'V' to 'U' cannot occur in a constant expression. Sub s3(Optional F As Object = CType(CType(CType(Nothing, V), U), I)) ~~~~~~~~~~~~~~~~~ BC30060: Conversion from 'V' to 'U' cannot occur in a constant expression. Sub s4(Optional F As I = CType(CType(CType(Nothing, V), U), I)) ~~~~~~~~~~~~~~~~~ BC30060: Conversion from 'Integer?' to 'Object' cannot occur in a constant expression. Sub s5(Optional F As Object = CType(Nothing, Integer?)) ~~~~~~~~~~~~~~~~~~~~~~~~ BC30060: Conversion from 'Integer?' to 'Object' cannot occur in a constant expression. Sub s8(Optional F As Object = CType(CType(Nothing, Object), Integer?)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30060: Conversion from 'Integer?' to 'Object' cannot occur in a constant expression. Sub s10(Optional F As Object = CType(CType(1, Integer), Integer?)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30060: Conversion from 'T?' to 'Object' cannot occur in a constant expression. Sub s5(Optional F As Object = CType(Nothing, T?)) ~~~~~~~~~~~~~~~~~~ BC30060: Conversion from 'T?' to 'Object' cannot occur in a constant expression. Sub s8(Optional F As Object = CType(CType(Nothing, Object), T?)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30060: Conversion from 'EI?' to 'Object' cannot occur in a constant expression. Sub s7(Optional p7 As Object = CType(EI.BI, EI?)) ~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact> Public Sub VbParameterDefaults_NoError() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Interface I : End Interface Interface II : Inherits I : End Interface Interface III : Inherits II : End Interface Interface IV : Inherits III : End Interface Structure SomeStructure : Implements I : End Structure Class SomeClass : Implements I : End Class Class SomeClass2 : Inherits SomeClass : End Class Interface Clazz Sub s1(Optional F1 As SomeStructure = CType(CType(CType(Nothing, SomeStructure), SomeStructure), SomeStructure)) ' Dev11 - ERROR, Roslyn - OK Sub s2(Optional F2 As Object = CType(CType(Nothing, Integer), Object)) ' Dev11 - ERROR, Roslyn - OK Sub s3(Optional F3 As Object = CType(CType(CType(Nothing, SomeClass2), SomeClass), I)) Sub s4(Optional F4 As I = CType(CType(CType(Nothing, SomeClass2), SomeClass), I)) Sub s5(Optional F5 As Object = CType(CType(CType((((Nothing))), SomeClass2), SomeClass), I)) End Interface Interface Clazz2(Of T As {Class, I}) Sub s1(Optional F6 As Object = CType(CType(Nothing, T), I)) ' Dev11 - ERROR, Roslyn - OK Sub s2(Optional F7 As I = CType(CType(Nothing, T), I)) ' Dev11 - ERROR, Roslyn - OK Sub s3(Optional F8 As Object = CType(CType(CType(CType(Nothing, T), Object), Object), Object)) End Interface Interface Clazz2x(Of T As {Class, Iv}) Sub s1(Optional F9 As Object = CType(CType(CType(CType(CType(Nothing, T), IV), III), II), I)) ' Dev11 - ERROR, Roslyn - OK Sub s2(Optional F10 As I = CType(CType(CType(CType(CType(Nothing, T), IV), III), II), I)) ' Dev11 - ERROR, Roslyn - OK End Interface Interface Clazz6(Of T As Structure) Sub s3(Optional F11 As T = CType(CType(CType(CType(Nothing, T), T), T), T)) End Interface Interface Clazz7(Of T) Sub s3(Optional F12 As T = CType(CType(CType(CType(Nothing, T), T), T), T)) End Interface Interface Clazz9(Of T As IV) Sub s1(Optional F13 As Object = CType(CType(CType(CType(Nothing, IV), III), II), I)) Sub s2(Optional F14 As I = CType(CType(CType(CType(Nothing, IV), III), II), I)) End Interface Interface ClazzMisc Sub s1(Optional F15 As Object = CType(#12:00:00 AM#, Object)) ' Dev11 - ERROR, Roslyn - OK Sub s2(Optional F16 As Object = CType(CType(Nothing, Date), Object)) ' Dev11 - ERROR, Roslyn - OK Sub s3(Optional F17 As Object = CType(1.2345D, Object)) ' Dev11 - ERROR, Roslyn - OK Sub s4(Optional F18 As Object = CType(CType(Nothing, Decimal), Object)) ' Dev11 - ERROR, Roslyn - OK Sub s6(Optional F19 As Integer? = CType(Nothing, Integer?)) ' Dev11 - ERROR, Roslyn - OK Sub s7(Optional F20 As Integer? = Nothing) Sub s9(Optional F21 As Integer? = CType(CType(Nothing, Object), Integer?)) ' Dev11 - ERROR, Roslyn - OK Sub s11(Optional F22 As Integer? = CType(CType(1, Integer), Integer?)) ' Dev11 - ERROR, Roslyn - OK Sub s12(Optional F23 As Integer? = 1) Sub s13(Optional F24 As Integer? = CType(1, Integer?)) ' Dev11 - ERROR, Roslyn - OK Sub s14(Optional F25 As Integer? = CType(1, Integer)) End Interface Interface ClazzMisc(Of T As Structure) Sub s6(Optional F26 As T? = CType(Nothing, T?)) ' Dev11 - ERROR, Roslyn - OK Sub s7(Optional F27 As T? = Nothing) Sub s9(Optional F28 As T? = CType(CType(Nothing, Object), T?)) ' Dev11 - ERROR, Roslyn - OK End Interface Enum EI : AI : BI : End Enum Interface ClazzWithEnums Sub s1(Optional F30 As Object = CType(CType(CType(CType(Nothing, EI), Object), Object), Object)) 'Dev11 - ERROR, Roslyn - OK, Int constant!!! Sub s2(Optional F31 As Object = CType(Nothing, EI)) ' Int constant!!! Sub s3(Optional F32 As EI = CType(Nothing, EI)) Sub s4(Optional F33 As EI? = CType(Nothing, EI)) Sub s5(Optional F34 As EI? = CType(Nothing, EI?)) 'Dev11 - ERROR, Roslyn - OK Sub s6(Optional F35 As Object = EI.BI) 'Int constant!!! Sub s8(Optional F36 As Object = CType(EI.BI, Object)) 'Int constant!!! Sub s9(Optional F37 As EI? = CType(EI.BI, EI?)) 'Dev11 - ERROR, Roslyn - OK Sub s10(Optional F38 As EI? = EI.BI) Sub s11(Optional F39 As EI? = Nothing) Sub s12(Optional F40 As EI? = CType(CType(CType(Nothing, Integer), Byte), EI)) Sub s13(Optional F41 As EI? = CType(CType(CType(EI.BI, Integer), Byte), EI)) End Interface </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) Dim bytes = compilation.EmitToArray() Using md = ModuleMetadata.CreateFromImage(bytes) Dim reader = md.MetadataReader Const FIELD_COUNT = 40 Const ATTR_CONST_COUNT = 4 Const ENUM_CONST_COUNT = 2 Assert.Equal(FIELD_COUNT - ATTR_CONST_COUNT + ENUM_CONST_COUNT, reader.GetTableRowCount(TableIndex.Constant)) Assert.Equal(FIELD_COUNT, reader.GetTableRowCount(TableIndex.Param)) For Each handle In reader.GetConstants() Dim constant = reader.GetConstant(handle) If constant.Parent.Kind = HandleKind.Parameter Then Dim paramRow = reader.GetParameter(CType(constant.Parent, ParameterHandle)) Dim name = reader.GetString(paramRow.Name) Select Case name Case "F1", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12", "F13", "F14", "F19", "F20", "F21", "F26", "F27", "F28", "F34", "F39" ' Constant: nullref Assert.Equal(s_ELEMENT_TYPE_CLASS, constant.TypeCode) AssertEx.Equal(_ZERO4, reader.GetBlobBytes(constant.Value)) Case "F2", "F30", "F31", "F32", "F33", "F40" ' Constant: int32(0) Assert.Equal(s_ELEMENT_TYPE_I4, constant.TypeCode) AssertEx.Equal(_ZERO4, reader.GetBlobBytes(constant.Value)) Case "F22", "F23", "F24", "F25", "F35", "F36", "F37", "F38", "F41" ' Constant: int32(1) Assert.Equal(s_ELEMENT_TYPE_I4, constant.TypeCode) AssertEx.Equal(_ONE4, reader.GetBlobBytes(constant.Value)) Case Else Assert.True(False, "Unknown field: " + name) End Select End If Next For Each paramDef In reader.GetParameters() Dim name = reader.GetString(reader.GetParameter(paramDef).Name) ' Just make sure we have attributes on F15, F16, F17, F18 Select Case name Case "F15", "F16", "F17", "F18" Assert.True(HasAnyCustomAttribute(reader, paramDef)) End Select Next End Using End Sub Private Function HasAnyCustomAttribute(reader As MetadataReader, parent As EntityHandle) As Boolean For Each ca In reader.CustomAttributes If reader.GetCustomAttribute(ca).Parent = parent Then Return True End If Next Return False End Function <Fact()> Public Sub ConstantOfWrongType() Dim ilSource = <![CDATA[ .class public auto ansi Clazz extends [mscorlib]System.Object { .field public static literal object a = int32(0x00000001) .field public static literal object b = "abc" .method public specialname rtspecialname instance void .ctor() cil managed { .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 9 (0x9) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: nop IL_0007: nop IL_0008: ret } // end of method Clazz::.ctor } ]]> Dim vbSource = <compilation> <file name="a.vb"> Imports System Module C Sub S() Console.WriteLine(Clazz.a.ToString()) Console.WriteLine(Clazz.b.ToString()) End Sub End Module </file> </compilation> Dim reference As MetadataReference = Nothing Using tempAssembly = IlasmUtilities.CreateTempAssembly(ilSource.Value) reference = MetadataReference.CreateFromImage(ReadFromFile(tempAssembly.Path)) End Using Dim compilation = CreateEmptyCompilationWithReferences(vbSource, {MscorlibRef, MsvbRef, reference}, TestOptions.ReleaseDll) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> BC30799: Field 'Clazz.a' has an invalid constant value. Console.WriteLine(Clazz.a.ToString()) ~~~~~~~ BC30799: Field 'Clazz.b' has an invalid constant value. Console.WriteLine(Clazz.b.ToString()) ~~~~~~~ </errors>) End Sub <Fact, WorkItem(1028, "https://github.com/dotnet/roslyn/issues/1028")> Public Sub WriteOfReadonlySharedMemberOfAnotherInstantiation01() Dim source = <compilation> <file name="a.vb"> Class Goo(Of T) Shared Sub New() Goo(Of Integer).X = 12 Goo(Of Integer).Y = 12 Goo(Of T).X = 12 Goo(Of T).Y = 12 End Sub Public Shared ReadOnly X As Integer Public Shared ReadOnly Property Y As Integer = 0 End Class </file> </compilation> Dim standardCompilation = CompilationUtils.CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseDll) Dim strictCompilation = CompilationUtils.CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseDll, parseOptions:=TestOptions.Regular.WithStrictFeature()) CompilationUtils.AssertTheseDiagnostics(standardCompilation, <expected> BC30526: Property 'Y' is 'ReadOnly'. Goo(Of Integer).Y = 12 ~~~~~~~~~~~~~~~~~~~~~~ </expected>) CompilationUtils.AssertTheseDiagnostics(strictCompilation, <expected> BC30064: 'ReadOnly' variable cannot be the target of an assignment. Goo(Of Integer).X = 12 ~~~~~~~~~~~~~~~~~ BC30526: Property 'Y' is 'ReadOnly'. Goo(Of Integer).Y = 12 ~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact, WorkItem(1028, "https://github.com/dotnet/roslyn/issues/1028")> Public Sub WriteOfReadonlySharedMemberOfAnotherInstantiation02() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module M1 Sub Main() Console.WriteLine(Goo(Of Long).X) Console.WriteLine(Goo(Of Integer).X) Console.WriteLine(Goo(Of String).X) Console.WriteLine(Goo(Of Integer).X) End Sub End Module Public Class Goo(Of T) Shared Sub New() Console.WriteLine("Initializing for {0}", GetType(T)) Goo(Of Integer).X = GetType(T).Name End Sub Public Shared ReadOnly X As String End Class </file> </compilation>, verify:=Verification.Fails, expectedOutput:=<![CDATA[Initializing for System.Int64 Initializing for System.Int32 Int64 Initializing for System.String String ]]>) End Sub #Region "Helpers" Private Shared Function CompileAndExtractTypeSymbol(sources As Xml.Linq.XElement, Optional typeName As String = "C") As SourceNamedTypeSymbol Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(sources) Dim typeSymbol = DirectCast(compilation.SourceModule.GlobalNamespace.GetTypeMembers(typeName).Single(), SourceNamedTypeSymbol) Return typeSymbol End Function Private Shared Function GetMember(sources As Xml.Linq.XElement, fieldName As String, Optional typeName As String = "C") As Symbol Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(sources) Dim symbol = DirectCast(compilation.SourceModule.GlobalNamespace.GetTypeMembers(typeName).Single.GetMembers(fieldName).Single(), Symbol) Return symbol End Function Private Shared Function HasSynthesizedStaticConstructor(typeSymbol As NamedTypeSymbol) As Boolean For Each member In typeSymbol.GetMembers(WellKnownMemberNames.StaticConstructorName) If member.IsImplicitlyDeclared Then Return True End If Next Return False End Function Private Shared Function IsBeforeFieldInit(typeSymbol As NamedTypeSymbol) As Boolean Return (DirectCast(typeSymbol.GetCciAdapter(), Microsoft.Cci.ITypeDefinition)).IsBeforeFieldInit End Function Private Shared Function IsStatic(symbol As Symbol) As Boolean Return (DirectCast(symbol.GetCciAdapter(), Microsoft.Cci.IFieldDefinition)).IsStatic End Function Private Shared Sub CompileAndCheckInitializers(sources As Xml.Linq.XElement, expectedInstanceInitializers As IEnumerable(Of ExpectedInitializer), expectedStaticInitializers As IEnumerable(Of ExpectedInitializer)) ' Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(sources) Dim typeSymbol = DirectCast(compilation.SourceModule.GlobalNamespace.GetTypeMembers("C").Single(), SourceNamedTypeSymbol) Dim syntaxTree = compilation.SyntaxTrees.First() Dim boundInstanceInitializers = BindInitializersWithoutDiagnostics(typeSymbol, typeSymbol.InstanceInitializers) CheckBoundInitializers(expectedInstanceInitializers, syntaxTree, boundInstanceInitializers, isStatic:=False) Dim boundStaticInitializers = BindInitializersWithoutDiagnostics(typeSymbol, typeSymbol.StaticInitializers) CheckBoundInitializers(expectedStaticInitializers, syntaxTree, boundStaticInitializers, isStatic:=True) End Sub Private Shared Sub CheckBoundInitializers(expectedInitializers As IEnumerable(Of ExpectedInitializer), syntaxTree As SyntaxTree, boundInitializers As ImmutableArray(Of BoundInitializer), isStatic As Boolean) If expectedInitializers Is Nothing Then Assert.[True](boundInitializers.IsEmpty) Else Assert.[True](Not boundInitializers.IsDefault) Dim numInitializers As Integer = expectedInitializers.Count() Assert.Equal(numInitializers, boundInitializers.Length) Dim i As Integer = 0 For Each expectedInitializer In expectedInitializers Dim boundInit = boundInitializers(i) i += 1 Assert.[True](boundInit.Kind = BoundKind.FieldInitializer OrElse boundInit.Kind = BoundKind.PropertyInitializer) Dim boundFieldInit = DirectCast(boundInit, BoundFieldOrPropertyInitializer) Dim initValueSyntax = boundFieldInit.InitialValue.Syntax If boundInit.Syntax.Kind <> SyntaxKind.AsNewClause Then Assert.Same(initValueSyntax.Parent, boundInit.Syntax) Assert.Equal(expectedInitializer.InitialValue, initValueSyntax.ToString()) End If Dim initValueLineNumber = syntaxTree.GetLineSpan(initValueSyntax.Span).StartLinePosition.Line Assert.Equal(expectedInitializer.LineNumber, initValueLineNumber) Dim fieldOrPropertySymbol As Symbol If boundInit.Kind = BoundKind.FieldInitializer Then fieldOrPropertySymbol = DirectCast(boundFieldInit, BoundFieldInitializer).InitializedFields.First Else fieldOrPropertySymbol = DirectCast(boundFieldInit, BoundPropertyInitializer).InitializedProperties.First End If Assert.Equal(expectedInitializer.FieldName, fieldOrPropertySymbol.Name) Dim boundReceiver As BoundExpression Select Case boundFieldInit.MemberAccessExpressionOpt.Kind Case BoundKind.PropertyAccess boundReceiver = DirectCast(boundFieldInit.MemberAccessExpressionOpt, BoundPropertyAccess).ReceiverOpt Case BoundKind.FieldAccess boundReceiver = DirectCast(boundFieldInit.MemberAccessExpressionOpt, BoundFieldAccess).ReceiverOpt Case Else Throw TestExceptionUtilities.UnexpectedValue(boundFieldInit.MemberAccessExpressionOpt.Kind) End Select Assert.Equal(BoundKind.FieldAccess, boundFieldInit.MemberAccessExpressionOpt.Kind) If isStatic Then Assert.Null(boundReceiver) Else Assert.Equal(BoundKind.MeReference, boundReceiver.Kind) End If Next End If End Sub Private Shared Function BindInitializersWithoutDiagnostics(typeSymbol As SourceNamedTypeSymbol, initializers As ImmutableArray(Of ImmutableArray(Of FieldOrPropertyInitializer))) As ImmutableArray(Of BoundInitializer) Dim diagnostics As DiagnosticBag = DiagnosticBag.GetInstance() Dim processedFieldInitializers = Binder.BindFieldAndPropertyInitializers(typeSymbol, initializers, Nothing, New BindingDiagnosticBag(diagnostics)) Dim sealedDiagnostics = diagnostics.ToReadOnlyAndFree() For Each d In sealedDiagnostics Console.WriteLine(d) Next Assert.False(sealedDiagnostics.Any()) Return processedFieldInitializers End Function Public Class ExpectedInitializer Public Property FieldName As String Public Property InitialValue As String Public Property LineNumber As Integer Public Sub New(fieldName As String, initialValue As String, lineNumber As Integer) Me.FieldName = fieldName Me.InitialValue = initialValue Me.LineNumber = lineNumber End Sub End Class #End Region End Class End Namespace
' 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.Reflection.Metadata Imports System.Reflection.Metadata.Ecma335 Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Public Class FieldInitializerBindingTests Inherits BasicTestBase <Fact> Public Sub NoInitializers() Dim source = <compilation name="NoInitializers"> <file name="fi.vb"> Class C Shared s1 as String Dim i1 As Integer End Class </file> </compilation> Dim expectedStaticInitializers As IEnumerable(Of ExpectedInitializer) = Nothing Dim expectedInstanceInitializers As IEnumerable(Of ExpectedInitializer) = Nothing CompileAndCheckInitializers(source, expectedInstanceInitializers, expectedStaticInitializers) End Sub <Fact> Public Sub ConstantInstanceInitializer() Dim source = <compilation name="ConstantInstanceInitializer"> <file name="fi.vb"> Class C Shared s1 as String Dim i1 As Integer = 1 End Class </file> </compilation> Dim expectedStaticInitializers As IEnumerable(Of ExpectedInitializer) = Nothing Dim expectedInstanceInitializers As IEnumerable(Of ExpectedInitializer) = New ExpectedInitializer() {New ExpectedInitializer("i1", "1", lineNumber:=2)} CompileAndCheckInitializers(source, expectedInstanceInitializers, expectedStaticInitializers) End Sub <Fact> Public Sub ConstantStaticInitializer() Dim source = <compilation name="ConstantStaticInitializer"> <file name="fi.vb"> Class C Shared s1 as String = "1" Dim i1 As Integer End Class </file> </compilation> Dim expectedStaticInitializers As IEnumerable(Of ExpectedInitializer) = New ExpectedInitializer() {New ExpectedInitializer("s1", """1""", lineNumber:=1)} Dim expectedInstanceInitializers As IEnumerable(Of ExpectedInitializer) = Nothing CompileAndCheckInitializers(source, expectedInstanceInitializers, expectedStaticInitializers) End Sub <Fact> Public Sub ExpressionInstanceInitializer() Dim source = <compilation name="ExpressionInstanceInitializer"> <file name="fi.vb"> Class C Shared s1 As String Dim i1 As Integer = 1 + Goo() Dim i2 As New C() Shared Function Goo() As Integer Return 1 End Function End Class </file> </compilation> Dim expectedStaticInitializers As IEnumerable(Of ExpectedInitializer) = Nothing Dim expectedInstanceInitializers As IEnumerable(Of ExpectedInitializer) = New ExpectedInitializer() {New ExpectedInitializer("i1", "1 + Goo()", lineNumber:=2), New ExpectedInitializer("i2", "As New C()", lineNumber:=3)} CompileAndCheckInitializers(source, expectedInstanceInitializers, expectedStaticInitializers) End Sub <Fact> Public Sub ExpressionStaticInitializer() Dim source = <compilation name="ExpressionStaticInitializer"> <file name="fi.vb"> Class C Shared s1 As Integer = 1 + Goo() Dim i1 As Integer Shared Function Goo() As Integer Return 1 End Function End Class </file> </compilation> Dim expectedStaticInitializers As IEnumerable(Of ExpectedInitializer) = New ExpectedInitializer() {New ExpectedInitializer("s1", "1 + Goo()", lineNumber:=1)} Dim expectedInstanceInitializers As IEnumerable(Of ExpectedInitializer) = Nothing CompileAndCheckInitializers(source, expectedInstanceInitializers, expectedStaticInitializers) End Sub <Fact> Public Sub InitializerOrder() Dim source = <compilation name="InitializerOrder"> <file name="fi.vb"> Class C Shared s1 As Integer = 1 Shared s2 As Integer = 2 Shared s3 As Integer = 3 Dim i1 As Integer = 1 Dim i2 As Integer = 2 Dim i3 As Integer = 3 End Class </file> </compilation> Dim expectedStaticInitializers As IEnumerable(Of ExpectedInitializer) = New ExpectedInitializer() {New ExpectedInitializer("s1", "1", lineNumber:=1), New ExpectedInitializer("s2", "2", lineNumber:=2), New ExpectedInitializer("s3", "3", lineNumber:=3)} Dim expectedInstanceInitializers As IEnumerable(Of ExpectedInitializer) = New ExpectedInitializer() {New ExpectedInitializer("i1", "1", lineNumber:=4), New ExpectedInitializer("i2", "2", lineNumber:=5), New ExpectedInitializer("i3", "3", lineNumber:=6)} CompileAndCheckInitializers(source, expectedInstanceInitializers, expectedStaticInitializers) End Sub <Fact> Public Sub AllPartialClasses() Dim source = <compilation name="AllPartialClasses"> <file name="fi.vb"> Partial Class C Shared s1 As Integer = 1 Dim i1 As Integer = 1 End Class Partial Class C Shared s2 As Integer = 2 Dim i2 As Integer = 2 End Class </file> </compilation> Dim expectedStaticInitializers As IEnumerable(Of ExpectedInitializer) = New ExpectedInitializer() {New ExpectedInitializer("s1", "1", lineNumber:=1), New ExpectedInitializer("s2", "2", lineNumber:=5)} Dim expectedInstanceInitializers As IEnumerable(Of ExpectedInitializer) = New ExpectedInitializer() {New ExpectedInitializer("i1", "1", lineNumber:=2), New ExpectedInitializer("i2", "2", lineNumber:=6)} CompileAndCheckInitializers(source, expectedInstanceInitializers, expectedStaticInitializers) End Sub <Fact> Public Sub SomePartialClasses() Dim source = <compilation name="SomePartialClasses"> <file name="fi.vb"> Partial Class C Shared s1 As Integer = 1 Dim i1 As Integer = 1 End Class Partial Class C Shared s2 As Integer = 2 Dim i2 As Integer = 2 End Class Partial Class C Shared s3 As Integer Dim i3 As Integer End Class </file> </compilation> Dim expectedStaticInitializers As IEnumerable(Of ExpectedInitializer) = New ExpectedInitializer() {New ExpectedInitializer("s1", "1", lineNumber:=1), New ExpectedInitializer("s2", "2", lineNumber:=5)} Dim expectedInstanceInitializers As IEnumerable(Of ExpectedInitializer) = New ExpectedInitializer() {New ExpectedInitializer("i1", "1", lineNumber:=2), New ExpectedInitializer("i2", "2", lineNumber:=6)} CompileAndCheckInitializers(source, expectedInstanceInitializers, expectedStaticInitializers) End Sub <Fact> Public Sub NoStaticMembers() Dim source = <compilation name="NoStaticMembers"> <file name="fi.vb"> Class C Dim i1 As Integer End Class </file> </compilation> Dim typeSymbol = CompileAndExtractTypeSymbol(source) Assert.False(HasSynthesizedStaticConstructor(typeSymbol)) Assert.False(IsBeforeFieldInit(typeSymbol)) Assert.False(IsStatic(GetMember(source, "i1"))) End Sub <Fact> Public Sub NoStaticFields() Dim source = <compilation name="NoStaticFields"> <file name="fi.vb"> Class C Dim i1 As Integer Shared Sub Goo() End Sub End Class </file> </compilation> Dim typeSymbol = CompileAndExtractTypeSymbol(source) Assert.False(HasSynthesizedStaticConstructor(typeSymbol)) Assert.False(IsBeforeFieldInit(typeSymbol)) Assert.False(IsStatic(GetMember(source, "i1"))) End Sub <Fact> Public Sub NoStaticInitializers() Dim source = <compilation name="NoStaticInitializers"> <file name="fi.vb"> Class C Dim i1 As Integer Shared s1 As Integer Shared Sub Goo() End Sub End Class </file> </compilation> Dim typeSymbol = CompileAndExtractTypeSymbol(source) Assert.False(HasSynthesizedStaticConstructor(typeSymbol)) Assert.False(IsBeforeFieldInit(typeSymbol)) Assert.False(IsStatic(GetMember(source, "i1"))) Assert.True(IsStatic(GetMember(source, "s1"))) End Sub <Fact> Public Sub StaticInitializers() Dim source = <compilation name="StaticInitializers"> <file name="fi.vb"> Class C Dim i1 As Integer Shared s1 As Integer = 1 Shared Sub Goo() End Sub End Class </file> </compilation> Dim typeSymbol = CompileAndExtractTypeSymbol(source) Assert.True(HasSynthesizedStaticConstructor(typeSymbol)) Assert.True(IsBeforeFieldInit(typeSymbol)) Assert.False(IsStatic(GetMember(source, "i1"))) Assert.True(IsStatic(GetMember(source, "s1"))) End Sub <Fact> Public Sub ConstantInitializers() Dim source = <compilation name="ConstantInitializers"> <file name="fi.vb"> Class C Dim i1 As Integer Const s1 As Integer = 1 Shared Sub Goo() End Sub End Class </file> </compilation> Dim typeSymbol = CompileAndExtractTypeSymbol(source) Assert.False(HasSynthesizedStaticConstructor(typeSymbol)) Assert.False(IsBeforeFieldInit(typeSymbol)) Assert.False(IsStatic(GetMember(source, "i1"))) Assert.True(IsStatic(GetMember(source, "s1"))) End Sub <Fact> Public Sub SourceStaticConstructorNoStaticMembers() Dim source = <compilation name="SourceStaticConstructorNoStaticMembers"> <file name="fi.vb"> Class C Shared Sub New() End Sub Dim i1 As Integer End Class </file> </compilation> Dim typeSymbol = CompileAndExtractTypeSymbol(source) Assert.False(HasSynthesizedStaticConstructor(typeSymbol)) Assert.False(IsBeforeFieldInit(typeSymbol)) End Sub <Fact> Public Sub SourceStaticConstructorNoStaticFields() Dim source = <compilation name="SourceStaticConstructorNoStaticFields"> <file name="fi.vb"> Class C Shared Sub New() End Sub Dim i1 As Integer Shared Sub Goo() End Sub End Class </file> </compilation> Dim typeSymbol = CompileAndExtractTypeSymbol(source) Assert.False(HasSynthesizedStaticConstructor(typeSymbol)) Assert.False(IsBeforeFieldInit(typeSymbol)) End Sub <Fact> Public Sub SourceStaticConstructorNoStaticInitializers() Dim source = <compilation name="SourceStaticConstructorNoStaticInitializers"> <file name="fi.vb"> Class C Shared Sub New() End Sub Dim i1 As Integer Shared s1 As Integer Shared Sub Goo() End Sub End Class </file> </compilation> Dim typeSymbol = CompileAndExtractTypeSymbol(source) Assert.False(HasSynthesizedStaticConstructor(typeSymbol)) Assert.False(IsBeforeFieldInit(typeSymbol)) End Sub <Fact> Public Sub SourceStaticConstructorStaticInitializers() Dim source = <compilation name="SourceStaticConstructorStaticInitializers"> <file name="fi.vb"> Class C Shared Sub New() End Sub Dim i1 As Integer Shared s1 As Integer = 1 Shared Sub Goo() End Sub End Class </file> </compilation> Dim typeSymbol = CompileAndExtractTypeSymbol(source) Assert.False(HasSynthesizedStaticConstructor(typeSymbol)) Assert.False(IsBeforeFieldInit(typeSymbol)) End Sub <Fact> Public Sub SourceStaticConstructorConstantInitializers() Dim source = <compilation name="SourceStaticConstructorConstantInitializers"> <file name="fi.vb"> Class C Shared Sub New() End Sub Dim i1 As Integer Const s1 As Integer = 1 Shared Sub Goo() End Sub End Class </file> </compilation> Dim typeSymbol = CompileAndExtractTypeSymbol(source) Assert.False(HasSynthesizedStaticConstructor(typeSymbol)) Assert.False(IsBeforeFieldInit(typeSymbol)) End Sub <Fact> Public Sub SourceSingleDimensionArrayWithInitializers() Dim source = <compilation name="Array1D.vb"> <file name="a.cs">Imports System Class Test Friend Shared ary01 As Short() = {+1, -2, 0}, ary02() As Single = {Math.Sqrt(2.0), 1.234!} ReadOnly ary03() = {"1", ary01(0).ToString(), Nothing, ""}, ary04 = {1, F(Nothing)} Function F(o As Object) As String If (o Is Nothing) Then Return Nothing End If Return o.ToString() End Function End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(source) Dim tree = compilation.SyntaxTrees(0) Dim typeSymbol = DirectCast(compilation.SourceModule.GlobalNamespace.GetTypeMembers("Test").Single(), SourceNamedTypeSymbol) Dim ary = DirectCast(typeSymbol.GetMembers("ary01").FirstOrDefault(), FieldSymbol) Assert.True(ary.IsShared) Assert.Equal(TypeKind.Array, ary.Type.TypeKind) Assert.Equal("System.Int16()", ary.Type.ToDisplayString(SymbolDisplayFormat.TestFormat)) ary = DirectCast(typeSymbol.GetMembers("ary02").FirstOrDefault(), FieldSymbol) Assert.True(ary.IsShared) Assert.Equal(TypeKind.Array, ary.Type.TypeKind) Assert.Equal("System.Single()", ary.Type.ToDisplayString(SymbolDisplayFormat.TestFormat)) ary = DirectCast(typeSymbol.GetMembers("ary03").FirstOrDefault(), FieldSymbol) Assert.True(ary.IsReadOnly) Assert.Equal(TypeKind.Array, ary.Type.TypeKind) Assert.Equal("System.Object()", ary.Type.ToDisplayString(SymbolDisplayFormat.TestFormat)) ary = DirectCast(typeSymbol.GetMembers("ary04").FirstOrDefault(), FieldSymbol) Assert.True(ary.IsReadOnly) Assert.Equal(TypeKind.Class, ary.Type.TypeKind) Assert.Equal("System.Object", ary.Type.ToDisplayString(SymbolDisplayFormat.TestFormat)) '''' NYI: collection initializer 'Dim expectedInitializers As IEnumerable(Of ExpectedInitializer) = _ 'New ExpectedInitializer() {New ExpectedInitializer("ary01", "{+1, -2, 0}", lineNumber:=2), ' New ExpectedInitializer("ary02", "{Math.Sqrt(2.0), 1.234!}", lineNumber:=2)} 'Dim boundInitializers = BindInitializersWithoutDiagnostics(typeSymbol, typeSymbol.StaticInitializers) 'CheckBoundInitializers(expectedInitializers, tree, boundInitializers, isStatic:=True) 'expectedInitializers = New ExpectedInitializer() { ' New ExpectedInitializer("ary03", "{""1"", ary01(0).ToString(), Nothing, """"}", lineNumber:=3), ' New ExpectedInitializer("ary04", "{1, F(Nothing)}", lineNumber:=3)} 'boundInitializers = BindInitializersWithoutDiagnostics(typeSymbol, typeSymbol.InstanceInitializers) 'CheckBoundInitializers(expectedInitializers, tree, boundInitializers, isStatic:=False) End Sub <Fact> Public Sub SourceFieldInitializers007() Dim source = <compilation name="FieldInit.dll"> <file name="aaa.cs.vb">Imports System Class Test Friend Shared field01 As New Double() Const field02 = -2147483648 - 1, field03 = True + True ' -2 ReadOnly field04 = F(Nothing), field05 As New Func(Of String, ULong)(Function(s) s.Length) Function F(o As Object) As String Return Nothing End Function End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(source) Dim tree = compilation.SyntaxTrees(0) Dim typeSymbol = DirectCast(compilation.SourceModule.GlobalNamespace.GetTypeMembers("Test").Single(), SourceNamedTypeSymbol) Dim field = DirectCast(typeSymbol.GetMembers("field01").FirstOrDefault(), FieldSymbol) Assert.True(field.IsShared) Assert.Equal(TypeKind.Structure, field.Type.TypeKind) Assert.Equal("System.Double", field.Type.ToDisplayString(SymbolDisplayFormat.TestFormat)) field = DirectCast(typeSymbol.GetMembers("field02").FirstOrDefault(), FieldSymbol) Assert.True(field.IsConst) Assert.Equal(-2147483649, field.ConstantValue) Assert.Equal(TypeKind.Structure, field.Type.TypeKind) Assert.Equal("System.Int64", field.Type.ToDisplayString(SymbolDisplayFormat.TestFormat)) field = DirectCast(typeSymbol.GetMembers("field03").FirstOrDefault(), FieldSymbol) Assert.True(field.IsConst) Assert.Equal(CShort(-2), field.ConstantValue) Assert.Equal(TypeKind.Structure, field.Type.TypeKind) Assert.Equal("System.Int16", field.Type.ToDisplayString(SymbolDisplayFormat.TestFormat)) field = DirectCast(typeSymbol.GetMembers("field04").FirstOrDefault(), FieldSymbol) Assert.True(field.IsReadOnly) Assert.Equal(TypeKind.Class, field.Type.TypeKind) Assert.Equal("System.Object", field.Type.ToDisplayString(SymbolDisplayFormat.TestFormat)) field = DirectCast(typeSymbol.GetMembers("field05").FirstOrDefault(), FieldSymbol) Assert.True(field.IsReadOnly) Assert.Equal(TypeKind.Delegate, field.Type.TypeKind) Assert.Equal("System.Func(Of System.String, System.UInt64)", field.Type.ToDisplayString(SymbolDisplayFormat.TestFormat)) Dim expectedInitializers As IEnumerable(Of ExpectedInitializer) = New ExpectedInitializer() {New ExpectedInitializer("field01", "New Double()", lineNumber:=2)} Dim boundInitializers = BindInitializersWithoutDiagnostics(typeSymbol, typeSymbol.StaticInitializers) CheckBoundInitializers(expectedInitializers, tree, boundInitializers, isStatic:=True) expectedInitializers = New ExpectedInitializer() { New ExpectedInitializer("field04", "F(Nothing)", lineNumber:=4), New ExpectedInitializer("field05", "New Func(Of String, ULong)(Function(s) s.Length)", lineNumber:=4)} boundInitializers = BindInitializersWithoutDiagnostics(typeSymbol, typeSymbol.InstanceInitializers) CheckBoundInitializers(expectedInitializers, tree, boundInitializers, isStatic:=False) End Sub <WorkItem(539286, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539286")> <Fact> Public Sub Bug5181() Dim source = <compilation name="Bug5181_1"> <file name="a.b"> Class Class1 Public Shared A As Integer = 10 Public B As Integer = 10 + A + Me.F() Public C As Func(Of Integer, Integer) = Function(p) 10 + A + p + Me.F() Public Function F() As Integer Return 10 + A + Me.F() End Function End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(source) Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim firstMeF = tree.FindNodeOrTokenByKind(SyntaxKind.SimpleMemberAccessExpression, 1) Dim secondMeF = tree.FindNodeOrTokenByKind(SyntaxKind.SimpleMemberAccessExpression, 2) Dim thirdMeF = tree.FindNodeOrTokenByKind(SyntaxKind.SimpleMemberAccessExpression, 3) Dim firstMeFSymbol = model.GetSemanticInfoSummary(CType(firstMeF.AsNode(), ExpressionSyntax)).Symbol Dim secondMeFSymbol = model.GetSemanticInfoSummary(CType(secondMeF.AsNode(), ExpressionSyntax)).Symbol Dim thirdMeFSymbol = model.GetSemanticInfoSummary(CType(thirdMeF.AsNode(), ExpressionSyntax)).Symbol Assert.NotNull(firstMeFSymbol) Assert.NotNull(secondMeFSymbol) Assert.NotNull(thirdMeFSymbol) Assert.Equal(firstMeFSymbol, secondMeFSymbol) Assert.Equal(firstMeFSymbol, thirdMeFSymbol) Dim firstMe = tree.FindNodeOrTokenByKind(SyntaxKind.MeExpression, 1) Dim secondMe = tree.FindNodeOrTokenByKind(SyntaxKind.MeExpression, 2) Dim thirdMe = tree.FindNodeOrTokenByKind(SyntaxKind.MeExpression, 3) Dim firstMeSymbol = model.GetSemanticInfoSummary(CType(firstMe.AsNode(), ExpressionSyntax)).Symbol Dim secondMeSymbol = model.GetSemanticInfoSummary(CType(secondMe.AsNode(), ExpressionSyntax)).Symbol Dim thirdMeSymbol = model.GetSemanticInfoSummary(CType(thirdMe.AsNode(), ExpressionSyntax)).Symbol 'Assert.Equal(1, firstMeSymbols.Count) returned 0 symbols 'Assert.Equal(1, secondMeSymbols.Count) 'Assert.Equal(1, thirdMeSymbols.Count) End Sub <Fact> Public Sub Bug6935() Dim source = <compilation name="Bug6935"> <file name="a.b"> Class C2 End C2 Class Class1 Public C2 As New C2() Public Function F() As Boolean Return Me.C2 IsNot Nothing End Function End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(source) Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim firstMeF = tree.FindNodeOrTokenByKind(SyntaxKind.SimpleMemberAccessExpression, 1) Dim firstMeFSymbol = model.GetSemanticInfoSummary(CType(firstMeF.AsNode(), ExpressionSyntax)).Symbol Assert.NotNull(firstMeFSymbol) Assert.Equal(firstMeFSymbol.Name, "C2") End Sub <WorkItem(542375, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542375")> <Fact> Public Sub ConstFieldNonConstValueAsArrayBoundary() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> <![CDATA[ Imports Microsoft.VisualBasic Module Module2 Const x As Integer = AscW(y) Const y As String = ChrW(z) Dim z As Integer = 123 Const Scen1 As Integer = z Sub Cnst100() Dim ArrScen9(Scen1) As Double End Sub End Module ]]> </file> </compilation>) 'BC30059: Constant expression is required. compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_RequiredConstExpr, "AscW(y)"), Diagnostic(ERRID.ERR_RequiredConstExpr, "ChrW(z)"), Diagnostic(ERRID.ERR_RequiredConstExpr, "z")) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub StaticLocalFields() 'As we can't easily get at fields which are non callable by user code such as 'the $STATIC$Goo$001$a we can simply determine that the count of items which 'we expect is present Dim source = <compilation name="StaticLocals"> <file name="a.vb"> Class C Private _Field as integer = 1 Shared Sub Goo() static a as integer = 1 End Sub End Class </file> </compilation> Dim typeSymbol = CompileAndExtractTypeSymbol(source) 'Perhaps we should verify that the members does not include the fields Assert.Equal(3, typeSymbol.GetMembers.Length) Dim Lst_members As New List(Of String) For Each i In typeSymbol.GetMembers Lst_members.Add(i.ToString) Next Assert.Contains("Private _Field As Integer", Lst_members) Assert.Contains("Public Sub New()", Lst_members) Assert.Contains("Public Shared Sub Goo()", Lst_members) End Sub <Fact> Public Sub VbConstantFields_Error() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Interface I : End Interface Interface II : Inherits I : End Interface Interface III : Inherits II : End Interface Interface IV : Inherits III : End Interface Structure SomeStructure : Implements I : End Structure Class SomeClass : Implements I : End Class Class SomeClass2 : Inherits SomeClass : End Class Class Clazz Public Const F = CType(CType(Nothing, SomeStructure), I) Public Const F2 = CType(CType(Nothing, Integer), Object) End Class Class Clazz(Of T As I) Public Const F = CType(CType(Nothing, T), I) End Class Class Clazz3(Of T As {Structure, I}) Public Const F = CType(CType(Nothing, T), I) End Class Class Clazz6(Of T As {Structure}) Public Const F2 = CType(CType(CType(CType(Nothing, T), Object), Object), Object) ' Dev11 does not generate error, but it should Public Const F6 = CType(CType(CType(CType(Nothing, T), T), T), T) ' Dev11 does not generate error, but it should End Class Class Clazz7(Of T) Public Const F = CType(CType(CType(CType(Nothing, T), Object), Object), Object) ' Dev11 does not generate error, but it should End Class Class Clazz9(Of U As {Class, I}, V As U) Public Const F = CType(CType(CType(Nothing, U), V), I) End Class Class Clazz4 Public Const F4 = CType(CType(CType(Nothing, SomeStructure), SomeStructure), SomeStructure) End Class Class ClazzDateTimeDecimal Public Const F2 = CType(#12:00:00 AM#, Object) Public Const F4 = CType(CType(Nothing, Date), Object) Public Const F6 = CType(1.2345D, Object) Public Const F8 = CType(CType(Nothing, Decimal), Object) End Class Class ClazzNullable Public Const F1 = CType(Nothing, Integer?) Public Const F2 = CType(CType(Nothing, Object), Integer?) Public Const F3 = CType(CType(1, Integer), Integer?) Public Const F4 As Integer? = Nothing End Class Class ClazzNullable(Of T As Structure) Public Const F1 = CType(Nothing, T?) Public Const F2 = CType(CType(Nothing, Object), T?) Public Const F4 As T? = Nothing End Class Enum EI : AI : BI : End Enum Enum EB As Byte : AB : BB : End Enum Class ClazzWithEnums Public Const F1 = CType(CType(CType(CType(Nothing, EI), Object), Object), Object) Public Const F3 = CType(CType(CType(CType(Nothing, EB), Object), Object), Object) End Class Class StringConstants Const a As Object = "1" Const b As System.Object = "1" Const c = "1" End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30060: Conversion from 'Object' to 'SomeStructure' cannot occur in a constant expression. Public Const F = CType(CType(Nothing, SomeStructure), I) ~~~~~~~ BC30060: Conversion from 'Integer' to 'Object' cannot occur in a constant expression. Public Const F2 = CType(CType(Nothing, Integer), Object) ~~~~~~~~~~~~~~~~~~~~~~~ BC30060: Conversion from 'Object' to 'T' cannot occur in a constant expression. Public Const F = CType(CType(Nothing, T), I) ~~~~~~~ BC30060: Conversion from 'Object' to 'T' cannot occur in a constant expression. Public Const F = CType(CType(Nothing, T), I) ~~~~~~~ BC30060: Conversion from 'Object' to 'T' cannot occur in a constant expression. Public Const F2 = CType(CType(CType(CType(Nothing, T), Object), Object), Object) ' Dev11 does not generate error, but it should ~~~~~~~ BC30060: Conversion from 'Object' to 'T' cannot occur in a constant expression. Public Const F6 = CType(CType(CType(CType(Nothing, T), T), T), T) ' Dev11 does not generate error, but it should ~~~~~~~ BC30060: Conversion from 'Object' to 'T' cannot occur in a constant expression. Public Const F = CType(CType(CType(CType(Nothing, T), Object), Object), Object) ' Dev11 does not generate error, but it should ~~~~~~~ BC30060: Conversion from 'U' to 'V' cannot occur in a constant expression. Public Const F = CType(CType(CType(Nothing, U), V), I) ~~~~~~~~~~~~~~~~~ BC30060: Conversion from 'Object' to 'SomeStructure' cannot occur in a constant expression. Public Const F4 = CType(CType(CType(Nothing, SomeStructure), SomeStructure), SomeStructure) ~~~~~~~ BC30060: Conversion from 'Date' to 'Object' cannot occur in a constant expression. Public Const F2 = CType(#12:00:00 AM#, Object) ~~~~~~~~~~~~~ BC30060: Conversion from 'Date' to 'Object' cannot occur in a constant expression. Public Const F4 = CType(CType(Nothing, Date), Object) ~~~~~~~~~~~~~~~~~~~~ BC30060: Conversion from 'Decimal' to 'Object' cannot occur in a constant expression. Public Const F6 = CType(1.2345D, Object) ~~~~~~~ BC30060: Conversion from 'Decimal' to 'Object' cannot occur in a constant expression. Public Const F8 = CType(CType(Nothing, Decimal), Object) ~~~~~~~~~~~~~~~~~~~~~~~ BC30060: Conversion from 'Object' to 'Integer?' cannot occur in a constant expression. Public Const F1 = CType(Nothing, Integer?) ~~~~~~~ BC30060: Conversion from 'Object' to 'Integer?' cannot occur in a constant expression. Public Const F2 = CType(CType(Nothing, Object), Integer?) ~~~~~~~~~~~~~~~~~~~~~~ BC30060: Conversion from 'Integer' to 'Integer?' cannot occur in a constant expression. Public Const F3 = CType(CType(1, Integer), Integer?) ~~~~~~~~~~~~~~~~~ BC30424: Constants must be of an intrinsic or enumerated type, not a class, structure, type parameter, or array type. Public Const F4 As Integer? = Nothing ~~~~~~~~ BC30060: Conversion from 'Object' to 'T?' cannot occur in a constant expression. Public Const F1 = CType(Nothing, T?) ~~~~~~~ BC30060: Conversion from 'Object' to 'T?' cannot occur in a constant expression. Public Const F2 = CType(CType(Nothing, Object), T?) ~~~~~~~~~~~~~~~~~~~~~~ BC30424: Constants must be of an intrinsic or enumerated type, not a class, structure, type parameter, or array type. Public Const F4 As T? = Nothing ~~ BC30060: Conversion from 'EI' to 'Object' cannot occur in a constant expression. Public Const F1 = CType(CType(CType(CType(Nothing, EI), Object), Object), Object) ~~~~~~~~~~~~~~~~~~ BC30060: Conversion from 'EB' to 'Object' cannot occur in a constant expression. Public Const F3 = CType(CType(CType(CType(Nothing, EB), Object), Object), Object) ~~~~~~~~~~~~~~~~~~ BC30060: Conversion from 'String' to 'Object' cannot occur in a constant expression. Const b As System.Object = "1" ~~~ </expected>) End Sub Private Const s_ELEMENT_TYPE_U1 = 5 Private Const s_ELEMENT_TYPE_I4 = 8 Private Const s_ELEMENT_TYPE_VALUETYPE = 17 Private Const s_ELEMENT_TYPE_CLASS = 18 Private Const s_ELEMENT_TYPE_OBJECT = 28 Private Const s_FIELD_SIGNATURE_CALLING_CONVENTION = 6 Private ReadOnly _ZERO4 As Byte() = New Byte() {0, 0, 0, 0} Private ReadOnly _ONE4 As Byte() = New Byte() {1, 0, 0, 0} Private ReadOnly _ZERO1 As Byte() = New Byte() {0} Private ReadOnly _ONE1 As Byte() = New Byte() {1} <Fact> Public Sub VbConstantFields_NoError() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Interface I : End Interface Interface II : Inherits I : End Interface Interface III : Inherits II : End Interface Interface IV : Inherits III : End Interface Structure SomeStructure : Implements I : End Structure Class SomeClass : Implements I : End Class Class SomeClass2 : Inherits SomeClass : End Class Class Clazz9(Of T As IV) Public Const F9 = CType(CType(CType(CType(Nothing, IV), III), II), I) End Class Class Clazz3 Public Const F3 = CType(CType(CType(Nothing, SomeClass2), SomeClass), I) Public Const F33 = CType(CType(CType((((Nothing))), SomeClass2), SomeClass), I) End Class Class Clazz2(Of T As {Class, I}) Public Const F22 = CType(CType(Nothing, T), I) 'Dev11 - error, Roslyn - OK End Class Class Clazz7(Of T As {Class}) Public Const F7 = CType(CType(CType(CType(Nothing, T), Object), Object), Object) End Class Class Clazz8(Of T As {Class, IV}) Public Const F8 = CType(CType(CType(CType(CType(Nothing, T), IV), III), II), I) 'Dev11 - error, Roslyn - OK End Class </file> </compilation>, options:=TestOptions.ReleaseDll) CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) Dim bytes = compilation.EmitToArray() Using md = ModuleMetadata.CreateFromImage(bytes) Dim reader = md.MetadataReader Assert.Equal(6, reader.GetTableRowCount(TableIndex.Constant)) Assert.Equal(6, reader.FieldDefinitions.Count) For Each handle In reader.GetConstants() Dim constant = reader.GetConstant(handle) Dim field = reader.GetFieldDefinition(CType(constant.Parent, FieldDefinitionHandle)) Dim name = reader.GetString(field.Name) Dim actual = reader.GetBlobBytes(constant.Value) AssertEx.Equal(_ZERO4, actual) Dim constType = constant.TypeCode Select Case name Case "F9", "F3", "F33", "F22", "F7", "F8" Assert.Equal(s_ELEMENT_TYPE_CLASS, constType) Case Else Assert.True(False) End Select Next End Using End Sub <Fact> Public Sub VbConstantFields_NoError_DateDecimal() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class ClazzDateTimeDecimal Public Const F1 = #12:00:00 AM# Public Const F3 = CType(CType(#12:00:00 AM#, Date), Date) Public Const F5 = 1.2345D Public Const F7 = CType(CType(CType(1.2345D, Decimal), Decimal), Decimal) End Class </file> </compilation>, options:=TestOptions.ReleaseDll) CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) End Sub <Fact> Public Sub VbConstantFields_Enum() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Enum EI : AI : BI : End Enum Enum EB As Byte : AB : BB : End Enum Class Clazz Public Const F2 = CType(Nothing, EI) Public Const F4 = CType(Nothing, EB) Public Const F5 = EI.BI Public Const F6 = EB.BB Public Const F7 As EI = Nothing Public Const F8 As EB = Nothing End Class </file> </compilation>, options:=TestOptions.ReleaseDll) CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) Dim bytes = compilation.EmitToArray() Using md = ModuleMetadata.CreateFromImage(bytes) Dim reader = md.MetadataReader Assert.Equal(10, reader.GetTableRowCount(TableIndex.Constant)) Assert.Equal(10 + 2, reader.FieldDefinitions.Count) For Each handle In reader.GetConstants() Dim constant = reader.GetConstant(handle) Dim field = reader.GetFieldDefinition(CType(constant.Parent, FieldDefinitionHandle)) Dim name = reader.GetString(field.Name) Select Case name Case "F1" ' Constant: int32(0) Assert.Equal(s_ELEMENT_TYPE_I4, constant.TypeCode) AssertEx.Equal(_ZERO4, reader.GetBlobBytes(constant.Value)) ' Field type: System.Object AssertEx.Equal(New Byte() {s_FIELD_SIGNATURE_CALLING_CONVENTION, s_ELEMENT_TYPE_OBJECT}, reader.GetBlobBytes(field.Signature)) Case "F2" ' Constant: int32(0) Assert.Equal(s_ELEMENT_TYPE_I4, constant.TypeCode) AssertEx.Equal(_ZERO4, reader.GetBlobBytes(constant.Value)) ' Field type: int32 AssertEx.Equal(New Byte() {s_FIELD_SIGNATURE_CALLING_CONVENTION, s_ELEMENT_TYPE_I4}, reader.GetBlobBytes(field.Signature)) Case "F3" ' Constant: uint8(0) Assert.Equal(s_ELEMENT_TYPE_U1, constant.TypeCode) AssertEx.Equal(_ZERO1, reader.GetBlobBytes(constant.Value)) ' Field type: System.Object AssertEx.Equal(New Byte() {s_FIELD_SIGNATURE_CALLING_CONVENTION, s_ELEMENT_TYPE_OBJECT}, reader.GetBlobBytes(field.Signature)) Case "F4" ' Constant: uint8(0) Assert.Equal(s_ELEMENT_TYPE_U1, constant.TypeCode) AssertEx.Equal(_ZERO1, reader.GetBlobBytes(constant.Value)) ' Field type: uint8 AssertEx.Equal(New Byte() {s_FIELD_SIGNATURE_CALLING_CONVENTION, s_ELEMENT_TYPE_U1}, reader.GetBlobBytes(field.Signature)) Case "F5" ' Constant: int32(0) Assert.Equal(s_ELEMENT_TYPE_I4, constant.TypeCode) AssertEx.Equal(_ONE4, reader.GetBlobBytes(constant.Value)) ' Field type: int32 AssertEx.Equal(New Byte() {s_FIELD_SIGNATURE_CALLING_CONVENTION, s_ELEMENT_TYPE_I4}, reader.GetBlobBytes(field.Signature)) Case "F6" ' Constant: uint8(0) Assert.Equal(s_ELEMENT_TYPE_U1, constant.TypeCode) AssertEx.Equal(_ONE1, reader.GetBlobBytes(constant.Value)) ' Field type: uint8 AssertEx.Equal(New Byte() {s_FIELD_SIGNATURE_CALLING_CONVENTION, s_ELEMENT_TYPE_U1}, reader.GetBlobBytes(field.Signature)) Case "F7" ' Constant: int32(0) Assert.Equal(s_ELEMENT_TYPE_I4, constant.TypeCode) AssertEx.Equal(_ZERO4, reader.GetBlobBytes(constant.Value)) ' Field type: EI (valuetype) AssertAnyValueType(reader.GetBlobBytes(field.Signature)) Case "F8" ' Constant: uint8(0) Assert.Equal(s_ELEMENT_TYPE_U1, constant.TypeCode) AssertEx.Equal(_ZERO1, reader.GetBlobBytes(constant.Value)) ' Field type: EB (valuetype) AssertAnyValueType(reader.GetBlobBytes(field.Signature)) Case "AI" ' Constant: int32(0) Assert.Equal(s_ELEMENT_TYPE_I4, constant.TypeCode) AssertEx.Equal(_ZERO4, reader.GetBlobBytes(constant.Value)) ' Field type: EI (valuetype) AssertAnyValueType(reader.GetBlobBytes(field.Signature)) Case "BI" ' Constant: int32(0) Assert.Equal(s_ELEMENT_TYPE_I4, constant.TypeCode) AssertEx.Equal(_ONE4, reader.GetBlobBytes(constant.Value)) ' Field type: EI (valuetype) AssertAnyValueType(reader.GetBlobBytes(field.Signature)) Case "AB" ' Constant: uint8(0) Assert.Equal(s_ELEMENT_TYPE_U1, constant.TypeCode) AssertEx.Equal(_ZERO1, reader.GetBlobBytes(constant.Value)) ' Field type: EB (valuetype) AssertAnyValueType(reader.GetBlobBytes(field.Signature)) Case "BB" ' Constant: uint8(0) Assert.Equal(s_ELEMENT_TYPE_U1, constant.TypeCode) AssertEx.Equal(_ONE1, reader.GetBlobBytes(constant.Value)) ' Field type: EB (valuetype) AssertAnyValueType(reader.GetBlobBytes(field.Signature)) Case Else Assert.True(False) End Select Next End Using End Sub Private Sub AssertAnyValueType(actual As Byte()) Assert.Equal(3, actual.Length) Assert.Equal(s_FIELD_SIGNATURE_CALLING_CONVENTION, actual(0)) Assert.Equal(s_ELEMENT_TYPE_VALUETYPE, actual(1)) End Sub <Fact> Public Sub VbParameterDefaults_Error() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Interface I : End Interface Interface II : Inherits I : End Interface Interface III : Inherits II : End Interface Interface IV : Inherits III : End Interface Structure SomeStructure : Implements I : End Structure Class SomeClass : Implements I : End Class Class SomeClass2 : Inherits SomeClass : End Class Interface Clazz Sub s1(Optional F As Object = CType(CType(Nothing, SomeStructure), I)) Sub s2(Optional F As I = CType(CType(Nothing, SomeStructure), I)) Sub s3(Optional F As Object = CType(CType(CType(Nothing, SomeStructure), SomeStructure), SomeStructure)) End Interface Interface Clazz(Of T As I) Sub s1(Optional F As Object = CType(CType(Nothing, T), I)) Sub s2(Optional F As I = CType(CType(Nothing, T), I)) End Interface Interface Clazz3(Of T As {Structure, I}) Sub s1(Optional F As Object = CType(CType(Nothing, T), I)) Sub s2(Optional F As I = CType(CType(Nothing, T), I)) End Interface Interface Clazz6(Of T As Structure) Sub s1(Optional F As Object = CType(CType(CType(CType(Nothing, T), Object), Object), Object)) ' Dev11 - OK, Roslyn - ERROR Sub s2(Optional F As Object = CType(CType(CType(CType(Nothing, T), T), T), T)) ' Dev11 - OK, Roslyn - ERROR End Interface Interface Clazz7(Of T) Sub s1(Optional F As Object = CType(CType(CType(CType(Nothing, T), Object), Object), Object)) ' Dev11 - OK, Roslyn - ERROR Sub s2(Optional F As Object = CType(CType(CType(CType(Nothing, T), T), T), T)) ' Dev11 - OK, Roslyn - ERROR End Interface Interface Clazz9(Of U As {Class, I}, V As U) Sub s1(Optional F As Object = CType(CType(CType(Nothing, U), V), I)) Sub s2(Optional F As I = CType(CType(CType(Nothing, U), V), I)) Sub s3(Optional F As Object = CType(CType(CType(Nothing, V), U), I)) Sub s4(Optional F As I = CType(CType(CType(Nothing, V), U), I)) End Interface Interface ClazzMisc Sub s5(Optional F As Object = CType(Nothing, Integer?)) Sub s8(Optional F As Object = CType(CType(Nothing, Object), Integer?)) Sub s10(Optional F As Object = CType(CType(1, Integer), Integer?)) End Interface Interface ClazzMisc(Of T As Structure) Sub s5(Optional F As Object = CType(Nothing, T?)) Sub s8(Optional F As Object = CType(CType(Nothing, Object), T?)) End Interface Enum EI : AI : BI : End Enum Interface ClazzWithEnums Sub s7(Optional p7 As Object = CType(EI.BI, EI?)) End Interface </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30060: Conversion from 'SomeStructure' to 'I' cannot occur in a constant expression. Sub s1(Optional F As Object = CType(CType(Nothing, SomeStructure), I)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30060: Conversion from 'SomeStructure' to 'I' cannot occur in a constant expression. Sub s2(Optional F As I = CType(CType(Nothing, SomeStructure), I)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30060: Conversion from 'SomeStructure' to 'Object' cannot occur in a constant expression. Sub s3(Optional F As Object = CType(CType(CType(Nothing, SomeStructure), SomeStructure), SomeStructure)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30060: Conversion from 'T' to 'I' cannot occur in a constant expression. Sub s1(Optional F As Object = CType(CType(Nothing, T), I)) ~~~~~~~~~~~~~~~~~ BC30060: Conversion from 'T' to 'I' cannot occur in a constant expression. Sub s2(Optional F As I = CType(CType(Nothing, T), I)) ~~~~~~~~~~~~~~~~~ BC30060: Conversion from 'T' to 'I' cannot occur in a constant expression. Sub s1(Optional F As Object = CType(CType(Nothing, T), I)) ~~~~~~~~~~~~~~~~~ BC30060: Conversion from 'T' to 'I' cannot occur in a constant expression. Sub s2(Optional F As I = CType(CType(Nothing, T), I)) ~~~~~~~~~~~~~~~~~ BC30060: Conversion from 'T' to 'Object' cannot occur in a constant expression. Sub s1(Optional F As Object = CType(CType(CType(CType(Nothing, T), Object), Object), Object)) ' Dev11 - OK, Roslyn - ERROR ~~~~~~~~~~~~~~~~~ BC30060: Conversion from 'T' to 'Object' cannot occur in a constant expression. Sub s2(Optional F As Object = CType(CType(CType(CType(Nothing, T), T), T), T)) ' Dev11 - OK, Roslyn - ERROR ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30060: Conversion from 'T' to 'Object' cannot occur in a constant expression. Sub s1(Optional F As Object = CType(CType(CType(CType(Nothing, T), Object), Object), Object)) ' Dev11 - OK, Roslyn - ERROR ~~~~~~~~~~~~~~~~~ BC30060: Conversion from 'T' to 'Object' cannot occur in a constant expression. Sub s2(Optional F As Object = CType(CType(CType(CType(Nothing, T), T), T), T)) ' Dev11 - OK, Roslyn - ERROR ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30060: Conversion from 'V' to 'I' cannot occur in a constant expression. Sub s1(Optional F As Object = CType(CType(CType(Nothing, U), V), I)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30060: Conversion from 'V' to 'I' cannot occur in a constant expression. Sub s2(Optional F As I = CType(CType(CType(Nothing, U), V), I)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30060: Conversion from 'V' to 'U' cannot occur in a constant expression. Sub s3(Optional F As Object = CType(CType(CType(Nothing, V), U), I)) ~~~~~~~~~~~~~~~~~ BC30060: Conversion from 'V' to 'U' cannot occur in a constant expression. Sub s4(Optional F As I = CType(CType(CType(Nothing, V), U), I)) ~~~~~~~~~~~~~~~~~ BC30060: Conversion from 'Integer?' to 'Object' cannot occur in a constant expression. Sub s5(Optional F As Object = CType(Nothing, Integer?)) ~~~~~~~~~~~~~~~~~~~~~~~~ BC30060: Conversion from 'Integer?' to 'Object' cannot occur in a constant expression. Sub s8(Optional F As Object = CType(CType(Nothing, Object), Integer?)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30060: Conversion from 'Integer?' to 'Object' cannot occur in a constant expression. Sub s10(Optional F As Object = CType(CType(1, Integer), Integer?)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30060: Conversion from 'T?' to 'Object' cannot occur in a constant expression. Sub s5(Optional F As Object = CType(Nothing, T?)) ~~~~~~~~~~~~~~~~~~ BC30060: Conversion from 'T?' to 'Object' cannot occur in a constant expression. Sub s8(Optional F As Object = CType(CType(Nothing, Object), T?)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30060: Conversion from 'EI?' to 'Object' cannot occur in a constant expression. Sub s7(Optional p7 As Object = CType(EI.BI, EI?)) ~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact> Public Sub VbParameterDefaults_NoError() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Interface I : End Interface Interface II : Inherits I : End Interface Interface III : Inherits II : End Interface Interface IV : Inherits III : End Interface Structure SomeStructure : Implements I : End Structure Class SomeClass : Implements I : End Class Class SomeClass2 : Inherits SomeClass : End Class Interface Clazz Sub s1(Optional F1 As SomeStructure = CType(CType(CType(Nothing, SomeStructure), SomeStructure), SomeStructure)) ' Dev11 - ERROR, Roslyn - OK Sub s2(Optional F2 As Object = CType(CType(Nothing, Integer), Object)) ' Dev11 - ERROR, Roslyn - OK Sub s3(Optional F3 As Object = CType(CType(CType(Nothing, SomeClass2), SomeClass), I)) Sub s4(Optional F4 As I = CType(CType(CType(Nothing, SomeClass2), SomeClass), I)) Sub s5(Optional F5 As Object = CType(CType(CType((((Nothing))), SomeClass2), SomeClass), I)) End Interface Interface Clazz2(Of T As {Class, I}) Sub s1(Optional F6 As Object = CType(CType(Nothing, T), I)) ' Dev11 - ERROR, Roslyn - OK Sub s2(Optional F7 As I = CType(CType(Nothing, T), I)) ' Dev11 - ERROR, Roslyn - OK Sub s3(Optional F8 As Object = CType(CType(CType(CType(Nothing, T), Object), Object), Object)) End Interface Interface Clazz2x(Of T As {Class, Iv}) Sub s1(Optional F9 As Object = CType(CType(CType(CType(CType(Nothing, T), IV), III), II), I)) ' Dev11 - ERROR, Roslyn - OK Sub s2(Optional F10 As I = CType(CType(CType(CType(CType(Nothing, T), IV), III), II), I)) ' Dev11 - ERROR, Roslyn - OK End Interface Interface Clazz6(Of T As Structure) Sub s3(Optional F11 As T = CType(CType(CType(CType(Nothing, T), T), T), T)) End Interface Interface Clazz7(Of T) Sub s3(Optional F12 As T = CType(CType(CType(CType(Nothing, T), T), T), T)) End Interface Interface Clazz9(Of T As IV) Sub s1(Optional F13 As Object = CType(CType(CType(CType(Nothing, IV), III), II), I)) Sub s2(Optional F14 As I = CType(CType(CType(CType(Nothing, IV), III), II), I)) End Interface Interface ClazzMisc Sub s1(Optional F15 As Object = CType(#12:00:00 AM#, Object)) ' Dev11 - ERROR, Roslyn - OK Sub s2(Optional F16 As Object = CType(CType(Nothing, Date), Object)) ' Dev11 - ERROR, Roslyn - OK Sub s3(Optional F17 As Object = CType(1.2345D, Object)) ' Dev11 - ERROR, Roslyn - OK Sub s4(Optional F18 As Object = CType(CType(Nothing, Decimal), Object)) ' Dev11 - ERROR, Roslyn - OK Sub s6(Optional F19 As Integer? = CType(Nothing, Integer?)) ' Dev11 - ERROR, Roslyn - OK Sub s7(Optional F20 As Integer? = Nothing) Sub s9(Optional F21 As Integer? = CType(CType(Nothing, Object), Integer?)) ' Dev11 - ERROR, Roslyn - OK Sub s11(Optional F22 As Integer? = CType(CType(1, Integer), Integer?)) ' Dev11 - ERROR, Roslyn - OK Sub s12(Optional F23 As Integer? = 1) Sub s13(Optional F24 As Integer? = CType(1, Integer?)) ' Dev11 - ERROR, Roslyn - OK Sub s14(Optional F25 As Integer? = CType(1, Integer)) End Interface Interface ClazzMisc(Of T As Structure) Sub s6(Optional F26 As T? = CType(Nothing, T?)) ' Dev11 - ERROR, Roslyn - OK Sub s7(Optional F27 As T? = Nothing) Sub s9(Optional F28 As T? = CType(CType(Nothing, Object), T?)) ' Dev11 - ERROR, Roslyn - OK End Interface Enum EI : AI : BI : End Enum Interface ClazzWithEnums Sub s1(Optional F30 As Object = CType(CType(CType(CType(Nothing, EI), Object), Object), Object)) 'Dev11 - ERROR, Roslyn - OK, Int constant!!! Sub s2(Optional F31 As Object = CType(Nothing, EI)) ' Int constant!!! Sub s3(Optional F32 As EI = CType(Nothing, EI)) Sub s4(Optional F33 As EI? = CType(Nothing, EI)) Sub s5(Optional F34 As EI? = CType(Nothing, EI?)) 'Dev11 - ERROR, Roslyn - OK Sub s6(Optional F35 As Object = EI.BI) 'Int constant!!! Sub s8(Optional F36 As Object = CType(EI.BI, Object)) 'Int constant!!! Sub s9(Optional F37 As EI? = CType(EI.BI, EI?)) 'Dev11 - ERROR, Roslyn - OK Sub s10(Optional F38 As EI? = EI.BI) Sub s11(Optional F39 As EI? = Nothing) Sub s12(Optional F40 As EI? = CType(CType(CType(Nothing, Integer), Byte), EI)) Sub s13(Optional F41 As EI? = CType(CType(CType(EI.BI, Integer), Byte), EI)) End Interface </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) Dim bytes = compilation.EmitToArray() Using md = ModuleMetadata.CreateFromImage(bytes) Dim reader = md.MetadataReader Const FIELD_COUNT = 40 Const ATTR_CONST_COUNT = 4 Const ENUM_CONST_COUNT = 2 Assert.Equal(FIELD_COUNT - ATTR_CONST_COUNT + ENUM_CONST_COUNT, reader.GetTableRowCount(TableIndex.Constant)) Assert.Equal(FIELD_COUNT, reader.GetTableRowCount(TableIndex.Param)) For Each handle In reader.GetConstants() Dim constant = reader.GetConstant(handle) If constant.Parent.Kind = HandleKind.Parameter Then Dim paramRow = reader.GetParameter(CType(constant.Parent, ParameterHandle)) Dim name = reader.GetString(paramRow.Name) Select Case name Case "F1", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12", "F13", "F14", "F19", "F20", "F21", "F26", "F27", "F28", "F34", "F39" ' Constant: nullref Assert.Equal(s_ELEMENT_TYPE_CLASS, constant.TypeCode) AssertEx.Equal(_ZERO4, reader.GetBlobBytes(constant.Value)) Case "F2", "F30", "F31", "F32", "F33", "F40" ' Constant: int32(0) Assert.Equal(s_ELEMENT_TYPE_I4, constant.TypeCode) AssertEx.Equal(_ZERO4, reader.GetBlobBytes(constant.Value)) Case "F22", "F23", "F24", "F25", "F35", "F36", "F37", "F38", "F41" ' Constant: int32(1) Assert.Equal(s_ELEMENT_TYPE_I4, constant.TypeCode) AssertEx.Equal(_ONE4, reader.GetBlobBytes(constant.Value)) Case Else Assert.True(False, "Unknown field: " + name) End Select End If Next For Each paramDef In reader.GetParameters() Dim name = reader.GetString(reader.GetParameter(paramDef).Name) ' Just make sure we have attributes on F15, F16, F17, F18 Select Case name Case "F15", "F16", "F17", "F18" Assert.True(HasAnyCustomAttribute(reader, paramDef)) End Select Next End Using End Sub Private Function HasAnyCustomAttribute(reader As MetadataReader, parent As EntityHandle) As Boolean For Each ca In reader.CustomAttributes If reader.GetCustomAttribute(ca).Parent = parent Then Return True End If Next Return False End Function <Fact()> Public Sub ConstantOfWrongType() Dim ilSource = <![CDATA[ .class public auto ansi Clazz extends [mscorlib]System.Object { .field public static literal object a = int32(0x00000001) .field public static literal object b = "abc" .method public specialname rtspecialname instance void .ctor() cil managed { .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) // Code size 9 (0x9) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: nop IL_0007: nop IL_0008: ret } // end of method Clazz::.ctor } ]]> Dim vbSource = <compilation> <file name="a.vb"> Imports System Module C Sub S() Console.WriteLine(Clazz.a.ToString()) Console.WriteLine(Clazz.b.ToString()) End Sub End Module </file> </compilation> Dim reference As MetadataReference = Nothing Using tempAssembly = IlasmUtilities.CreateTempAssembly(ilSource.Value) reference = MetadataReference.CreateFromImage(ReadFromFile(tempAssembly.Path)) End Using Dim compilation = CreateEmptyCompilationWithReferences(vbSource, {MscorlibRef, MsvbRef, reference}, TestOptions.ReleaseDll) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> BC30799: Field 'Clazz.a' has an invalid constant value. Console.WriteLine(Clazz.a.ToString()) ~~~~~~~ BC30799: Field 'Clazz.b' has an invalid constant value. Console.WriteLine(Clazz.b.ToString()) ~~~~~~~ </errors>) End Sub <Fact, WorkItem(1028, "https://github.com/dotnet/roslyn/issues/1028")> Public Sub WriteOfReadonlySharedMemberOfAnotherInstantiation01() Dim source = <compilation> <file name="a.vb"> Class Goo(Of T) Shared Sub New() Goo(Of Integer).X = 12 Goo(Of Integer).Y = 12 Goo(Of T).X = 12 Goo(Of T).Y = 12 End Sub Public Shared ReadOnly X As Integer Public Shared ReadOnly Property Y As Integer = 0 End Class </file> </compilation> Dim standardCompilation = CompilationUtils.CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseDll) Dim strictCompilation = CompilationUtils.CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseDll, parseOptions:=TestOptions.Regular.WithStrictFeature()) CompilationUtils.AssertTheseDiagnostics(standardCompilation, <expected> BC30526: Property 'Y' is 'ReadOnly'. Goo(Of Integer).Y = 12 ~~~~~~~~~~~~~~~~~~~~~~ </expected>) CompilationUtils.AssertTheseDiagnostics(strictCompilation, <expected> BC30064: 'ReadOnly' variable cannot be the target of an assignment. Goo(Of Integer).X = 12 ~~~~~~~~~~~~~~~~~ BC30526: Property 'Y' is 'ReadOnly'. Goo(Of Integer).Y = 12 ~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact, WorkItem(1028, "https://github.com/dotnet/roslyn/issues/1028")> Public Sub WriteOfReadonlySharedMemberOfAnotherInstantiation02() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module M1 Sub Main() Console.WriteLine(Goo(Of Long).X) Console.WriteLine(Goo(Of Integer).X) Console.WriteLine(Goo(Of String).X) Console.WriteLine(Goo(Of Integer).X) End Sub End Module Public Class Goo(Of T) Shared Sub New() Console.WriteLine("Initializing for {0}", GetType(T)) Goo(Of Integer).X = GetType(T).Name End Sub Public Shared ReadOnly X As String End Class </file> </compilation>, verify:=Verification.Fails, expectedOutput:=<![CDATA[Initializing for System.Int64 Initializing for System.Int32 Int64 Initializing for System.String String ]]>) End Sub #Region "Helpers" Private Shared Function CompileAndExtractTypeSymbol(sources As Xml.Linq.XElement, Optional typeName As String = "C") As SourceNamedTypeSymbol Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(sources) Dim typeSymbol = DirectCast(compilation.SourceModule.GlobalNamespace.GetTypeMembers(typeName).Single(), SourceNamedTypeSymbol) Return typeSymbol End Function Private Shared Function GetMember(sources As Xml.Linq.XElement, fieldName As String, Optional typeName As String = "C") As Symbol Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(sources) Dim symbol = DirectCast(compilation.SourceModule.GlobalNamespace.GetTypeMembers(typeName).Single.GetMembers(fieldName).Single(), Symbol) Return symbol End Function Private Shared Function HasSynthesizedStaticConstructor(typeSymbol As NamedTypeSymbol) As Boolean For Each member In typeSymbol.GetMembers(WellKnownMemberNames.StaticConstructorName) If member.IsImplicitlyDeclared Then Return True End If Next Return False End Function Private Shared Function IsBeforeFieldInit(typeSymbol As NamedTypeSymbol) As Boolean Return (DirectCast(typeSymbol.GetCciAdapter(), Microsoft.Cci.ITypeDefinition)).IsBeforeFieldInit End Function Private Shared Function IsStatic(symbol As Symbol) As Boolean Return (DirectCast(symbol.GetCciAdapter(), Microsoft.Cci.IFieldDefinition)).IsStatic End Function Private Shared Sub CompileAndCheckInitializers(sources As Xml.Linq.XElement, expectedInstanceInitializers As IEnumerable(Of ExpectedInitializer), expectedStaticInitializers As IEnumerable(Of ExpectedInitializer)) ' Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(sources) Dim typeSymbol = DirectCast(compilation.SourceModule.GlobalNamespace.GetTypeMembers("C").Single(), SourceNamedTypeSymbol) Dim syntaxTree = compilation.SyntaxTrees.First() Dim boundInstanceInitializers = BindInitializersWithoutDiagnostics(typeSymbol, typeSymbol.InstanceInitializers) CheckBoundInitializers(expectedInstanceInitializers, syntaxTree, boundInstanceInitializers, isStatic:=False) Dim boundStaticInitializers = BindInitializersWithoutDiagnostics(typeSymbol, typeSymbol.StaticInitializers) CheckBoundInitializers(expectedStaticInitializers, syntaxTree, boundStaticInitializers, isStatic:=True) End Sub Private Shared Sub CheckBoundInitializers(expectedInitializers As IEnumerable(Of ExpectedInitializer), syntaxTree As SyntaxTree, boundInitializers As ImmutableArray(Of BoundInitializer), isStatic As Boolean) If expectedInitializers Is Nothing Then Assert.[True](boundInitializers.IsEmpty) Else Assert.[True](Not boundInitializers.IsDefault) Dim numInitializers As Integer = expectedInitializers.Count() Assert.Equal(numInitializers, boundInitializers.Length) Dim i As Integer = 0 For Each expectedInitializer In expectedInitializers Dim boundInit = boundInitializers(i) i += 1 Assert.[True](boundInit.Kind = BoundKind.FieldInitializer OrElse boundInit.Kind = BoundKind.PropertyInitializer) Dim boundFieldInit = DirectCast(boundInit, BoundFieldOrPropertyInitializer) Dim initValueSyntax = boundFieldInit.InitialValue.Syntax If boundInit.Syntax.Kind <> SyntaxKind.AsNewClause Then Assert.Same(initValueSyntax.Parent, boundInit.Syntax) Assert.Equal(expectedInitializer.InitialValue, initValueSyntax.ToString()) End If Dim initValueLineNumber = syntaxTree.GetLineSpan(initValueSyntax.Span).StartLinePosition.Line Assert.Equal(expectedInitializer.LineNumber, initValueLineNumber) Dim fieldOrPropertySymbol As Symbol If boundInit.Kind = BoundKind.FieldInitializer Then fieldOrPropertySymbol = DirectCast(boundFieldInit, BoundFieldInitializer).InitializedFields.First Else fieldOrPropertySymbol = DirectCast(boundFieldInit, BoundPropertyInitializer).InitializedProperties.First End If Assert.Equal(expectedInitializer.FieldName, fieldOrPropertySymbol.Name) Dim boundReceiver As BoundExpression Select Case boundFieldInit.MemberAccessExpressionOpt.Kind Case BoundKind.PropertyAccess boundReceiver = DirectCast(boundFieldInit.MemberAccessExpressionOpt, BoundPropertyAccess).ReceiverOpt Case BoundKind.FieldAccess boundReceiver = DirectCast(boundFieldInit.MemberAccessExpressionOpt, BoundFieldAccess).ReceiverOpt Case Else Throw TestExceptionUtilities.UnexpectedValue(boundFieldInit.MemberAccessExpressionOpt.Kind) End Select Assert.Equal(BoundKind.FieldAccess, boundFieldInit.MemberAccessExpressionOpt.Kind) If isStatic Then Assert.Null(boundReceiver) Else Assert.Equal(BoundKind.MeReference, boundReceiver.Kind) End If Next End If End Sub Private Shared Function BindInitializersWithoutDiagnostics(typeSymbol As SourceNamedTypeSymbol, initializers As ImmutableArray(Of ImmutableArray(Of FieldOrPropertyInitializer))) As ImmutableArray(Of BoundInitializer) Dim diagnostics As DiagnosticBag = DiagnosticBag.GetInstance() Dim processedFieldInitializers = Binder.BindFieldAndPropertyInitializers(typeSymbol, initializers, Nothing, New BindingDiagnosticBag(diagnostics)) Dim sealedDiagnostics = diagnostics.ToReadOnlyAndFree() For Each d In sealedDiagnostics Console.WriteLine(d) Next Assert.False(sealedDiagnostics.Any()) Return processedFieldInitializers End Function Public Class ExpectedInitializer Public Property FieldName As String Public Property InitialValue As String Public Property LineNumber As Integer Public Sub New(fieldName As String, initialValue As String, lineNumber As Integer) Me.FieldName = fieldName Me.InitialValue = initialValue Me.LineNumber = lineNumber End Sub End Class #End Region End Class End Namespace
-1
dotnet/roslyn
56,011
React to string comparison changing on .NET Core
The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
jaredpar
"2021-08-30T17:18:52Z"
"2021-08-30T20:20:04Z"
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
4d99cda6e446e77dbb302e26388c1093bd3ef569
React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
./src/Compilers/VisualBasic/Portable/Symbols/Source/SourceParameterSymbolBase.vb
' 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.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ''' <summary> ''' Base class for all parameters that are emitted. ''' </summary> Friend MustInherit Class SourceParameterSymbolBase Inherits ParameterSymbol Private ReadOnly _containingSymbol As Symbol Private ReadOnly _ordinal As UShort Friend Sub New(containingSymbol As Symbol, ordinal As Integer) _containingSymbol = containingSymbol _ordinal = CUShort(ordinal) End Sub Public NotOverridable Overrides ReadOnly Property Ordinal As Integer Get Return _ordinal End Get End Property Public NotOverridable Overrides ReadOnly Property ContainingSymbol As Symbol Get Return _containingSymbol End Get End Property Friend MustOverride ReadOnly Property HasParamArrayAttribute As Boolean Friend MustOverride ReadOnly Property HasDefaultValueAttribute As Boolean Friend NotOverridable Overrides Sub AddSynthesizedAttributes(compilationState as ModuleCompilationState, ByRef attributes As ArrayBuilder(Of SynthesizedAttributeData)) MyBase.AddSynthesizedAttributes(compilationState, attributes) ' Create the ParamArrayAttribute If IsParamArray AndAlso Not HasParamArrayAttribute Then Dim compilation = Me.DeclaringCompilation AddSynthesizedAttribute(attributes, compilation.TrySynthesizeAttribute( WellKnownMember.System_ParamArrayAttribute__ctor)) End If ' Create the default attribute If HasExplicitDefaultValue AndAlso Not HasDefaultValueAttribute Then ' Synthesize DateTimeConstantAttribute or DecimalConstantAttribute when the default ' value is either DateTime or Decimal and there is not an explicit custom attribute. Dim compilation = Me.DeclaringCompilation Dim defaultValue = ExplicitDefaultConstantValue Select Case defaultValue.SpecialType Case SpecialType.System_DateTime AddSynthesizedAttribute(attributes, compilation.TrySynthesizeAttribute( WellKnownMember.System_Runtime_CompilerServices_DateTimeConstantAttribute__ctor, ImmutableArray.Create(New TypedConstant(compilation.GetSpecialType(SpecialType.System_Int64), TypedConstantKind.Primitive, defaultValue.DateTimeValue.Ticks)))) Case SpecialType.System_Decimal AddSynthesizedAttribute(attributes, compilation.SynthesizeDecimalConstantAttribute(defaultValue.DecimalValue)) End Select End If If Me.Type.ContainsTupleNames() Then AddSynthesizedAttribute(attributes, DeclaringCompilation.SynthesizeTupleNamesAttribute(Type)) End If End Sub Friend MustOverride Function WithTypeAndCustomModifiers(type As TypeSymbol, customModifiers As ImmutableArray(Of CustomModifier), refCustomModifiers As ImmutableArray(Of CustomModifier)) As ParameterSymbol End Class End Namespace
' 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.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ''' <summary> ''' Base class for all parameters that are emitted. ''' </summary> Friend MustInherit Class SourceParameterSymbolBase Inherits ParameterSymbol Private ReadOnly _containingSymbol As Symbol Private ReadOnly _ordinal As UShort Friend Sub New(containingSymbol As Symbol, ordinal As Integer) _containingSymbol = containingSymbol _ordinal = CUShort(ordinal) End Sub Public NotOverridable Overrides ReadOnly Property Ordinal As Integer Get Return _ordinal End Get End Property Public NotOverridable Overrides ReadOnly Property ContainingSymbol As Symbol Get Return _containingSymbol End Get End Property Friend MustOverride ReadOnly Property HasParamArrayAttribute As Boolean Friend MustOverride ReadOnly Property HasDefaultValueAttribute As Boolean Friend NotOverridable Overrides Sub AddSynthesizedAttributes(compilationState as ModuleCompilationState, ByRef attributes As ArrayBuilder(Of SynthesizedAttributeData)) MyBase.AddSynthesizedAttributes(compilationState, attributes) ' Create the ParamArrayAttribute If IsParamArray AndAlso Not HasParamArrayAttribute Then Dim compilation = Me.DeclaringCompilation AddSynthesizedAttribute(attributes, compilation.TrySynthesizeAttribute( WellKnownMember.System_ParamArrayAttribute__ctor)) End If ' Create the default attribute If HasExplicitDefaultValue AndAlso Not HasDefaultValueAttribute Then ' Synthesize DateTimeConstantAttribute or DecimalConstantAttribute when the default ' value is either DateTime or Decimal and there is not an explicit custom attribute. Dim compilation = Me.DeclaringCompilation Dim defaultValue = ExplicitDefaultConstantValue Select Case defaultValue.SpecialType Case SpecialType.System_DateTime AddSynthesizedAttribute(attributes, compilation.TrySynthesizeAttribute( WellKnownMember.System_Runtime_CompilerServices_DateTimeConstantAttribute__ctor, ImmutableArray.Create(New TypedConstant(compilation.GetSpecialType(SpecialType.System_Int64), TypedConstantKind.Primitive, defaultValue.DateTimeValue.Ticks)))) Case SpecialType.System_Decimal AddSynthesizedAttribute(attributes, compilation.SynthesizeDecimalConstantAttribute(defaultValue.DecimalValue)) End Select End If If Me.Type.ContainsTupleNames() Then AddSynthesizedAttribute(attributes, DeclaringCompilation.SynthesizeTupleNamesAttribute(Type)) End If End Sub Friend MustOverride Function WithTypeAndCustomModifiers(type As TypeSymbol, customModifiers As ImmutableArray(Of CustomModifier), refCustomModifiers As ImmutableArray(Of CustomModifier)) As ParameterSymbol End Class End Namespace
-1
dotnet/roslyn
56,011
React to string comparison changing on .NET Core
The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
jaredpar
"2021-08-30T17:18:52Z"
"2021-08-30T20:20:04Z"
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
4d99cda6e446e77dbb302e26388c1093bd3ef569
React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
./src/EditorFeatures/Test2/Rename/CSharp/LocalConflictTests.vb
' 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.Remote.Testing Imports Microsoft.CodeAnalysis.Rename.ConflictEngine Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Rename.CSharp <[UseExportProvider]> Public Class LocalConflictTests Private ReadOnly _outputHelper As Abstractions.ITestOutputHelper Public Sub New(outputHelper As Abstractions.ITestOutputHelper) _outputHelper = outputHelper End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(539939, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539939")> Public Sub ConflictingLocalWithLocal(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Program { static void Main(string[] args) { int {|stmt1:$$x|} = 1; int {|Conflict:y|} = 2; } } </Document> </Project> </Workspace>, host:=host, renameTo:="y") result.AssertLabeledSpansAre("stmt1", "y", type:=RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(539939, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539939")> Public Sub ConflictingLocalWithParameter(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Program { static void Main(string[] {|Conflict:args|}) { int {|stmt1:$$x|} = 1; } } </Document> </Project> </Workspace>, host:=host, renameTo:="args") result.AssertLabeledSpansAre("stmt1", "args", RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictingLocalWithForEachRangeVariable(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Program { static void Main(string[] args) { int {|stmt1:$$x|} = 1; foreach (var {|Conflict:y|} in args) { } } } </Document> </Project> </Workspace>, host:=host, renameTo:="y") result.AssertLabeledSpansAre("stmt1", "y", RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictingLocalWithForLoopVariable(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Program { static void Main(string[] args) { int {|stmt1:$$x|} = 1; for (int {|Conflict:y|} = 0; ; } { } } } </Document> </Project> </Workspace>, host:=host, renameTo:="y") result.AssertLabeledSpansAre("stmt1", "y", RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictingLocalWithUsingBlockVariable(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Program : IDisposable { static void Main(string[] args) { int {|stmt1:$$x|} = 1; using (var {|Conflict:y|} = new Program()) { } } } </Document> </Project> </Workspace>, host:=host, renameTo:="y") result.AssertLabeledSpansAre("stmt1", "y", RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictingLocalWithSimpleLambdaParameter(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ using System; class Program { static void Main(string[] args) { int {|stmt1:$$x|} = 1; Func<int> lambda = {|Conflict:y|} => 42; } } ]]></Document> </Project> </Workspace>, host:=host, renameTo:="y") result.AssertLabeledSpansAre("stmt1", "y", RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictingLocalWithParenthesizedLambdaParameter(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ using System; class Program { static void Main(string[] args) { int {|stmt1:$$x|} = 1; Func<int> lambda = ({|Conflict:y|}) => 42; } } ]]></Document> </Project> </Workspace>, host:=host, renameTo:="y") result.AssertLabeledSpansAre("stmt1", "y", RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictingFromClauseWithLetClause(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System.Linq; class C { static void Main(string[] args) { var temp = from [|$$x|] in "abc" let {|DeclarationConflict:y|} = [|x|].ToString() select {|Conflict:y|}; } } </Document> </Project> </Workspace>, host:=host, renameTo:="y") ' We have two kinds of conflicts here: we flag a declaration conflict on the let: result.AssertLabeledSpansAre("DeclarationConflict", type:=RelatedLocationType.UnresolvedConflict) ' And also for the y in the select clause. The compiler binds the "y" to the let ' clause's y. result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <WorkItem(543407, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543407")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictBetweenLabelsInSameMethod(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> using System; public class C { public void Goo() { {|stmt1:$$Bar|}:; {|Conflict:Goo|}:; } } </Document> </Project> </Workspace>, host:=host, renameTo:="Goo") result.AssertLabeledSpansAre("stmt1", "Goo", RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <WorkItem(543407, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543407")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictBetweenLabelInMethodAndLambda(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> using System; public class C { public void Goo() { {|stmt1:$$Bar|}: ; Action x = () => { {|Conflict:Goo|}:;}; } } </Document> </Project> </Workspace>, host:=host, renameTo:="Goo") result.AssertLabeledSpansAre("stmt1", "Goo", RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <WorkItem(543407, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543407")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictBetweenLabelsInLambda(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> using System; public class C { Action x = () => { {|Conflict:Goo|}:; {|stmt1:$$Bar|}: ; }; } </Document> </Project> </Workspace>, host:=host, renameTo:="Goo") result.AssertLabeledSpansAre("stmt1", "Goo", RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <WorkItem(543407, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543407")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub NoConflictBetweenLabelsInTwoNonNestedLambdas(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> using System; public class C { public void Goo() { Action x = () => { Goo:; }; Action x = () => { {|stmt1:$$Bar|}:; }; } } </Document> </Project> </Workspace>, host:=host, renameTo:="Goo") result.AssertLabeledSpansAre("stmt1", "Goo", RelatedLocationType.NoConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(545468, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545468")> Public Sub NoConflictsWithCatchBlockWithoutExceptionVariable(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Test { static void Main() { try { int {|stmt1:$$i|}; } catch (System.Exception) { } } } </Document> </Project> </Workspace>, host:=host, renameTo:="j") result.AssertLabeledSpansAre("stmt1", "j", RelatedLocationType.NoConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(1081066, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1081066")> Public Sub NoConflictsBetweenCatchClauses(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System; class Test { static void Main() { try { } catch (Exception {|stmt1:$$ex|}) { } try { } catch (Exception j) { } } } </Document> </Project> </Workspace>, host:=host, renameTo:="j") result.AssertLabeledSpansAre("stmt1", "j", RelatedLocationType.NoConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(1081066, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1081066")> Public Sub ConflictsWithinCatchClause(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System; class Test { static void Main() { try { } catch (Exception {|stmt1:$$ex|}) { int {|stmt2:j|}; } try { } catch (Exception j) { } } } </Document> </Project> </Workspace>, host:=host, renameTo:="j") result.AssertLabeledSpansAre("stmt1", "j", RelatedLocationType.UnresolvableConflict) result.AssertLabeledSpansAre("stmt2", "j", RelatedLocationType.UnresolvableConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(546163, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546163")> Public Sub NoConflictsWithCatchExceptionWithoutDeclaration(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Test { static void Main() { try { int {|stmt1:$$i|}; } catch { } } } </Document> </Project> </Workspace>, host:=host, renameTo:="j") result.AssertLabeledSpansAre("stmt1", "j", RelatedLocationType.NoConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(992721, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/992721")> Public Sub ConflictingLocalWithFieldWithExtensionMethodInvolved(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System.Collections.Generic; using System.Linq; namespace ConsoleApplication1 { class Program { private List&lt;object&gt; {|def:_list|}; public Program(IEnumerable&lt;object&gt; list) { {|stmt2:_list|} = list.ToList(); foreach (var i in {|stmt1:$$_list|}.OfType&lt;int&gt;()){} } } } </Document> </Project> </Workspace>, host:=host, renameTo:="list") result.AssertLabeledSpansAre("def", "list", RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("stmt1", "foreach (var i in this.list.OfType<int>()){}", RelatedLocationType.ResolvedReferenceConflict) result.AssertLabeledSpansAre("stmt2", "this.list = list.ToList();", RelatedLocationType.ResolvedReferenceConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(17177, "https://github.com/dotnet/roslyn/issues/17177")> Public Sub ConflictsBetweenSwitchCaseStatementsWithoutBlocks(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Test { static void Main() { switch (true) { case true: object {|stmt1:$$i|} = null; break; case false: object {|stmt2:j|} = null; break; } } } </Document> </Project> </Workspace>, host:=host, renameTo:="j") result.AssertLabeledSpansAre("stmt1", "j", RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("stmt2", "j", RelatedLocationType.UnresolvableConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(17177, "https://github.com/dotnet/roslyn/issues/17177")> Public Sub NoConflictsBetweenSwitchCaseStatementsWithBlocks(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Test { static void Main() { switch (true) { case true: { object {|stmt1:$$i|} = null; break; } case false: { object j = null; break; } } } } </Document> </Project> </Workspace>, host:=host, renameTo:="j") result.AssertLabeledSpansAre("stmt1", "j", RelatedLocationType.NoConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(17177, "https://github.com/dotnet/roslyn/issues/17177")> Public Sub NoConflictsBetweenSwitchCaseStatementFirstStatementWithBlock(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Test { static void Main() { switch (true) { case true: { object {|stmt1:$$i|} = null; break; } case false: object {|stmt2:j|} = null; break; } } } </Document> </Project> </Workspace>, host:=host, renameTo:="j") result.AssertLabeledSpansAre("stmt1", "j", RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("stmt2", "j", RelatedLocationType.UnresolvableConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(17177, "https://github.com/dotnet/roslyn/issues/17177")> Public Sub NoConflictsBetweenSwitchCaseStatementSecondStatementWithBlock(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Test { static void Main() { switch (true) { case true: object {|stmt1:$$i|} = null; break; case false: { object {|stmt2:j|} = null; break; } } } } </Document> </Project> </Workspace>, host:=host, renameTo:="j") result.AssertLabeledSpansAre("stmt1", "j", RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("stmt2", "j", RelatedLocationType.UnresolvableConflict) End Using End Sub End Class End Namespace
' 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.Remote.Testing Imports Microsoft.CodeAnalysis.Rename.ConflictEngine Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Rename.CSharp <[UseExportProvider]> Public Class LocalConflictTests Private ReadOnly _outputHelper As Abstractions.ITestOutputHelper Public Sub New(outputHelper As Abstractions.ITestOutputHelper) _outputHelper = outputHelper End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(539939, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539939")> Public Sub ConflictingLocalWithLocal(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Program { static void Main(string[] args) { int {|stmt1:$$x|} = 1; int {|Conflict:y|} = 2; } } </Document> </Project> </Workspace>, host:=host, renameTo:="y") result.AssertLabeledSpansAre("stmt1", "y", type:=RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(539939, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539939")> Public Sub ConflictingLocalWithParameter(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Program { static void Main(string[] {|Conflict:args|}) { int {|stmt1:$$x|} = 1; } } </Document> </Project> </Workspace>, host:=host, renameTo:="args") result.AssertLabeledSpansAre("stmt1", "args", RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictingLocalWithForEachRangeVariable(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Program { static void Main(string[] args) { int {|stmt1:$$x|} = 1; foreach (var {|Conflict:y|} in args) { } } } </Document> </Project> </Workspace>, host:=host, renameTo:="y") result.AssertLabeledSpansAre("stmt1", "y", RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictingLocalWithForLoopVariable(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Program { static void Main(string[] args) { int {|stmt1:$$x|} = 1; for (int {|Conflict:y|} = 0; ; } { } } } </Document> </Project> </Workspace>, host:=host, renameTo:="y") result.AssertLabeledSpansAre("stmt1", "y", RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictingLocalWithUsingBlockVariable(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Program : IDisposable { static void Main(string[] args) { int {|stmt1:$$x|} = 1; using (var {|Conflict:y|} = new Program()) { } } } </Document> </Project> </Workspace>, host:=host, renameTo:="y") result.AssertLabeledSpansAre("stmt1", "y", RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictingLocalWithSimpleLambdaParameter(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ using System; class Program { static void Main(string[] args) { int {|stmt1:$$x|} = 1; Func<int> lambda = {|Conflict:y|} => 42; } } ]]></Document> </Project> </Workspace>, host:=host, renameTo:="y") result.AssertLabeledSpansAre("stmt1", "y", RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictingLocalWithParenthesizedLambdaParameter(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ using System; class Program { static void Main(string[] args) { int {|stmt1:$$x|} = 1; Func<int> lambda = ({|Conflict:y|}) => 42; } } ]]></Document> </Project> </Workspace>, host:=host, renameTo:="y") result.AssertLabeledSpansAre("stmt1", "y", RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictingFromClauseWithLetClause(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System.Linq; class C { static void Main(string[] args) { var temp = from [|$$x|] in "abc" let {|DeclarationConflict:y|} = [|x|].ToString() select {|Conflict:y|}; } } </Document> </Project> </Workspace>, host:=host, renameTo:="y") ' We have two kinds of conflicts here: we flag a declaration conflict on the let: result.AssertLabeledSpansAre("DeclarationConflict", type:=RelatedLocationType.UnresolvedConflict) ' And also for the y in the select clause. The compiler binds the "y" to the let ' clause's y. result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <WorkItem(543407, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543407")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictBetweenLabelsInSameMethod(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> using System; public class C { public void Goo() { {|stmt1:$$Bar|}:; {|Conflict:Goo|}:; } } </Document> </Project> </Workspace>, host:=host, renameTo:="Goo") result.AssertLabeledSpansAre("stmt1", "Goo", RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <WorkItem(543407, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543407")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictBetweenLabelInMethodAndLambda(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> using System; public class C { public void Goo() { {|stmt1:$$Bar|}: ; Action x = () => { {|Conflict:Goo|}:;}; } } </Document> </Project> </Workspace>, host:=host, renameTo:="Goo") result.AssertLabeledSpansAre("stmt1", "Goo", RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <WorkItem(543407, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543407")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictBetweenLabelsInLambda(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> using System; public class C { Action x = () => { {|Conflict:Goo|}:; {|stmt1:$$Bar|}: ; }; } </Document> </Project> </Workspace>, host:=host, renameTo:="Goo") result.AssertLabeledSpansAre("stmt1", "Goo", RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <WorkItem(543407, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543407")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub NoConflictBetweenLabelsInTwoNonNestedLambdas(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> using System; public class C { public void Goo() { Action x = () => { Goo:; }; Action x = () => { {|stmt1:$$Bar|}:; }; } } </Document> </Project> </Workspace>, host:=host, renameTo:="Goo") result.AssertLabeledSpansAre("stmt1", "Goo", RelatedLocationType.NoConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(545468, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545468")> Public Sub NoConflictsWithCatchBlockWithoutExceptionVariable(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Test { static void Main() { try { int {|stmt1:$$i|}; } catch (System.Exception) { } } } </Document> </Project> </Workspace>, host:=host, renameTo:="j") result.AssertLabeledSpansAre("stmt1", "j", RelatedLocationType.NoConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(1081066, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1081066")> Public Sub NoConflictsBetweenCatchClauses(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System; class Test { static void Main() { try { } catch (Exception {|stmt1:$$ex|}) { } try { } catch (Exception j) { } } } </Document> </Project> </Workspace>, host:=host, renameTo:="j") result.AssertLabeledSpansAre("stmt1", "j", RelatedLocationType.NoConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(1081066, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1081066")> Public Sub ConflictsWithinCatchClause(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System; class Test { static void Main() { try { } catch (Exception {|stmt1:$$ex|}) { int {|stmt2:j|}; } try { } catch (Exception j) { } } } </Document> </Project> </Workspace>, host:=host, renameTo:="j") result.AssertLabeledSpansAre("stmt1", "j", RelatedLocationType.UnresolvableConflict) result.AssertLabeledSpansAre("stmt2", "j", RelatedLocationType.UnresolvableConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(546163, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546163")> Public Sub NoConflictsWithCatchExceptionWithoutDeclaration(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Test { static void Main() { try { int {|stmt1:$$i|}; } catch { } } } </Document> </Project> </Workspace>, host:=host, renameTo:="j") result.AssertLabeledSpansAre("stmt1", "j", RelatedLocationType.NoConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(992721, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/992721")> Public Sub ConflictingLocalWithFieldWithExtensionMethodInvolved(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System.Collections.Generic; using System.Linq; namespace ConsoleApplication1 { class Program { private List&lt;object&gt; {|def:_list|}; public Program(IEnumerable&lt;object&gt; list) { {|stmt2:_list|} = list.ToList(); foreach (var i in {|stmt1:$$_list|}.OfType&lt;int&gt;()){} } } } </Document> </Project> </Workspace>, host:=host, renameTo:="list") result.AssertLabeledSpansAre("def", "list", RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("stmt1", "foreach (var i in this.list.OfType<int>()){}", RelatedLocationType.ResolvedReferenceConflict) result.AssertLabeledSpansAre("stmt2", "this.list = list.ToList();", RelatedLocationType.ResolvedReferenceConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(17177, "https://github.com/dotnet/roslyn/issues/17177")> Public Sub ConflictsBetweenSwitchCaseStatementsWithoutBlocks(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Test { static void Main() { switch (true) { case true: object {|stmt1:$$i|} = null; break; case false: object {|stmt2:j|} = null; break; } } } </Document> </Project> </Workspace>, host:=host, renameTo:="j") result.AssertLabeledSpansAre("stmt1", "j", RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("stmt2", "j", RelatedLocationType.UnresolvableConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(17177, "https://github.com/dotnet/roslyn/issues/17177")> Public Sub NoConflictsBetweenSwitchCaseStatementsWithBlocks(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Test { static void Main() { switch (true) { case true: { object {|stmt1:$$i|} = null; break; } case false: { object j = null; break; } } } } </Document> </Project> </Workspace>, host:=host, renameTo:="j") result.AssertLabeledSpansAre("stmt1", "j", RelatedLocationType.NoConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(17177, "https://github.com/dotnet/roslyn/issues/17177")> Public Sub NoConflictsBetweenSwitchCaseStatementFirstStatementWithBlock(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Test { static void Main() { switch (true) { case true: { object {|stmt1:$$i|} = null; break; } case false: object {|stmt2:j|} = null; break; } } } </Document> </Project> </Workspace>, host:=host, renameTo:="j") result.AssertLabeledSpansAre("stmt1", "j", RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("stmt2", "j", RelatedLocationType.UnresolvableConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(17177, "https://github.com/dotnet/roslyn/issues/17177")> Public Sub NoConflictsBetweenSwitchCaseStatementSecondStatementWithBlock(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Test { static void Main() { switch (true) { case true: object {|stmt1:$$i|} = null; break; case false: { object {|stmt2:j|} = null; break; } } } } </Document> </Project> </Workspace>, host:=host, renameTo:="j") result.AssertLabeledSpansAre("stmt1", "j", RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("stmt2", "j", RelatedLocationType.UnresolvableConflict) End Using End Sub End Class End Namespace
-1
dotnet/roslyn
56,011
React to string comparison changing on .NET Core
The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
jaredpar
"2021-08-30T17:18:52Z"
"2021-08-30T20:20:04Z"
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
4d99cda6e446e77dbb302e26388c1093bd3ef569
React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
./src/Compilers/VisualBasic/Portable/Syntax/ArrayRankSpecifierSyntax.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax Partial Public Class ArrayRankSpecifierSyntax ''' <summary> ''' Returns the ranks of this array rank specifier. ''' </summary> Public ReadOnly Property Rank() As Integer Get Return Me.CommaTokens.Count + 1 End Get End Property End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax Partial Public Class ArrayRankSpecifierSyntax ''' <summary> ''' Returns the ranks of this array rank specifier. ''' </summary> Public ReadOnly Property Rank() As Integer Get Return Me.CommaTokens.Count + 1 End Get End Property End Class End Namespace
-1
dotnet/roslyn
56,011
React to string comparison changing on .NET Core
The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
jaredpar
"2021-08-30T17:18:52Z"
"2021-08-30T20:20:04Z"
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
4d99cda6e446e77dbb302e26388c1093bd3ef569
React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
./src/CodeStyle/VisualBasic/Tests/FormattingAnalyzerTests.vb
' 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 VerifyVB = Microsoft.CodeAnalysis.VisualBasic.Testing.VisualBasicCodeFixVerifier( Of Microsoft.CodeAnalysis.CodeStyle.VisualBasicFormattingAnalyzer, Microsoft.CodeAnalysis.CodeStyle.VisualBasicFormattingCodeFixProvider, Microsoft.CodeAnalysis.Testing.Verifiers.XUnitVerifier) Namespace Microsoft.CodeAnalysis.CodeStyle Public Class FormattingAnalyzerTests <Fact> Public Async Function TestCaseCorrection() As Task Dim testCode = " class TestClass public Sub MyMethod() End Sub end class " ' Currently the analyzer and code fix rely on Formatter.FormatAsync, which does not normalize the casing of ' keywords in Visual Basic. Await VerifyVB.VerifyAnalyzerAsync(testCode) End Function End Class End Namespace
' 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 VerifyVB = Microsoft.CodeAnalysis.VisualBasic.Testing.VisualBasicCodeFixVerifier( Of Microsoft.CodeAnalysis.CodeStyle.VisualBasicFormattingAnalyzer, Microsoft.CodeAnalysis.CodeStyle.VisualBasicFormattingCodeFixProvider, Microsoft.CodeAnalysis.Testing.Verifiers.XUnitVerifier) Namespace Microsoft.CodeAnalysis.CodeStyle Public Class FormattingAnalyzerTests <Fact> Public Async Function TestCaseCorrection() As Task Dim testCode = " class TestClass public Sub MyMethod() End Sub end class " ' Currently the analyzer and code fix rely on Formatter.FormatAsync, which does not normalize the casing of ' keywords in Visual Basic. Await VerifyVB.VerifyAnalyzerAsync(testCode) End Function End Class End Namespace
-1
dotnet/roslyn
56,011
React to string comparison changing on .NET Core
The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
jaredpar
"2021-08-30T17:18:52Z"
"2021-08-30T20:20:04Z"
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
4d99cda6e446e77dbb302e26388c1093bd3ef569
React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
./src/EditorFeatures/VisualBasic/Utilities/CommandHandlers/AbstractImplementAbstractClassOrInterfaceCommandHandler.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Editor.Implementation.EndConstructGeneration Imports Microsoft.CodeAnalysis.Formatting Imports Microsoft.CodeAnalysis.Simplification Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.Text.Shared.Extensions Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.VisualStudio.Commanding Imports Microsoft.VisualStudio.Text Imports Microsoft.VisualStudio.Text.Editor.Commanding.Commands Imports Microsoft.VisualStudio.Text.Operations Imports Microsoft.VisualStudio.Utilities Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.Utilities.CommandHandlers Friend MustInherit Class AbstractImplementAbstractClassOrInterfaceCommandHandler Implements ICommandHandler(Of ReturnKeyCommandArgs) Private ReadOnly _editorOperationsFactoryService As IEditorOperationsFactoryService Public ReadOnly Property DisplayName As String Implements INamed.DisplayName Get Return VBEditorResources.Implement_Abstract_Class_Or_Interface End Get End Property Protected Sub New(editorOperationsFactoryService As IEditorOperationsFactoryService) _editorOperationsFactoryService = editorOperationsFactoryService End Sub Protected MustOverride Overloads Function TryGetNewDocument( document As Document, typeSyntax As TypeSyntax, cancellationToken As CancellationToken) As Document Private Function ExecuteCommand(args As ReturnKeyCommandArgs, context As CommandExecutionContext) As Boolean Implements ICommandHandler(Of ReturnKeyCommandArgs).ExecuteCommand Dim caretPointOpt = args.TextView.GetCaretPoint(args.SubjectBuffer) If caretPointOpt Is Nothing Then Return False End If ' Implement interface is not cancellable. Dim _cancellationToken = CancellationToken.None If Not TryExecute(args, _cancellationToken) Then Return False End If ' It's possible that there may be an end construct to generate at this position. ' We'll go ahead and generate it before determining whether we need to move the caret TryGenerateEndConstruct(args, _cancellationToken) Dim snapshot = args.SubjectBuffer.CurrentSnapshot Dim caretPosition = args.TextView.GetCaretPoint(args.SubjectBuffer).Value Dim caretLine = snapshot.GetLineFromPosition(caretPosition) ' If there is any text after the caret on the same line, we'll pass through to ' insert a new line. Dim lastNonWhitespacePosition = If(caretLine.GetLastNonWhitespacePosition(), -1) If lastNonWhitespacePosition > caretPosition.Position Then Return False End If Dim nextLine = snapshot.GetLineFromLineNumber(caretLine.LineNumber + 1) If Not nextLine.IsEmptyOrWhitespace() Then ' If the next line is not whitespace, we'll go ahead and pass through to insert a new line. Return False End If ' If the next line *is* whitespace, we're just going to move the caret down a line. _editorOperationsFactoryService.GetEditorOperations(args.TextView).MoveLineDown(extendSelection:=False) Return True End Function Private Shared Function TryGenerateEndConstruct(args As ReturnKeyCommandArgs, cancellationToken As CancellationToken) As Boolean Dim textSnapshot = args.SubjectBuffer.CurrentSnapshot Dim document = textSnapshot.GetOpenDocumentInCurrentContextWithChanges() If document Is Nothing Then Return False End If Dim caretPointOpt = args.TextView.GetCaretPoint(args.SubjectBuffer) If caretPointOpt Is Nothing Then Return False End If Dim caretPosition = caretPointOpt.Value.Position If caretPosition = 0 Then Return False End If Dim endConstructGenerationService = document.GetLanguageService(Of IEndConstructGenerationService)() Return endConstructGenerationService.TryDo(args.TextView, args.SubjectBuffer, vbLf(0), cancellationToken) End Function Private Overloads Function TryExecute(args As ReturnKeyCommandArgs, cancellationToken As CancellationToken) As Boolean Dim textSnapshot = args.SubjectBuffer.CurrentSnapshot Dim text = textSnapshot.AsText() Dim document = textSnapshot.GetOpenDocumentInCurrentContextWithChanges() If document Is Nothing Then Return False End If If Not args.SubjectBuffer.GetFeatureOnOffOption(FeatureOnOffOptions.AutomaticInsertionOfAbstractOrInterfaceMembers) Then Return False End If Dim caretPointOpt = args.TextView.GetCaretPoint(args.SubjectBuffer) If caretPointOpt Is Nothing Then Return False End If Dim caretPosition = caretPointOpt.Value.Position If caretPosition = 0 Then Return False End If Dim syntaxRoot = document.GetSyntaxRootSynchronously(cancellationToken) Dim token = syntaxRoot.FindTokenOnLeftOfPosition(caretPosition) If text.Lines.IndexOf(token.SpanStart) <> text.Lines.IndexOf(caretPosition) Then Return False End If Dim statement = token.GetAncestor(Of InheritsOrImplementsStatementSyntax)() If statement Is Nothing Then Return False End If If statement.Span.End <> token.Span.End Then Return False End If ' We need to track this token into the resulting buffer so we know what to do with the cursor ' from there Dim caretOffsetFromToken = caretPosition - token.Span.End Dim tokenAnnotation As New SyntaxAnnotation() document = document.WithSyntaxRoot(syntaxRoot.ReplaceToken(token, token.WithAdditionalAnnotations(tokenAnnotation))) token = document.GetSyntaxRootSynchronously(cancellationToken). GetAnnotatedNodesAndTokens(tokenAnnotation).First().AsToken() Dim typeSyntax = token.GetAncestor(Of TypeSyntax)() If typeSyntax Is Nothing Then Return False End If ' get top most identifier Dim identifier = DirectCast(typeSyntax.AncestorsAndSelf(ascendOutOfTrivia:=False).Where(Function(t) TypeOf t Is TypeSyntax).LastOrDefault(), TypeSyntax) If identifier Is Nothing Then Return False End If Dim newDocument = TryGetNewDocument(document, identifier, cancellationToken) If newDocument Is Nothing Then Return False End If newDocument = Simplifier.ReduceAsync(newDocument, Simplifier.Annotation, Nothing, cancellationToken).WaitAndGetResult(cancellationToken) newDocument = Formatter.FormatAsync(newDocument, Formatter.Annotation, cancellationToken:=cancellationToken).WaitAndGetResult(cancellationToken) newDocument.Project.Solution.Workspace.ApplyDocumentChanges(newDocument, cancellationToken) ' Place the cursor back to where it logically was after this token = newDocument.GetSyntaxRootSynchronously(cancellationToken). GetAnnotatedNodesAndTokens(tokenAnnotation).First().AsToken() args.TextView.TryMoveCaretToAndEnsureVisible( New SnapshotPoint(args.SubjectBuffer.CurrentSnapshot, Math.Min(token.Span.End + caretOffsetFromToken, args.SubjectBuffer.CurrentSnapshot.Length))) Return True End Function Private Function GetCommandState(args As ReturnKeyCommandArgs) As CommandState Implements ICommandHandler(Of ReturnKeyCommandArgs).GetCommandState Return CommandState.Unspecified End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Editor.Implementation.EndConstructGeneration Imports Microsoft.CodeAnalysis.Formatting Imports Microsoft.CodeAnalysis.Simplification Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.Text.Shared.Extensions Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.VisualStudio.Commanding Imports Microsoft.VisualStudio.Text Imports Microsoft.VisualStudio.Text.Editor.Commanding.Commands Imports Microsoft.VisualStudio.Text.Operations Imports Microsoft.VisualStudio.Utilities Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.Utilities.CommandHandlers Friend MustInherit Class AbstractImplementAbstractClassOrInterfaceCommandHandler Implements ICommandHandler(Of ReturnKeyCommandArgs) Private ReadOnly _editorOperationsFactoryService As IEditorOperationsFactoryService Public ReadOnly Property DisplayName As String Implements INamed.DisplayName Get Return VBEditorResources.Implement_Abstract_Class_Or_Interface End Get End Property Protected Sub New(editorOperationsFactoryService As IEditorOperationsFactoryService) _editorOperationsFactoryService = editorOperationsFactoryService End Sub Protected MustOverride Overloads Function TryGetNewDocument( document As Document, typeSyntax As TypeSyntax, cancellationToken As CancellationToken) As Document Private Function ExecuteCommand(args As ReturnKeyCommandArgs, context As CommandExecutionContext) As Boolean Implements ICommandHandler(Of ReturnKeyCommandArgs).ExecuteCommand Dim caretPointOpt = args.TextView.GetCaretPoint(args.SubjectBuffer) If caretPointOpt Is Nothing Then Return False End If ' Implement interface is not cancellable. Dim _cancellationToken = CancellationToken.None If Not TryExecute(args, _cancellationToken) Then Return False End If ' It's possible that there may be an end construct to generate at this position. ' We'll go ahead and generate it before determining whether we need to move the caret TryGenerateEndConstruct(args, _cancellationToken) Dim snapshot = args.SubjectBuffer.CurrentSnapshot Dim caretPosition = args.TextView.GetCaretPoint(args.SubjectBuffer).Value Dim caretLine = snapshot.GetLineFromPosition(caretPosition) ' If there is any text after the caret on the same line, we'll pass through to ' insert a new line. Dim lastNonWhitespacePosition = If(caretLine.GetLastNonWhitespacePosition(), -1) If lastNonWhitespacePosition > caretPosition.Position Then Return False End If Dim nextLine = snapshot.GetLineFromLineNumber(caretLine.LineNumber + 1) If Not nextLine.IsEmptyOrWhitespace() Then ' If the next line is not whitespace, we'll go ahead and pass through to insert a new line. Return False End If ' If the next line *is* whitespace, we're just going to move the caret down a line. _editorOperationsFactoryService.GetEditorOperations(args.TextView).MoveLineDown(extendSelection:=False) Return True End Function Private Shared Function TryGenerateEndConstruct(args As ReturnKeyCommandArgs, cancellationToken As CancellationToken) As Boolean Dim textSnapshot = args.SubjectBuffer.CurrentSnapshot Dim document = textSnapshot.GetOpenDocumentInCurrentContextWithChanges() If document Is Nothing Then Return False End If Dim caretPointOpt = args.TextView.GetCaretPoint(args.SubjectBuffer) If caretPointOpt Is Nothing Then Return False End If Dim caretPosition = caretPointOpt.Value.Position If caretPosition = 0 Then Return False End If Dim endConstructGenerationService = document.GetLanguageService(Of IEndConstructGenerationService)() Return endConstructGenerationService.TryDo(args.TextView, args.SubjectBuffer, vbLf(0), cancellationToken) End Function Private Overloads Function TryExecute(args As ReturnKeyCommandArgs, cancellationToken As CancellationToken) As Boolean Dim textSnapshot = args.SubjectBuffer.CurrentSnapshot Dim text = textSnapshot.AsText() Dim document = textSnapshot.GetOpenDocumentInCurrentContextWithChanges() If document Is Nothing Then Return False End If If Not args.SubjectBuffer.GetFeatureOnOffOption(FeatureOnOffOptions.AutomaticInsertionOfAbstractOrInterfaceMembers) Then Return False End If Dim caretPointOpt = args.TextView.GetCaretPoint(args.SubjectBuffer) If caretPointOpt Is Nothing Then Return False End If Dim caretPosition = caretPointOpt.Value.Position If caretPosition = 0 Then Return False End If Dim syntaxRoot = document.GetSyntaxRootSynchronously(cancellationToken) Dim token = syntaxRoot.FindTokenOnLeftOfPosition(caretPosition) If text.Lines.IndexOf(token.SpanStart) <> text.Lines.IndexOf(caretPosition) Then Return False End If Dim statement = token.GetAncestor(Of InheritsOrImplementsStatementSyntax)() If statement Is Nothing Then Return False End If If statement.Span.End <> token.Span.End Then Return False End If ' We need to track this token into the resulting buffer so we know what to do with the cursor ' from there Dim caretOffsetFromToken = caretPosition - token.Span.End Dim tokenAnnotation As New SyntaxAnnotation() document = document.WithSyntaxRoot(syntaxRoot.ReplaceToken(token, token.WithAdditionalAnnotations(tokenAnnotation))) token = document.GetSyntaxRootSynchronously(cancellationToken). GetAnnotatedNodesAndTokens(tokenAnnotation).First().AsToken() Dim typeSyntax = token.GetAncestor(Of TypeSyntax)() If typeSyntax Is Nothing Then Return False End If ' get top most identifier Dim identifier = DirectCast(typeSyntax.AncestorsAndSelf(ascendOutOfTrivia:=False).Where(Function(t) TypeOf t Is TypeSyntax).LastOrDefault(), TypeSyntax) If identifier Is Nothing Then Return False End If Dim newDocument = TryGetNewDocument(document, identifier, cancellationToken) If newDocument Is Nothing Then Return False End If newDocument = Simplifier.ReduceAsync(newDocument, Simplifier.Annotation, Nothing, cancellationToken).WaitAndGetResult(cancellationToken) newDocument = Formatter.FormatAsync(newDocument, Formatter.Annotation, cancellationToken:=cancellationToken).WaitAndGetResult(cancellationToken) newDocument.Project.Solution.Workspace.ApplyDocumentChanges(newDocument, cancellationToken) ' Place the cursor back to where it logically was after this token = newDocument.GetSyntaxRootSynchronously(cancellationToken). GetAnnotatedNodesAndTokens(tokenAnnotation).First().AsToken() args.TextView.TryMoveCaretToAndEnsureVisible( New SnapshotPoint(args.SubjectBuffer.CurrentSnapshot, Math.Min(token.Span.End + caretOffsetFromToken, args.SubjectBuffer.CurrentSnapshot.Length))) Return True End Function Private Function GetCommandState(args As ReturnKeyCommandArgs) As CommandState Implements ICommandHandler(Of ReturnKeyCommandArgs).GetCommandState Return CommandState.Unspecified End Function End Class End Namespace
-1
dotnet/roslyn
56,011
React to string comparison changing on .NET Core
The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
jaredpar
"2021-08-30T17:18:52Z"
"2021-08-30T20:20:04Z"
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
4d99cda6e446e77dbb302e26388c1093bd3ef569
React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
./src/Compilers/VisualBasic/Portable/Analysis/FlowAnalysis/DefinitelyAssignedWalker.vb
' 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. #If DEBUG Then ' See comment in DefiniteAssignment. #Const REFERENCE_STATE = True #End If Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' A region analysis walker that computes the set of variables that are definitely assigned ''' when a region is entered. ''' </summary> Friend Class DefinitelyAssignedWalker Inherits AbstractRegionDataFlowPass Private ReadOnly _definitelyAssignedOnEntry As New HashSet(Of Symbol)() Private ReadOnly _definitelyAssignedOnExit As New HashSet(Of Symbol)() Private Sub New(info As FlowAnalysisInfo, region As FlowAnalysisRegionInfo) MyBase.New(info, region) End Sub Friend Overloads Shared Function Analyze(info As FlowAnalysisInfo, region As FlowAnalysisRegionInfo) As (entry As HashSet(Of Symbol), ex As HashSet(Of Symbol)) Dim walker = New DefinitelyAssignedWalker(info, region) Try Dim success = walker.Analyze() Return If(success, (walker._definitelyAssignedOnEntry, walker._definitelyAssignedOnExit), (New HashSet(Of Symbol), New HashSet(Of Symbol))) Finally walker.Free() End Try End Function Protected Overrides Sub EnterRegion() ProcessRegion(_definitelyAssignedOnEntry) MyBase.EnterRegion() End Sub Protected Overrides Sub LeaveRegion() ProcessRegion(_definitelyAssignedOnExit) MyBase.LeaveRegion() End Sub Private Sub ProcessRegion(definitelyAssigned As HashSet(Of Symbol)) ' this can happen multiple times as flow analysis Is multi-pass. Always ' take the latest data And use that to determine our result. definitelyAssigned.Clear() If Me.IsConditionalState Then ' We're in a state where there are different flow paths (i.e. when-true and when-false). ' In that case, a variable Is only definitely assigned if it's definitely assigned through ' both paths. Me.ProcessState(definitelyAssigned, Me.StateWhenTrue, Me.StateWhenFalse) Else Me.ProcessState(definitelyAssigned, Me.State, state2opt:=Nothing) End If End Sub #If REFERENCE_STATE Then Private Sub ProcessState(definitelyAssigned As HashSet(Of Symbol), state1 As LocalState, state2opt As LocalState) #Else Private Sub ProcessState(definitelyAssigned As HashSet(Of Symbol), state1 As LocalState, state2opt As LocalState?) #End If For Each slot In state1.Assigned.TrueBits() If slot < variableBySlot.Length Then #If REFERENCE_STATE Then If state2opt Is Nothing OrElse state2opt.IsAssigned(slot) Then #Else If state2opt Is Nothing OrElse state2opt.Value.IsAssigned(slot) Then #End If Dim symbol = variableBySlot(slot).Symbol If symbol IsNot Nothing AndAlso symbol.Kind <> SymbolKind.Field Then definitelyAssigned.Add(symbol) End If End If End If Next End Sub End Class End Namespace
' 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. #If DEBUG Then ' See comment in DefiniteAssignment. #Const REFERENCE_STATE = True #End If Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' A region analysis walker that computes the set of variables that are definitely assigned ''' when a region is entered. ''' </summary> Friend Class DefinitelyAssignedWalker Inherits AbstractRegionDataFlowPass Private ReadOnly _definitelyAssignedOnEntry As New HashSet(Of Symbol)() Private ReadOnly _definitelyAssignedOnExit As New HashSet(Of Symbol)() Private Sub New(info As FlowAnalysisInfo, region As FlowAnalysisRegionInfo) MyBase.New(info, region) End Sub Friend Overloads Shared Function Analyze(info As FlowAnalysisInfo, region As FlowAnalysisRegionInfo) As (entry As HashSet(Of Symbol), ex As HashSet(Of Symbol)) Dim walker = New DefinitelyAssignedWalker(info, region) Try Dim success = walker.Analyze() Return If(success, (walker._definitelyAssignedOnEntry, walker._definitelyAssignedOnExit), (New HashSet(Of Symbol), New HashSet(Of Symbol))) Finally walker.Free() End Try End Function Protected Overrides Sub EnterRegion() ProcessRegion(_definitelyAssignedOnEntry) MyBase.EnterRegion() End Sub Protected Overrides Sub LeaveRegion() ProcessRegion(_definitelyAssignedOnExit) MyBase.LeaveRegion() End Sub Private Sub ProcessRegion(definitelyAssigned As HashSet(Of Symbol)) ' this can happen multiple times as flow analysis Is multi-pass. Always ' take the latest data And use that to determine our result. definitelyAssigned.Clear() If Me.IsConditionalState Then ' We're in a state where there are different flow paths (i.e. when-true and when-false). ' In that case, a variable Is only definitely assigned if it's definitely assigned through ' both paths. Me.ProcessState(definitelyAssigned, Me.StateWhenTrue, Me.StateWhenFalse) Else Me.ProcessState(definitelyAssigned, Me.State, state2opt:=Nothing) End If End Sub #If REFERENCE_STATE Then Private Sub ProcessState(definitelyAssigned As HashSet(Of Symbol), state1 As LocalState, state2opt As LocalState) #Else Private Sub ProcessState(definitelyAssigned As HashSet(Of Symbol), state1 As LocalState, state2opt As LocalState?) #End If For Each slot In state1.Assigned.TrueBits() If slot < variableBySlot.Length Then #If REFERENCE_STATE Then If state2opt Is Nothing OrElse state2opt.IsAssigned(slot) Then #Else If state2opt Is Nothing OrElse state2opt.Value.IsAssigned(slot) Then #End If Dim symbol = variableBySlot(slot).Symbol If symbol IsNot Nothing AndAlso symbol.Kind <> SymbolKind.Field Then definitelyAssigned.Add(symbol) End If End If End If Next End Sub End Class End Namespace
-1
dotnet/roslyn
56,011
React to string comparison changing on .NET Core
The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
jaredpar
"2021-08-30T17:18:52Z"
"2021-08-30T20:20:04Z"
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
4d99cda6e446e77dbb302e26388c1093bd3ef569
React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
./src/Compilers/VisualBasic/Test/CommandLine/SarifErrorLoggerTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Globalization Imports System.IO Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests Imports Xunit Imports Microsoft.CodeAnalysis.CommonDiagnosticAnalyzers Imports Roslyn.Test.Utilities.SharedResourceHelpers Namespace Microsoft.CodeAnalysis.VisualBasic.CommandLine.UnitTests Public MustInherit Class SarifErrorLoggerTests Inherits BasicTestBase Private ReadOnly _baseDirectory As String = TempRoot.Root Protected MustOverride ReadOnly Property ErrorLogQualifier As String Friend MustOverride Function GetExpectedOutputForNoDiagnostics( cmd As CommonCompiler) As String Friend MustOverride Function GetExpectedOutputForSimpleCompilerDiagnostics( cmd As CommonCompiler, sourceFilePath As String) As String Friend MustOverride Function GetExpectedOutputForSimpleCompilerDiagnosticsSuppressed( cmd As CommonCompiler, sourceFilePath As String) As String Friend MustOverride Function GetExpectedOutputForAnalyzerDiagnosticsWithAndWithoutLocation( cmd As MockVisualBasicCompiler) As String Protected Sub NoDiagnosticsImpl() Dim helloWorldVB As String = <text> Imports System Class C Shared Sub Main(args As String()) Console.WriteLine("Hello, world") End Sub End Class </text>.Value Dim hello = Temp.CreateFile().WriteAllText(helloWorldVB).Path Dim errorLogDir = Temp.CreateDirectory() Dim errorLogFile = Path.Combine(errorLogDir.Path, "ErrorLog.txt") Dim arguments = { "/nologo", $"/errorlog:{errorLogFile}{ErrorLogQualifier}", hello } Dim cmd = New MockVisualBasicCompiler(Nothing, _baseDirectory, arguments) Dim outWriter = New StringWriter(CultureInfo.InvariantCulture) Dim exitCode = cmd.Run(outWriter, Nothing) Assert.Equal("", outWriter.ToString().Trim()) Assert.Equal(0, exitCode) Dim actualOutput = File.ReadAllText(errorLogFile).Trim() Dim expectedOutput = GetExpectedOutputForNoDiagnostics(cmd) Assert.Equal(expectedOutput, actualOutput) CleanupAllGeneratedFiles(hello) CleanupAllGeneratedFiles(errorLogFile) End Sub Protected Sub SimpleCompilerDiagnosticsImpl() Dim source As String = <text> Public Class C Public Sub Method() Dim x As Integer End Sub End Class </text>.Value Dim sourceFilePath = Temp.CreateFile().WriteAllText(source).Path Dim errorLogDir = Temp.CreateDirectory() Dim errorLogFile = Path.Combine(errorLogDir.Path, "ErrorLog.txt") Dim arguments = { "/nologo", "/preferreduilang:en", $"/errorlog:{errorLogFile}{ErrorLogQualifier}", sourceFilePath } Dim cmd = New MockVisualBasicCompiler(Nothing, _baseDirectory, arguments) Dim outWriter = New StringWriter(CultureInfo.InvariantCulture) Dim exitCode = cmd.Run(outWriter, Nothing) Dim actualConsoleOutput = outWriter.ToString().Trim() Assert.Contains("BC42024", actualConsoleOutput) Assert.Contains("BC30420", actualConsoleOutput) Assert.NotEqual(0, exitCode) Dim actualOutput = File.ReadAllText(errorLogFile).Trim() Dim expectedOutput = GetExpectedOutputForSimpleCompilerDiagnostics(cmd, sourceFilePath) Assert.Equal(expectedOutput, actualOutput) CleanupAllGeneratedFiles(sourceFilePath) CleanupAllGeneratedFiles(errorLogFile) End Sub Protected Sub SimpleCompilerDiagnosticsSuppressedImpl() Dim source As String = <text> Public Class C Public Sub Method() #Disable Warning BC42024 Dim x As Integer #Enable Warning BC42024 End Sub End Class </text>.Value Dim sourceFilePath = Temp.CreateFile().WriteAllText(source).Path Dim errorLogDir = Temp.CreateDirectory() Dim errorLogFile = Path.Combine(errorLogDir.Path, "ErrorLog.txt") Dim arguments = { "/nologo", "/preferreduilang:en", $"/errorlog:{errorLogFile}{ErrorLogQualifier}", sourceFilePath } Dim cmd = New MockVisualBasicCompiler(Nothing, _baseDirectory, arguments) Dim outWriter = New StringWriter(CultureInfo.InvariantCulture) Dim exitCode = cmd.Run(outWriter, Nothing) Dim actualConsoleOutput = outWriter.ToString().Trim() ' Suppressed diagnostics are only reported in the error log, not the console output. Assert.DoesNotContain("BC42024", actualConsoleOutput) Assert.Contains("BC30420", actualConsoleOutput) Assert.NotEqual(0, exitCode) Dim actualOutput = File.ReadAllText(errorLogFile).Trim() Dim expectedOutput = GetExpectedOutputForSimpleCompilerDiagnosticsSuppressed(cmd, sourceFilePath) Assert.Equal(expectedOutput, actualOutput) CleanupAllGeneratedFiles(sourceFilePath) CleanupAllGeneratedFiles(errorLogFile) End Sub Protected Sub AnalyzerDiagnosticsWithAndWithoutLocationImpl() Dim source As String = <text> Imports System Class C End Class </text>.Value Dim sourceFilePath = Temp.CreateFile().WriteAllText(source).Path Dim outputDir = Temp.CreateDirectory() Dim errorLogFile = Path.Combine(outputDir.Path, "ErrorLog.txt") Dim outputFilePath = Path.Combine(outputDir.Path, "test.dll") Dim arguments = { "/nologo", "/preferreduilang:en", "/t:library", $"/out:{outputFilePath}", $"/errorlog:{errorLogFile}{ErrorLogQualifier}", sourceFilePath } Dim cmd = New MockVisualBasicCompiler(Nothing, _baseDirectory, arguments, analyzer:=New AnalyzerForErrorLogTest()) Dim outWriter = New StringWriter(CultureInfo.InvariantCulture) Dim exitCode = cmd.Run(outWriter, Nothing) Dim actualConsoleOutput = outWriter.ToString().Trim() Assert.Contains(AnalyzerForErrorLogTest.Descriptor1.Id, actualConsoleOutput) Assert.Contains(AnalyzerForErrorLogTest.Descriptor2.Id, actualConsoleOutput) Assert.NotEqual(0, exitCode) Dim actualOutput = File.ReadAllText(errorLogFile).Trim() Dim expectedOutput = GetExpectedOutputForAnalyzerDiagnosticsWithAndWithoutLocation(cmd) Assert.Equal(expectedOutput, actualOutput) CleanupAllGeneratedFiles(sourceFilePath) CleanupAllGeneratedFiles(outputFilePath) CleanupAllGeneratedFiles(errorLogFile) End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Globalization Imports System.IO Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests Imports Xunit Imports Microsoft.CodeAnalysis.CommonDiagnosticAnalyzers Imports Roslyn.Test.Utilities.SharedResourceHelpers Namespace Microsoft.CodeAnalysis.VisualBasic.CommandLine.UnitTests Public MustInherit Class SarifErrorLoggerTests Inherits BasicTestBase Private ReadOnly _baseDirectory As String = TempRoot.Root Protected MustOverride ReadOnly Property ErrorLogQualifier As String Friend MustOverride Function GetExpectedOutputForNoDiagnostics( cmd As CommonCompiler) As String Friend MustOverride Function GetExpectedOutputForSimpleCompilerDiagnostics( cmd As CommonCompiler, sourceFilePath As String) As String Friend MustOverride Function GetExpectedOutputForSimpleCompilerDiagnosticsSuppressed( cmd As CommonCompiler, sourceFilePath As String) As String Friend MustOverride Function GetExpectedOutputForAnalyzerDiagnosticsWithAndWithoutLocation( cmd As MockVisualBasicCompiler) As String Protected Sub NoDiagnosticsImpl() Dim helloWorldVB As String = <text> Imports System Class C Shared Sub Main(args As String()) Console.WriteLine("Hello, world") End Sub End Class </text>.Value Dim hello = Temp.CreateFile().WriteAllText(helloWorldVB).Path Dim errorLogDir = Temp.CreateDirectory() Dim errorLogFile = Path.Combine(errorLogDir.Path, "ErrorLog.txt") Dim arguments = { "/nologo", $"/errorlog:{errorLogFile}{ErrorLogQualifier}", hello } Dim cmd = New MockVisualBasicCompiler(Nothing, _baseDirectory, arguments) Dim outWriter = New StringWriter(CultureInfo.InvariantCulture) Dim exitCode = cmd.Run(outWriter, Nothing) Assert.Equal("", outWriter.ToString().Trim()) Assert.Equal(0, exitCode) Dim actualOutput = File.ReadAllText(errorLogFile).Trim() Dim expectedOutput = GetExpectedOutputForNoDiagnostics(cmd) Assert.Equal(expectedOutput, actualOutput) CleanupAllGeneratedFiles(hello) CleanupAllGeneratedFiles(errorLogFile) End Sub Protected Sub SimpleCompilerDiagnosticsImpl() Dim source As String = <text> Public Class C Public Sub Method() Dim x As Integer End Sub End Class </text>.Value Dim sourceFilePath = Temp.CreateFile().WriteAllText(source).Path Dim errorLogDir = Temp.CreateDirectory() Dim errorLogFile = Path.Combine(errorLogDir.Path, "ErrorLog.txt") Dim arguments = { "/nologo", "/preferreduilang:en", $"/errorlog:{errorLogFile}{ErrorLogQualifier}", sourceFilePath } Dim cmd = New MockVisualBasicCompiler(Nothing, _baseDirectory, arguments) Dim outWriter = New StringWriter(CultureInfo.InvariantCulture) Dim exitCode = cmd.Run(outWriter, Nothing) Dim actualConsoleOutput = outWriter.ToString().Trim() Assert.Contains("BC42024", actualConsoleOutput) Assert.Contains("BC30420", actualConsoleOutput) Assert.NotEqual(0, exitCode) Dim actualOutput = File.ReadAllText(errorLogFile).Trim() Dim expectedOutput = GetExpectedOutputForSimpleCompilerDiagnostics(cmd, sourceFilePath) Assert.Equal(expectedOutput, actualOutput) CleanupAllGeneratedFiles(sourceFilePath) CleanupAllGeneratedFiles(errorLogFile) End Sub Protected Sub SimpleCompilerDiagnosticsSuppressedImpl() Dim source As String = <text> Public Class C Public Sub Method() #Disable Warning BC42024 Dim x As Integer #Enable Warning BC42024 End Sub End Class </text>.Value Dim sourceFilePath = Temp.CreateFile().WriteAllText(source).Path Dim errorLogDir = Temp.CreateDirectory() Dim errorLogFile = Path.Combine(errorLogDir.Path, "ErrorLog.txt") Dim arguments = { "/nologo", "/preferreduilang:en", $"/errorlog:{errorLogFile}{ErrorLogQualifier}", sourceFilePath } Dim cmd = New MockVisualBasicCompiler(Nothing, _baseDirectory, arguments) Dim outWriter = New StringWriter(CultureInfo.InvariantCulture) Dim exitCode = cmd.Run(outWriter, Nothing) Dim actualConsoleOutput = outWriter.ToString().Trim() ' Suppressed diagnostics are only reported in the error log, not the console output. Assert.DoesNotContain("BC42024", actualConsoleOutput) Assert.Contains("BC30420", actualConsoleOutput) Assert.NotEqual(0, exitCode) Dim actualOutput = File.ReadAllText(errorLogFile).Trim() Dim expectedOutput = GetExpectedOutputForSimpleCompilerDiagnosticsSuppressed(cmd, sourceFilePath) Assert.Equal(expectedOutput, actualOutput) CleanupAllGeneratedFiles(sourceFilePath) CleanupAllGeneratedFiles(errorLogFile) End Sub Protected Sub AnalyzerDiagnosticsWithAndWithoutLocationImpl() Dim source As String = <text> Imports System Class C End Class </text>.Value Dim sourceFilePath = Temp.CreateFile().WriteAllText(source).Path Dim outputDir = Temp.CreateDirectory() Dim errorLogFile = Path.Combine(outputDir.Path, "ErrorLog.txt") Dim outputFilePath = Path.Combine(outputDir.Path, "test.dll") Dim arguments = { "/nologo", "/preferreduilang:en", "/t:library", $"/out:{outputFilePath}", $"/errorlog:{errorLogFile}{ErrorLogQualifier}", sourceFilePath } Dim cmd = New MockVisualBasicCompiler(Nothing, _baseDirectory, arguments, analyzer:=New AnalyzerForErrorLogTest()) Dim outWriter = New StringWriter(CultureInfo.InvariantCulture) Dim exitCode = cmd.Run(outWriter, Nothing) Dim actualConsoleOutput = outWriter.ToString().Trim() Assert.Contains(AnalyzerForErrorLogTest.Descriptor1.Id, actualConsoleOutput) Assert.Contains(AnalyzerForErrorLogTest.Descriptor2.Id, actualConsoleOutput) Assert.NotEqual(0, exitCode) Dim actualOutput = File.ReadAllText(errorLogFile).Trim() Dim expectedOutput = GetExpectedOutputForAnalyzerDiagnosticsWithAndWithoutLocation(cmd) Assert.Equal(expectedOutput, actualOutput) CleanupAllGeneratedFiles(sourceFilePath) CleanupAllGeneratedFiles(outputFilePath) CleanupAllGeneratedFiles(errorLogFile) End Sub End Class End Namespace
-1
dotnet/roslyn
56,011
React to string comparison changing on .NET Core
The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
jaredpar
"2021-08-30T17:18:52Z"
"2021-08-30T20:20:04Z"
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
4d99cda6e446e77dbb302e26388c1093bd3ef569
React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
./src/Compilers/VisualBasic/Portable/Preprocessor/CConst.vb
' 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.VisualBasic.Syntax.InternalSyntax ''' <summary> ''' Base class of a compile time constant. ''' </summary> Friend MustInherit Class CConst Protected ReadOnly _errid As ERRID Protected ReadOnly _diagnosticArguments As Object() Public Sub New() End Sub Public Sub New(id As ERRID, ParamArray diagnosticArguments As Object()) DiagnosticInfo.AssertMessageSerializable(diagnosticArguments) _errid = id _diagnosticArguments = diagnosticArguments End Sub Public MustOverride ReadOnly Property SpecialType As SpecialType Public MustOverride ReadOnly Property ValueAsObject As Object Public MustOverride Function WithError(id As ERRID) As CConst Friend Shared Function CreateChecked(value As Object) As CConst Dim constant = TryCreate(value) Debug.Assert(constant IsNot Nothing) Return constant End Function Friend Shared Function TryCreate(value As Object) As CConst If value Is Nothing Then Return CreateNothing() End If Dim specialType = SpecialTypeExtensions.FromRuntimeTypeOfLiteralValue(value) Select Case specialType Case SpecialType.System_Boolean Return Create(Convert.ToBoolean(value)) Case SpecialType.System_Byte Return Create(Convert.ToByte(value)) Case SpecialType.System_Char Return Create(Convert.ToChar(value)) Case SpecialType.System_DateTime Return Create(Convert.ToDateTime(value)) Case SpecialType.System_Decimal Return Create(Convert.ToDecimal(value)) Case SpecialType.System_Double Return Create(Convert.ToDouble(value)) Case SpecialType.System_Int16 Return Create(Convert.ToInt16(value)) Case SpecialType.System_Int32 Return Create(Convert.ToInt32(value)) Case SpecialType.System_Int64 Return Create(Convert.ToInt64(value)) Case SpecialType.System_SByte Return Create(Convert.ToSByte(value)) Case SpecialType.System_Single Return Create(Convert.ToSingle(value)) Case SpecialType.System_String Return Create(Convert.ToString(value)) Case SpecialType.System_UInt16 Return Create(Convert.ToUInt16(value)) Case SpecialType.System_UInt32 Return Create(Convert.ToUInt32(value)) Case SpecialType.System_UInt64 Return Create(Convert.ToUInt64(value)) Case Else Return Nothing End Select End Function Friend Shared Function CreateNothing() As CConst(Of Object) Return New CConst(Of Object)(Nothing, SpecialType.System_Object) End Function Friend Shared Function Create(value As Boolean) As CConst(Of Boolean) Return New CConst(Of Boolean)(value, SpecialType.System_Boolean) End Function Friend Shared Function Create(value As Byte) As CConst(Of Byte) Return New CConst(Of Byte)(value, SpecialType.System_Byte) End Function Friend Shared Function Create(value As SByte) As CConst(Of SByte) Return New CConst(Of SByte)(value, SpecialType.System_SByte) End Function Friend Shared Function Create(value As Char) As CConst(Of Char) Return New CConst(Of Char)(value, SpecialType.System_Char) End Function Friend Shared Function Create(value As Short) As CConst(Of Short) Return New CConst(Of Short)(value, SpecialType.System_Int16) End Function Friend Shared Function Create(value As UShort) As CConst(Of UShort) Return New CConst(Of UShort)(value, SpecialType.System_UInt16) End Function Friend Shared Function Create(value As Integer) As CConst(Of Integer) Return New CConst(Of Integer)(value, SpecialType.System_Int32) End Function Friend Shared Function Create(value As UInteger) As CConst(Of UInteger) Return New CConst(Of UInteger)(value, SpecialType.System_UInt32) End Function Friend Shared Function Create(value As Long) As CConst(Of Long) Return New CConst(Of Long)(value, SpecialType.System_Int64) End Function Friend Shared Function Create(value As ULong) As CConst(Of ULong) Return New CConst(Of ULong)(value, SpecialType.System_UInt64) End Function Friend Shared Function Create(value As Decimal) As CConst(Of Decimal) Return New CConst(Of Decimal)(value, SpecialType.System_Decimal) End Function Friend Shared Function Create(value As String) As CConst(Of String) Return New CConst(Of String)(value, SpecialType.System_String) End Function Friend Shared Function Create(value As Single) As CConst(Of Single) Return New CConst(Of Single)(value, SpecialType.System_Single) End Function Friend Shared Function Create(value As Double) As CConst(Of Double) Return New CConst(Of Double)(value, SpecialType.System_Double) End Function Friend Shared Function Create(value As Date) As CConst(Of Date) Return New CConst(Of Date)(value, SpecialType.System_DateTime) End Function Public ReadOnly Property IsBad As Boolean Get Return SpecialType = SpecialType.None End Get End Property Public ReadOnly Property IsBooleanTrue As Boolean Get If IsBad Then Return False End If Dim boolValue = TryCast(Me, CConst(Of Boolean)) If boolValue IsNot Nothing Then Return boolValue.Value End If Return False End Get End Property Public ReadOnly Property ErrorId As ERRID Get Return _errid End Get End Property Public ReadOnly Property ErrorArgs As Object() Get Return If(_diagnosticArguments, Array.Empty(Of Object)) End Get End Property End Class ''' <summary> ''' Represents a compile time constant. ''' </summary> Friend Class CConst(Of T) Inherits CConst Private ReadOnly _specialType As SpecialType Private ReadOnly _value As T Friend Sub New(value As T, specialType As SpecialType) _value = value _specialType = specialType End Sub Private Sub New(value As T, specialType As SpecialType, id As ERRID) MyBase.New(id) _value = value _specialType = specialType End Sub Public Overrides ReadOnly Property SpecialType As SpecialType Get Return _specialType End Get End Property Public Overrides ReadOnly Property ValueAsObject As Object Get Return _value End Get End Property Public ReadOnly Property Value As T Get Return _value End Get End Property Public Overrides Function WithError(id As ERRID) As CConst Return New CConst(Of T)(_value, _specialType, id) End Function End Class Friend Class BadCConst Inherits CConst Public Sub New(id As ERRID) MyBase.New(id) End Sub Public Sub New(id As ERRID, ParamArray args As Object()) MyBase.New(id, args) End Sub Public Overrides ReadOnly Property SpecialType As SpecialType Get Return SpecialType.None End Get End Property Public Overrides ReadOnly Property ValueAsObject As Object Get Return Nothing End Get End Property Public Overrides Function WithError(id As ERRID) As CConst ' TODO: we support only one error for now. Throw ExceptionUtilities.Unreachable End Function End Class End Namespace
' 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.VisualBasic.Syntax.InternalSyntax ''' <summary> ''' Base class of a compile time constant. ''' </summary> Friend MustInherit Class CConst Protected ReadOnly _errid As ERRID Protected ReadOnly _diagnosticArguments As Object() Public Sub New() End Sub Public Sub New(id As ERRID, ParamArray diagnosticArguments As Object()) DiagnosticInfo.AssertMessageSerializable(diagnosticArguments) _errid = id _diagnosticArguments = diagnosticArguments End Sub Public MustOverride ReadOnly Property SpecialType As SpecialType Public MustOverride ReadOnly Property ValueAsObject As Object Public MustOverride Function WithError(id As ERRID) As CConst Friend Shared Function CreateChecked(value As Object) As CConst Dim constant = TryCreate(value) Debug.Assert(constant IsNot Nothing) Return constant End Function Friend Shared Function TryCreate(value As Object) As CConst If value Is Nothing Then Return CreateNothing() End If Dim specialType = SpecialTypeExtensions.FromRuntimeTypeOfLiteralValue(value) Select Case specialType Case SpecialType.System_Boolean Return Create(Convert.ToBoolean(value)) Case SpecialType.System_Byte Return Create(Convert.ToByte(value)) Case SpecialType.System_Char Return Create(Convert.ToChar(value)) Case SpecialType.System_DateTime Return Create(Convert.ToDateTime(value)) Case SpecialType.System_Decimal Return Create(Convert.ToDecimal(value)) Case SpecialType.System_Double Return Create(Convert.ToDouble(value)) Case SpecialType.System_Int16 Return Create(Convert.ToInt16(value)) Case SpecialType.System_Int32 Return Create(Convert.ToInt32(value)) Case SpecialType.System_Int64 Return Create(Convert.ToInt64(value)) Case SpecialType.System_SByte Return Create(Convert.ToSByte(value)) Case SpecialType.System_Single Return Create(Convert.ToSingle(value)) Case SpecialType.System_String Return Create(Convert.ToString(value)) Case SpecialType.System_UInt16 Return Create(Convert.ToUInt16(value)) Case SpecialType.System_UInt32 Return Create(Convert.ToUInt32(value)) Case SpecialType.System_UInt64 Return Create(Convert.ToUInt64(value)) Case Else Return Nothing End Select End Function Friend Shared Function CreateNothing() As CConst(Of Object) Return New CConst(Of Object)(Nothing, SpecialType.System_Object) End Function Friend Shared Function Create(value As Boolean) As CConst(Of Boolean) Return New CConst(Of Boolean)(value, SpecialType.System_Boolean) End Function Friend Shared Function Create(value As Byte) As CConst(Of Byte) Return New CConst(Of Byte)(value, SpecialType.System_Byte) End Function Friend Shared Function Create(value As SByte) As CConst(Of SByte) Return New CConst(Of SByte)(value, SpecialType.System_SByte) End Function Friend Shared Function Create(value As Char) As CConst(Of Char) Return New CConst(Of Char)(value, SpecialType.System_Char) End Function Friend Shared Function Create(value As Short) As CConst(Of Short) Return New CConst(Of Short)(value, SpecialType.System_Int16) End Function Friend Shared Function Create(value As UShort) As CConst(Of UShort) Return New CConst(Of UShort)(value, SpecialType.System_UInt16) End Function Friend Shared Function Create(value As Integer) As CConst(Of Integer) Return New CConst(Of Integer)(value, SpecialType.System_Int32) End Function Friend Shared Function Create(value As UInteger) As CConst(Of UInteger) Return New CConst(Of UInteger)(value, SpecialType.System_UInt32) End Function Friend Shared Function Create(value As Long) As CConst(Of Long) Return New CConst(Of Long)(value, SpecialType.System_Int64) End Function Friend Shared Function Create(value As ULong) As CConst(Of ULong) Return New CConst(Of ULong)(value, SpecialType.System_UInt64) End Function Friend Shared Function Create(value As Decimal) As CConst(Of Decimal) Return New CConst(Of Decimal)(value, SpecialType.System_Decimal) End Function Friend Shared Function Create(value As String) As CConst(Of String) Return New CConst(Of String)(value, SpecialType.System_String) End Function Friend Shared Function Create(value As Single) As CConst(Of Single) Return New CConst(Of Single)(value, SpecialType.System_Single) End Function Friend Shared Function Create(value As Double) As CConst(Of Double) Return New CConst(Of Double)(value, SpecialType.System_Double) End Function Friend Shared Function Create(value As Date) As CConst(Of Date) Return New CConst(Of Date)(value, SpecialType.System_DateTime) End Function Public ReadOnly Property IsBad As Boolean Get Return SpecialType = SpecialType.None End Get End Property Public ReadOnly Property IsBooleanTrue As Boolean Get If IsBad Then Return False End If Dim boolValue = TryCast(Me, CConst(Of Boolean)) If boolValue IsNot Nothing Then Return boolValue.Value End If Return False End Get End Property Public ReadOnly Property ErrorId As ERRID Get Return _errid End Get End Property Public ReadOnly Property ErrorArgs As Object() Get Return If(_diagnosticArguments, Array.Empty(Of Object)) End Get End Property End Class ''' <summary> ''' Represents a compile time constant. ''' </summary> Friend Class CConst(Of T) Inherits CConst Private ReadOnly _specialType As SpecialType Private ReadOnly _value As T Friend Sub New(value As T, specialType As SpecialType) _value = value _specialType = specialType End Sub Private Sub New(value As T, specialType As SpecialType, id As ERRID) MyBase.New(id) _value = value _specialType = specialType End Sub Public Overrides ReadOnly Property SpecialType As SpecialType Get Return _specialType End Get End Property Public Overrides ReadOnly Property ValueAsObject As Object Get Return _value End Get End Property Public ReadOnly Property Value As T Get Return _value End Get End Property Public Overrides Function WithError(id As ERRID) As CConst Return New CConst(Of T)(_value, _specialType, id) End Function End Class Friend Class BadCConst Inherits CConst Public Sub New(id As ERRID) MyBase.New(id) End Sub Public Sub New(id As ERRID, ParamArray args As Object()) MyBase.New(id, args) End Sub Public Overrides ReadOnly Property SpecialType As SpecialType Get Return SpecialType.None End Get End Property Public Overrides ReadOnly Property ValueAsObject As Object Get Return Nothing End Get End Property Public Overrides Function WithError(id As ERRID) As CConst ' TODO: we support only one error for now. Throw ExceptionUtilities.Unreachable End Function End Class End Namespace
-1
dotnet/roslyn
56,011
React to string comparison changing on .NET Core
The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
jaredpar
"2021-08-30T17:18:52Z"
"2021-08-30T20:20:04Z"
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
4d99cda6e446e77dbb302e26388c1093bd3ef569
React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
./src/Features/VisualBasic/Portable/CodeFixes/IncorrectExitContinue/IncorrectExitContinueCodeFixProvider.AddKeywordCodeAction.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.CodeFixes.IncorrectExitContinue Partial Friend Class IncorrectExitContinueCodeFixProvider Private Class AddKeywordCodeAction Inherits CodeAction Private ReadOnly _node As SyntaxNode Private ReadOnly _containingBlock As SyntaxNode Private ReadOnly _document As Document Private ReadOnly _updateNode As Func(Of SyntaxNode, SyntaxNode, SyntaxKind, Document, CancellationToken, StatementSyntax) Private ReadOnly _createBlockKind As SyntaxKind Public Sub New(node As SyntaxNode, createBlockKind As SyntaxKind, containingBlock As SyntaxNode, document As Microsoft.CodeAnalysis.Document, updateNode As Func(Of SyntaxNode, SyntaxNode, SyntaxKind, Document, CancellationToken, StatementSyntax)) Me._node = node Me._createBlockKind = createBlockKind Me._containingBlock = containingBlock Me._document = document Me._updateNode = updateNode End Sub Public Overrides ReadOnly Property Title As String Get Return String.Format(VBFeaturesResources.Insert_0, SyntaxFacts.GetText(BlockKindToKeywordKind(_createBlockKind))) End Get End Property Protected Overrides Async Function GetChangedDocumentAsync(cancellationToken As CancellationToken) As Task(Of Document) Dim updatedStatement = _updateNode(_node, _containingBlock, _createBlockKind, _document, cancellationToken) Dim root = Await _document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(False) Dim updatedRoot = root.ReplaceNode(_node, updatedStatement) Return _document.WithSyntaxRoot(updatedRoot) End Function End Class End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.CodeFixes.IncorrectExitContinue Partial Friend Class IncorrectExitContinueCodeFixProvider Private Class AddKeywordCodeAction Inherits CodeAction Private ReadOnly _node As SyntaxNode Private ReadOnly _containingBlock As SyntaxNode Private ReadOnly _document As Document Private ReadOnly _updateNode As Func(Of SyntaxNode, SyntaxNode, SyntaxKind, Document, CancellationToken, StatementSyntax) Private ReadOnly _createBlockKind As SyntaxKind Public Sub New(node As SyntaxNode, createBlockKind As SyntaxKind, containingBlock As SyntaxNode, document As Microsoft.CodeAnalysis.Document, updateNode As Func(Of SyntaxNode, SyntaxNode, SyntaxKind, Document, CancellationToken, StatementSyntax)) Me._node = node Me._createBlockKind = createBlockKind Me._containingBlock = containingBlock Me._document = document Me._updateNode = updateNode End Sub Public Overrides ReadOnly Property Title As String Get Return String.Format(VBFeaturesResources.Insert_0, SyntaxFacts.GetText(BlockKindToKeywordKind(_createBlockKind))) End Get End Property Protected Overrides Async Function GetChangedDocumentAsync(cancellationToken As CancellationToken) As Task(Of Document) Dim updatedStatement = _updateNode(_node, _containingBlock, _createBlockKind, _document, cancellationToken) Dim root = Await _document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(False) Dim updatedRoot = root.ReplaceNode(_node, updatedStatement) Return _document.WithSyntaxRoot(updatedRoot) End Function End Class End Class End Namespace
-1
dotnet/roslyn
56,011
React to string comparison changing on .NET Core
The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
jaredpar
"2021-08-30T17:18:52Z"
"2021-08-30T20:20:04Z"
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
4d99cda6e446e77dbb302e26388c1093bd3ef569
React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
./src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/Symbols/DisplayClassInstance.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Roslyn.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator Friend MustInherit Class DisplayClassInstance Friend MustOverride ReadOnly Property ContainingSymbol As Symbol Friend MustOverride ReadOnly Property Type As TypeSymbol Friend MustOverride Function ToOtherMethod(method As MethodSymbol, typeMap As TypeSubstitution) As DisplayClassInstance Friend MustOverride Function ToBoundExpression(syntax As SyntaxNode) As BoundExpression Friend Function GetDebuggerDisplay(fields As ConsList(Of FieldSymbol)) As String Return GetDebuggerDisplay(GetInstanceName(), fields) End Function Private Shared Function GetDebuggerDisplay(expr As String, fields As ConsList(Of FieldSymbol)) As String Return If(fields.Any(), $"{GetDebuggerDisplay(expr, fields.Tail)}.{fields.Head.Name}", expr) End Function Protected MustOverride Function GetInstanceName() As String End Class Friend NotInheritable Class DisplayClassInstanceFromLocal Inherits DisplayClassInstance Friend ReadOnly Local As EELocalSymbol Friend Sub New(local As EELocalSymbol) Debug.Assert(Not local.IsByRef) Debug.Assert(local.DeclarationKind = LocalDeclarationKind.Variable) Me.Local = local End Sub Friend Overrides ReadOnly Property ContainingSymbol As Symbol Get Return Me.Local.ContainingSymbol End Get End Property Friend Overrides ReadOnly Property Type As TypeSymbol Get Return Me.Local.Type End Get End Property Friend Overrides Function ToOtherMethod(method As MethodSymbol, typeMap As TypeSubstitution) As DisplayClassInstance Dim otherInstance = DirectCast(Me.Local.ToOtherMethod(method, typeMap), EELocalSymbol) Return New DisplayClassInstanceFromLocal(otherInstance) End Function Friend Overrides Function ToBoundExpression(syntax As SyntaxNode) As BoundExpression Return New BoundLocal(syntax, Me.Local, Me.Local.Type).MakeCompilerGenerated() End Function Protected Overrides Function GetInstanceName() As String Return Local.Name End Function End Class Friend NotInheritable Class DisplayClassInstanceFromParameter Inherits DisplayClassInstance Friend ReadOnly Parameter As ParameterSymbol Friend Sub New(parameter As ParameterSymbol) Debug.Assert(parameter IsNot Nothing) Debug.Assert(parameter.Name.Equals("Me", StringComparison.Ordinal) OrElse parameter.Name.IndexOf("$Me", StringComparison.Ordinal) >= 0 OrElse parameter.Name.IndexOf("$It", StringComparison.Ordinal) >= 0) Me.Parameter = parameter End Sub Friend Overrides ReadOnly Property ContainingSymbol As Symbol Get Return Me.Parameter.ContainingSymbol End Get End Property Friend Overrides ReadOnly Property Type As TypeSymbol Get Return Me.Parameter.Type End Get End Property Friend Overrides Function ToOtherMethod(method As MethodSymbol, typeMap As TypeSubstitution) As DisplayClassInstance Debug.Assert(method.IsShared) Dim otherOrdinal = If(Me.ContainingSymbol.IsShared, Me.Parameter.Ordinal, Me.Parameter.Ordinal + 1) Dim otherParameter = method.Parameters(otherOrdinal) Return New DisplayClassInstanceFromParameter(otherParameter) End Function Friend Overrides Function ToBoundExpression(syntax As SyntaxNode) As BoundExpression Return New BoundParameter(syntax, Me.Parameter, Me.Parameter.Type).MakeCompilerGenerated() End Function Protected Overrides Function GetInstanceName() As String Return Parameter.Name End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Roslyn.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator Friend MustInherit Class DisplayClassInstance Friend MustOverride ReadOnly Property ContainingSymbol As Symbol Friend MustOverride ReadOnly Property Type As TypeSymbol Friend MustOverride Function ToOtherMethod(method As MethodSymbol, typeMap As TypeSubstitution) As DisplayClassInstance Friend MustOverride Function ToBoundExpression(syntax As SyntaxNode) As BoundExpression Friend Function GetDebuggerDisplay(fields As ConsList(Of FieldSymbol)) As String Return GetDebuggerDisplay(GetInstanceName(), fields) End Function Private Shared Function GetDebuggerDisplay(expr As String, fields As ConsList(Of FieldSymbol)) As String Return If(fields.Any(), $"{GetDebuggerDisplay(expr, fields.Tail)}.{fields.Head.Name}", expr) End Function Protected MustOverride Function GetInstanceName() As String End Class Friend NotInheritable Class DisplayClassInstanceFromLocal Inherits DisplayClassInstance Friend ReadOnly Local As EELocalSymbol Friend Sub New(local As EELocalSymbol) Debug.Assert(Not local.IsByRef) Debug.Assert(local.DeclarationKind = LocalDeclarationKind.Variable) Me.Local = local End Sub Friend Overrides ReadOnly Property ContainingSymbol As Symbol Get Return Me.Local.ContainingSymbol End Get End Property Friend Overrides ReadOnly Property Type As TypeSymbol Get Return Me.Local.Type End Get End Property Friend Overrides Function ToOtherMethod(method As MethodSymbol, typeMap As TypeSubstitution) As DisplayClassInstance Dim otherInstance = DirectCast(Me.Local.ToOtherMethod(method, typeMap), EELocalSymbol) Return New DisplayClassInstanceFromLocal(otherInstance) End Function Friend Overrides Function ToBoundExpression(syntax As SyntaxNode) As BoundExpression Return New BoundLocal(syntax, Me.Local, Me.Local.Type).MakeCompilerGenerated() End Function Protected Overrides Function GetInstanceName() As String Return Local.Name End Function End Class Friend NotInheritable Class DisplayClassInstanceFromParameter Inherits DisplayClassInstance Friend ReadOnly Parameter As ParameterSymbol Friend Sub New(parameter As ParameterSymbol) Debug.Assert(parameter IsNot Nothing) Debug.Assert(parameter.Name.Equals("Me", StringComparison.Ordinal) OrElse parameter.Name.IndexOf("$Me", StringComparison.Ordinal) >= 0 OrElse parameter.Name.IndexOf("$It", StringComparison.Ordinal) >= 0) Me.Parameter = parameter End Sub Friend Overrides ReadOnly Property ContainingSymbol As Symbol Get Return Me.Parameter.ContainingSymbol End Get End Property Friend Overrides ReadOnly Property Type As TypeSymbol Get Return Me.Parameter.Type End Get End Property Friend Overrides Function ToOtherMethod(method As MethodSymbol, typeMap As TypeSubstitution) As DisplayClassInstance Debug.Assert(method.IsShared) Dim otherOrdinal = If(Me.ContainingSymbol.IsShared, Me.Parameter.Ordinal, Me.Parameter.Ordinal + 1) Dim otherParameter = method.Parameters(otherOrdinal) Return New DisplayClassInstanceFromParameter(otherParameter) End Function Friend Overrides Function ToBoundExpression(syntax As SyntaxNode) As BoundExpression Return New BoundParameter(syntax, Me.Parameter, Me.Parameter.Type).MakeCompilerGenerated() End Function Protected Overrides Function GetInstanceName() As String Return Parameter.Name End Function End Class End Namespace
-1
dotnet/roslyn
56,011
React to string comparison changing on .NET Core
The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
jaredpar
"2021-08-30T17:18:52Z"
"2021-08-30T20:20:04Z"
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
4d99cda6e446e77dbb302e26388c1093bd3ef569
React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
./src/EditorFeatures/Test2/FindReferences/FindReferencesTests.AsyncSymbols.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.Remote.Testing Namespace Microsoft.CodeAnalysis.Editor.UnitTests.FindReferences Partial Public Class FindReferencesTests <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSAsyncMethodsName1(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Test { void TestFunction() { [|OneAsync|](); } async void TestFunctionAsync() { await [|OneAsync|](); } async Task {|Definition:$$OneAsync|}() { return; } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestVBAsyncMethodsName1(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Test Sub TestSub() [|OneAsync|]() End Sub Async Sub TestSubAsync() Await [|OneAsync|]() End Sub Async Function {|Definition:$$OneAsync|}() As Task Return End Function End Class </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSAsyncMethodsName2(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ class Test { void TestFunction() { [|TwoAsync|](); } async void TestFunctionAsync() { await [|TwoAsync|](); } async Task<int> {|Definition:$$TwoAsync|}() { return 1; } } ]]> </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestVBAsyncMethodsName2(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Test Sub TestSub() [|OneAsync|]() End Sub Async Sub TestSubAsync() Await [|OneAsync|]() End Sub Async Function {|Definition:$$OneAsync|}() As Task(Of Integer) Return 1 End Function End Class </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSAsyncMethodsName3(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Test { void TestFunction() { [|ThreeAsync|](); } async void TestFunctionAsync() { [|ThreeAsync|](); } async void {|Definition:$$ThreeAsync|}() { } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestVBAsyncMethodsName3(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Test Sub TestSub() [|OneAsync|]() End Sub Async Sub TestSubAsync() Await [|OneAsync|]() End Sub Async Sub {|Definition:$$OneAsync|}() 'do nothing End Sub End Class </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSAsyncDelegatesName1(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ class Test { Func<Task> {|Definition:$$a1|} = async delegate { return; }; void TestFunction() { [|a1|](); } async Task TestFunctionAsync() { await [|a1|](); } } ]]> </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestVBAsyncDelegatesName1(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Test Dim {|Definition:$$a1|} As Func(Of Task) = Async Function() Return End Function Sub TestFunction() [|a1|]() End Sub Async Function TestFunctionAsync() As Task Await [|a1|]() End Function End Class </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSAsyncDelegatesName2(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ class Test { Action<Task> {|Definition:$$a1|} = async delegate (Task t) { await t; }; void TestFunction() { Task t; [|a1|](t); } async Task TestFunctionAsync() { Task t; [|a1|](t); } } ]]> </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestVBAsyncDelegatesName2(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Test Dim {|Definition:$$a1|} As Action(Of Task) = Async Sub(ByVal t As Task) Await t End Sub Sub TestFunction() Dim t As Task [|a1|](t) End Sub Async Function TestFunctionAsync() As Task Dim t As Task [|a1|](t) End Function End Class </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSAsyncLambdaName1(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ class Test { Action<Task> {|Definition:$$f1|} = async (t) => { await t; }; void TestFunction() { Task t; [|f1|](t); } async void TestFunctionAsync() { Task t; [|f1|](t); } } ]]> </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestVBAsyncLambdaName1(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Test Dim {|Definition:$$a1|} As Action(Of Task) = Async Sub(t) Await t End Sub Sub TestFunction() Dim t As Task [|a1|](t) End Sub Async Function TestFunctionAsync() As Task Dim t As Task [|a1|](t) End Function End Class </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestAsyncWithinDelegate(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ class Test { Action<Task> a1 = async delegate (Task t) { await [|$$Function|](); }; public static async Task {|Definition:Function|}() { } } class Program { delegate Task mydel(); async Task FunctionAsync() { mydel d = new mydel(Test.[|Function|]); } } ]]> </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestAsyncVBWithinAnonFunctions(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Test Dim a1 As Action(Of Task) = Async Sub(t) Await [|$$TestFunctionAsync|]() End Sub Delegate Function mydel() As Task(Of Integer) Async Function {|Definition:TestFunctionAsync|}() As Task(Of Integer) Return 1 End Function Async Sub SubAsync() Dim d As mydel = New mydel(AddressOf [|TestFunctionAsync|]) End Sub End Class </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestAsyncWithinLambda(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ class Test { Action<Task> a1 = async (Task t) => { await [|$$Function|](); }; public static async Task {|Definition:Function|}() { } } class Program { delegate Task mydel(); async Task FunctionAsync() { mydel d = new mydel(Test.[|Function|]); } } ]]> </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestAsyncFunctionWithAsyncParameters1(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ class Test { async Task CallFunctionAsync() { await [|OuterFunctionAsync|](await InnerFunctionAsync()); } async Task {|Definition:$$OuterFunctionAsync|}(int x) { return; } async Task<int> InnerFunctionAsync() { return 1; } } ]]> </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestAsyncVBFunctionWithAsyncParameters1(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Test Async Sub CallSubAsync() Await OuterFunctionAsync(Await [|$$InnerFunctionAsync|]()) End Sub Async Function OuterFunctionAsync(ByVal x As Integer) As Task Return End Function Async Function {|Definition:InnerFunctionAsync|}() As Task(Of Integer) Return 1 End Function End Class </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestAsyncVBFunctionWithAsyncParameters2(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Test Async Sub CallSubAsync() Await [|OuterFunctionAsync|](Await InnerFunctionAsync()) End Sub Async Function {|Definition:$$OuterFunctionAsync|}(ByVal x As Integer) As Task Return End Function Async Function InnerFunctionAsync() As Task(Of Integer) Return 1 End Function End Class </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestAsyncFunctionWithAsyncParameters2(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ class Test { async Task CallFunctionAsync() { await OuterFunctionAsync(await [|$$InnerFunctionAsync|]()); } async Task OuterFunctionAsync(int x) { return; } async Task<int> {|Definition:InnerFunctionAsync|}() { return 1; } } ]]> </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestAsyncFunctionWithAsyncParameters3(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ class Test { Func<Task<int>> {|Definition:$$f1|} = async delegate {return 1; }; async void CallFunctionAsync() { await OuterFunctionAsync(await [|f1|]()); } async Task OuterFunctionAsync(int x) { return; } } ]]> </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestAsyncFunctionWithAsyncParameters4(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ class Test { Func<int,Task<int>> {|Definition:f1|} = async (x) => {return 1; }; async void CallFunctionAsync() { await OuterFunctionAsync(await [|$$f1|](1)); } async Task OuterFunctionAsync(int x) { return; } } ]]> </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestAsyncCSFunctionWithRecursion(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ class Test { async Task {|Definition:$$FunctionAsync|}(int x) { if (x == 1) return; await [|FunctionAsync|](--x); } public void Function(int x) { [|FunctionAsync|](x); } } ]]> </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestAsyncCSFunctionWithOverloading1(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ using System.Threading.Tasks; class Test { async Task {|Definition:FunctionAsync|}(int x) { FunctionAsync("hello"); await FunctionAsync(await FunctionAsync<string>("hello")); } async Task FunctionAsync(string x) { [|FunctionAsync|](3); await FunctionAsync<float>(3f); await [|$$FunctionAsync|](await FunctionAsync<int>(3)); } async Task<T> FunctionAsync<T>(T x) { return x; } } ]]> </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestAsyncVBFunctionWithOverloading1(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports System Imports System.Threading.Tasks Class Test Async Function {|Definition:FunctionAsync|}(ByVal x As Integer) As Task FunctionAsync("Hello") Await FunctionAsync(Await FunctionAsync(Of String)("hello")) End Function Async Function FunctionAsync(ByVal x As String) As Task [|FunctionAsync|](3) Await FunctionAsync(Of Single)(3.5F) Await [|$$FunctionAsync|](Await FunctionAsync(Of Integer)(3)) End Function Async Function FunctionAsync(Of T)(ByVal x As T) As Task(Of T) Return x End Function End Class </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestAsyncVBFunctionWithOverloading2(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports System Imports System.Threading.Tasks Class Test Async Function FunctionAsync(ByVal x As Integer) As Task FunctionAsync("Hello") Await FunctionAsync(Await [|FunctionAsync|](Of String)("hello")) End Function Async Function FunctionAsync(ByVal x As String) As Task FunctionAsync(3) Await [|FunctionAsync|](Of Single)(3.5F) Await FunctionAsync(Await [|FunctionAsync|](Of Integer)(3)) End Function Async Function {|Definition:$$FunctionAsync|}(Of T)(ByVal x As T) As Task(Of T) Return x End Function End Class </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestAsyncCSFunctionWithOverloading2(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ using System; using System.Threading.Tasks; class Test { async Task FunctionAsync(int x) { FunctionAsync("hello"); await FunctionAsync(await [|FunctionAsync|]<string>("hello")); } async Task FunctionAsync(string x) { FunctionAsync(3); await [|FunctionAsync|]<float>(3f); await FunctionAsync(await [|$$FunctionAsync|]<int>(3)); } async Task<T> {|Definition:FunctionAsync|}<T>(T x) { return x; } } ]]> </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestAsyncCSAsIdentifier(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Test { async Task {|Definition:$$async|}() { } async void TestFunction() { await [|async|](); } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestAsyncVBAsIdentifier(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Test Async Function {|Definition:$$Async|}() As Task 'do nothing End Function Async Sub TestSub() Await [|Async|]() End Sub End Class </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestAwaitCSAsIdentifier(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Test { async Task {|Definition:await|}(){} async void TestAsync(){ await [|$$@await|]();} } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestAwaitVBAsIdentifier(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Test Function {|Definition:Await|}() As Integer Return 1 End Function Async Function [Await](ByVal x As Integer) As Task Return End Function Async Sub TestAsync() [|$$[Await]|]() Await [Await](1) End Sub End Class </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.Remote.Testing Namespace Microsoft.CodeAnalysis.Editor.UnitTests.FindReferences Partial Public Class FindReferencesTests <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSAsyncMethodsName1(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Test { void TestFunction() { [|OneAsync|](); } async void TestFunctionAsync() { await [|OneAsync|](); } async Task {|Definition:$$OneAsync|}() { return; } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestVBAsyncMethodsName1(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Test Sub TestSub() [|OneAsync|]() End Sub Async Sub TestSubAsync() Await [|OneAsync|]() End Sub Async Function {|Definition:$$OneAsync|}() As Task Return End Function End Class </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSAsyncMethodsName2(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ class Test { void TestFunction() { [|TwoAsync|](); } async void TestFunctionAsync() { await [|TwoAsync|](); } async Task<int> {|Definition:$$TwoAsync|}() { return 1; } } ]]> </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestVBAsyncMethodsName2(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Test Sub TestSub() [|OneAsync|]() End Sub Async Sub TestSubAsync() Await [|OneAsync|]() End Sub Async Function {|Definition:$$OneAsync|}() As Task(Of Integer) Return 1 End Function End Class </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSAsyncMethodsName3(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Test { void TestFunction() { [|ThreeAsync|](); } async void TestFunctionAsync() { [|ThreeAsync|](); } async void {|Definition:$$ThreeAsync|}() { } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestVBAsyncMethodsName3(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Test Sub TestSub() [|OneAsync|]() End Sub Async Sub TestSubAsync() Await [|OneAsync|]() End Sub Async Sub {|Definition:$$OneAsync|}() 'do nothing End Sub End Class </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSAsyncDelegatesName1(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ class Test { Func<Task> {|Definition:$$a1|} = async delegate { return; }; void TestFunction() { [|a1|](); } async Task TestFunctionAsync() { await [|a1|](); } } ]]> </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestVBAsyncDelegatesName1(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Test Dim {|Definition:$$a1|} As Func(Of Task) = Async Function() Return End Function Sub TestFunction() [|a1|]() End Sub Async Function TestFunctionAsync() As Task Await [|a1|]() End Function End Class </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSAsyncDelegatesName2(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ class Test { Action<Task> {|Definition:$$a1|} = async delegate (Task t) { await t; }; void TestFunction() { Task t; [|a1|](t); } async Task TestFunctionAsync() { Task t; [|a1|](t); } } ]]> </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestVBAsyncDelegatesName2(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Test Dim {|Definition:$$a1|} As Action(Of Task) = Async Sub(ByVal t As Task) Await t End Sub Sub TestFunction() Dim t As Task [|a1|](t) End Sub Async Function TestFunctionAsync() As Task Dim t As Task [|a1|](t) End Function End Class </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSAsyncLambdaName1(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ class Test { Action<Task> {|Definition:$$f1|} = async (t) => { await t; }; void TestFunction() { Task t; [|f1|](t); } async void TestFunctionAsync() { Task t; [|f1|](t); } } ]]> </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestVBAsyncLambdaName1(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Test Dim {|Definition:$$a1|} As Action(Of Task) = Async Sub(t) Await t End Sub Sub TestFunction() Dim t As Task [|a1|](t) End Sub Async Function TestFunctionAsync() As Task Dim t As Task [|a1|](t) End Function End Class </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestAsyncWithinDelegate(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ class Test { Action<Task> a1 = async delegate (Task t) { await [|$$Function|](); }; public static async Task {|Definition:Function|}() { } } class Program { delegate Task mydel(); async Task FunctionAsync() { mydel d = new mydel(Test.[|Function|]); } } ]]> </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestAsyncVBWithinAnonFunctions(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Test Dim a1 As Action(Of Task) = Async Sub(t) Await [|$$TestFunctionAsync|]() End Sub Delegate Function mydel() As Task(Of Integer) Async Function {|Definition:TestFunctionAsync|}() As Task(Of Integer) Return 1 End Function Async Sub SubAsync() Dim d As mydel = New mydel(AddressOf [|TestFunctionAsync|]) End Sub End Class </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestAsyncWithinLambda(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ class Test { Action<Task> a1 = async (Task t) => { await [|$$Function|](); }; public static async Task {|Definition:Function|}() { } } class Program { delegate Task mydel(); async Task FunctionAsync() { mydel d = new mydel(Test.[|Function|]); } } ]]> </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestAsyncFunctionWithAsyncParameters1(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ class Test { async Task CallFunctionAsync() { await [|OuterFunctionAsync|](await InnerFunctionAsync()); } async Task {|Definition:$$OuterFunctionAsync|}(int x) { return; } async Task<int> InnerFunctionAsync() { return 1; } } ]]> </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestAsyncVBFunctionWithAsyncParameters1(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Test Async Sub CallSubAsync() Await OuterFunctionAsync(Await [|$$InnerFunctionAsync|]()) End Sub Async Function OuterFunctionAsync(ByVal x As Integer) As Task Return End Function Async Function {|Definition:InnerFunctionAsync|}() As Task(Of Integer) Return 1 End Function End Class </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestAsyncVBFunctionWithAsyncParameters2(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Test Async Sub CallSubAsync() Await [|OuterFunctionAsync|](Await InnerFunctionAsync()) End Sub Async Function {|Definition:$$OuterFunctionAsync|}(ByVal x As Integer) As Task Return End Function Async Function InnerFunctionAsync() As Task(Of Integer) Return 1 End Function End Class </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestAsyncFunctionWithAsyncParameters2(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ class Test { async Task CallFunctionAsync() { await OuterFunctionAsync(await [|$$InnerFunctionAsync|]()); } async Task OuterFunctionAsync(int x) { return; } async Task<int> {|Definition:InnerFunctionAsync|}() { return 1; } } ]]> </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestAsyncFunctionWithAsyncParameters3(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ class Test { Func<Task<int>> {|Definition:$$f1|} = async delegate {return 1; }; async void CallFunctionAsync() { await OuterFunctionAsync(await [|f1|]()); } async Task OuterFunctionAsync(int x) { return; } } ]]> </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestAsyncFunctionWithAsyncParameters4(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ class Test { Func<int,Task<int>> {|Definition:f1|} = async (x) => {return 1; }; async void CallFunctionAsync() { await OuterFunctionAsync(await [|$$f1|](1)); } async Task OuterFunctionAsync(int x) { return; } } ]]> </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestAsyncCSFunctionWithRecursion(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ class Test { async Task {|Definition:$$FunctionAsync|}(int x) { if (x == 1) return; await [|FunctionAsync|](--x); } public void Function(int x) { [|FunctionAsync|](x); } } ]]> </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestAsyncCSFunctionWithOverloading1(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ using System.Threading.Tasks; class Test { async Task {|Definition:FunctionAsync|}(int x) { FunctionAsync("hello"); await FunctionAsync(await FunctionAsync<string>("hello")); } async Task FunctionAsync(string x) { [|FunctionAsync|](3); await FunctionAsync<float>(3f); await [|$$FunctionAsync|](await FunctionAsync<int>(3)); } async Task<T> FunctionAsync<T>(T x) { return x; } } ]]> </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestAsyncVBFunctionWithOverloading1(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports System Imports System.Threading.Tasks Class Test Async Function {|Definition:FunctionAsync|}(ByVal x As Integer) As Task FunctionAsync("Hello") Await FunctionAsync(Await FunctionAsync(Of String)("hello")) End Function Async Function FunctionAsync(ByVal x As String) As Task [|FunctionAsync|](3) Await FunctionAsync(Of Single)(3.5F) Await [|$$FunctionAsync|](Await FunctionAsync(Of Integer)(3)) End Function Async Function FunctionAsync(Of T)(ByVal x As T) As Task(Of T) Return x End Function End Class </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestAsyncVBFunctionWithOverloading2(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports System Imports System.Threading.Tasks Class Test Async Function FunctionAsync(ByVal x As Integer) As Task FunctionAsync("Hello") Await FunctionAsync(Await [|FunctionAsync|](Of String)("hello")) End Function Async Function FunctionAsync(ByVal x As String) As Task FunctionAsync(3) Await [|FunctionAsync|](Of Single)(3.5F) Await FunctionAsync(Await [|FunctionAsync|](Of Integer)(3)) End Function Async Function {|Definition:$$FunctionAsync|}(Of T)(ByVal x As T) As Task(Of T) Return x End Function End Class </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestAsyncCSFunctionWithOverloading2(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ using System; using System.Threading.Tasks; class Test { async Task FunctionAsync(int x) { FunctionAsync("hello"); await FunctionAsync(await [|FunctionAsync|]<string>("hello")); } async Task FunctionAsync(string x) { FunctionAsync(3); await [|FunctionAsync|]<float>(3f); await FunctionAsync(await [|$$FunctionAsync|]<int>(3)); } async Task<T> {|Definition:FunctionAsync|}<T>(T x) { return x; } } ]]> </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestAsyncCSAsIdentifier(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Test { async Task {|Definition:$$async|}() { } async void TestFunction() { await [|async|](); } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestAsyncVBAsIdentifier(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Test Async Function {|Definition:$$Async|}() As Task 'do nothing End Function Async Sub TestSub() Await [|Async|]() End Sub End Class </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestAwaitCSAsIdentifier(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Test { async Task {|Definition:await|}(){} async void TestAsync(){ await [|$$@await|]();} } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestAwaitVBAsIdentifier(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Test Function {|Definition:Await|}() As Integer Return 1 End Function Async Function [Await](ByVal x As Integer) As Task Return End Function Async Sub TestAsync() [|$$[Await]|]() Await [Await](1) End Sub End Class </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function End Class End Namespace
-1
dotnet/roslyn
56,011
React to string comparison changing on .NET Core
The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
jaredpar
"2021-08-30T17:18:52Z"
"2021-08-30T20:20:04Z"
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
4d99cda6e446e77dbb302e26388c1093bd3ef569
React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
./src/Features/VisualBasic/Portable/Completion/KeywordRecommenders/Statements/CaseKeywordRecommender.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis.Completion.Providers Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Statements ''' <summary> ''' Recommends the "Case" and possibly "Case Else" keyword inside a Select block ''' </summary> Friend Class CaseKeywordRecommender Inherits AbstractKeywordRecommender Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword) Dim targetToken = context.TargetToken ' Are we after "Select" for "Select Case"? If targetToken.Kind = SyntaxKind.SelectKeyword AndAlso Not targetToken.Parent.IsKind(SyntaxKind.SelectClause) AndAlso Not context.FollowsEndOfStatement Then Return ImmutableArray.Create(New RecommendedKeyword("Case", VBFeaturesResources.Introduces_a_value_or_set_of_values_against_which_the_value_of_an_expression_in_a_Select_Case_statement_is_to_be_tested_Case_expression_expression1_To_expression2_bracket_Is_bracket_comparisonOperator_expression)) End If ' A "Case" keyword must be in a Select block, and exists either where a regular executable statement can go ' or the special case of being immediately after the Select Case If Not context.IsInStatementBlockOfKind(SyntaxKind.SelectBlock) OrElse Not (context.IsMultiLineStatementContext OrElse context.IsAfterStatementOfKind(SyntaxKind.SelectStatement)) Then Return ImmutableArray(Of RecommendedKeyword).Empty End If Dim selectStatement = targetToken.GetAncestor(Of SelectBlockSyntax)() Dim validKeywords As New List(Of RecommendedKeyword) ' We can do "Case" as long as we're not after a "Case Else" Dim caseElseBlock = selectStatement.CaseBlocks.FirstOrDefault(Function(caseBlock) caseBlock.CaseStatement.Kind = SyntaxKind.CaseElseStatement) If caseElseBlock Is Nothing OrElse targetToken.SpanStart < caseElseBlock.SpanStart Then validKeywords.Add(New RecommendedKeyword("Case", VBFeaturesResources.Introduces_a_value_or_set_of_values_against_which_the_value_of_an_expression_in_a_Select_Case_statement_is_to_be_tested_Case_expression_expression1_To_expression2_bracket_Is_bracket_comparisonOperator_expression)) End If ' We can do a "Case Else" as long as we're the last one and we don't already have one. ' We exclude any partial case keywords the parser is creating (possibly because of user typing) Dim lastBlock = selectStatement.CaseBlocks.LastOrDefault(Function(caseBlock) Not caseBlock.CaseStatement.CaseKeyword.IsMissing) If caseElseBlock Is Nothing AndAlso (lastBlock Is Nothing OrElse targetToken.SpanStart > lastBlock.SpanStart) Then validKeywords.Add(New RecommendedKeyword("Case Else", VBFeaturesResources.Introduces_the_statements_to_run_if_none_of_the_previous_cases_in_the_Select_Case_statement_returns_True)) End If Return validKeywords.ToImmutableArray() End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis.Completion.Providers Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Statements ''' <summary> ''' Recommends the "Case" and possibly "Case Else" keyword inside a Select block ''' </summary> Friend Class CaseKeywordRecommender Inherits AbstractKeywordRecommender Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword) Dim targetToken = context.TargetToken ' Are we after "Select" for "Select Case"? If targetToken.Kind = SyntaxKind.SelectKeyword AndAlso Not targetToken.Parent.IsKind(SyntaxKind.SelectClause) AndAlso Not context.FollowsEndOfStatement Then Return ImmutableArray.Create(New RecommendedKeyword("Case", VBFeaturesResources.Introduces_a_value_or_set_of_values_against_which_the_value_of_an_expression_in_a_Select_Case_statement_is_to_be_tested_Case_expression_expression1_To_expression2_bracket_Is_bracket_comparisonOperator_expression)) End If ' A "Case" keyword must be in a Select block, and exists either where a regular executable statement can go ' or the special case of being immediately after the Select Case If Not context.IsInStatementBlockOfKind(SyntaxKind.SelectBlock) OrElse Not (context.IsMultiLineStatementContext OrElse context.IsAfterStatementOfKind(SyntaxKind.SelectStatement)) Then Return ImmutableArray(Of RecommendedKeyword).Empty End If Dim selectStatement = targetToken.GetAncestor(Of SelectBlockSyntax)() Dim validKeywords As New List(Of RecommendedKeyword) ' We can do "Case" as long as we're not after a "Case Else" Dim caseElseBlock = selectStatement.CaseBlocks.FirstOrDefault(Function(caseBlock) caseBlock.CaseStatement.Kind = SyntaxKind.CaseElseStatement) If caseElseBlock Is Nothing OrElse targetToken.SpanStart < caseElseBlock.SpanStart Then validKeywords.Add(New RecommendedKeyword("Case", VBFeaturesResources.Introduces_a_value_or_set_of_values_against_which_the_value_of_an_expression_in_a_Select_Case_statement_is_to_be_tested_Case_expression_expression1_To_expression2_bracket_Is_bracket_comparisonOperator_expression)) End If ' We can do a "Case Else" as long as we're the last one and we don't already have one. ' We exclude any partial case keywords the parser is creating (possibly because of user typing) Dim lastBlock = selectStatement.CaseBlocks.LastOrDefault(Function(caseBlock) Not caseBlock.CaseStatement.CaseKeyword.IsMissing) If caseElseBlock Is Nothing AndAlso (lastBlock Is Nothing OrElse targetToken.SpanStart > lastBlock.SpanStart) Then validKeywords.Add(New RecommendedKeyword("Case Else", VBFeaturesResources.Introduces_the_statements_to_run_if_none_of_the_previous_cases_in_the_Select_Case_statement_returns_True)) End If Return validKeywords.ToImmutableArray() End Function End Class End Namespace
-1
dotnet/roslyn
56,011
React to string comparison changing on .NET Core
The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
jaredpar
"2021-08-30T17:18:52Z"
"2021-08-30T20:20:04Z"
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
4d99cda6e446e77dbb302e26388c1093bd3ef569
React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
./src/Compilers/VisualBasic/Test/Semantic/Semantics/MeMyBaseMyClassTests.vb
' 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.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Imports VB = Microsoft.CodeAnalysis.VisualBasic Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Public Class MeMyBaseMyClassTests Inherits FlowTestBase #Region "ControlFlowPass and DataflowAnalysis" <Fact> Public Sub SimpleForeachTest() Dim source = <compilation name="MeIsKeyWord"> <file name="a.vb"> Imports System Class MeClass Public Sub test() [| Console.WriteLine(Me Is Me) 'BIND1: Dim x = Me |] End Sub Public Shared Sub Main() Dim x = New MeClass() x.test() End Sub End Class </file> </compilation> Dim analysisResults = CompileAndAnalyzeControlAndDataFlow(source) Dim controlFlowResults = analysisResults.Item1 Dim dataFlowResults = analysisResults.Item2 Assert.Equal(0, controlFlowResults.EntryPoints.Count()) Assert.Equal(0, controlFlowResults.ExitPoints.Count()) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <Fact> Public Sub CallSharedFunctionInBaseClassByMe() Dim source = <compilation name="CallSharedFunctionInBaseClassByMe"> <file name="a.vb"> Imports System Class BaseClass Function Method() As String Return "BaseClass" End Function End Class Class DerivedClass Inherits BaseClass Sub Test() [| Console.WriteLine(Me.Method) Dim x = Me.Method |] End Sub End Class </file> </compilation> Dim analysisResults = CompileAndAnalyzeControlAndDataFlow(source) Dim controlFlowResults = analysisResults.Item1 Dim dataFlowResults = analysisResults.Item2 Assert.Equal(0, controlFlowResults.EntryPoints.Count()) Assert.Equal(0, controlFlowResults.ExitPoints.Count()) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <Fact> Public Sub UseMeInStructure() Dim source = <compilation name="UseMeInStructure"> <file name="a.vb"> Structure s1 Dim x As Integer Sub goo() [| Me.x = 1 Dim y = Me.x |] End Sub End Structure </file> </compilation> Dim analysisResults = CompileAndAnalyzeControlAndDataFlow(source) Dim controlFlowResults = analysisResults.Item1 Dim dataFlowResults = analysisResults.Item2 Assert.Equal(0, controlFlowResults.EntryPoints.Count()) Assert.Equal(0, controlFlowResults.ExitPoints.Count()) Assert.Equal("y", GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal("y", GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("Me, y", GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <Fact()> Public Sub CallMyBaseInLambda() Dim source = <compilation name="CallMyBaseInLambda"> <file name="a.vb"> Imports System Module Module1 Class Class1 Function Bar(n As Integer) As Integer Return n + 1 End Function End Class Class Class2 : Inherits Class1 Sub TEST() Dim TEMP = [| Function(X) MyBase.Bar(x) |] End Sub End Class End Module </file> </compilation> Dim dataFlowResults = CompileAndAnalyzeDataFlow(source) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.Captured)) Assert.Equal("X", GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("Me, X", GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("X", GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal("Me, TEMP", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <Fact> Public Sub UseMyBaseInQuery() Dim source = <compilation name="UseMyBaseInQuery"> <file name="a.vb"> Imports System.Linq Module Module1 Class Class1 Function Bar() As String Bar = "hello" End Function End Class Class Class2 : Inherits Class1 Function TEST() [| TEST = From x In MyBase.Bar Select x |] End Function End Class End Module </file> </compilation> Dim analysisResults = CompileAndAnalyzeControlAndDataFlow(source) Dim controlFlowResults = analysisResults.Item1 Dim dataFlowResults = analysisResults.Item2 Assert.Equal(0, controlFlowResults.EntryPoints.Count()) Assert.Equal(0, controlFlowResults.ExitPoints.Count()) Assert.Equal("x, x", GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal("TEST", GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("Me, x", GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("TEST, x, x", GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <Fact> Public Sub MyClassUsedToRefMethodDefinedInBaseClass() Dim source = <compilation name="MyClassUsedToRefMethodDefinedInBaseClass"> <file name="a.vb"> Class BaseClass Public Function goo() goo = "STRING" End Function End Class Class DerivedClass Inherits BaseClass Sub Test() [| Dim x = MyClass.goo() |] End Sub End Class </file> </compilation> Dim analysisResults = CompileAndAnalyzeControlAndDataFlow(source) Dim controlFlowResults = analysisResults.Item1 Dim dataFlowResults = analysisResults.Item2 Assert.Equal(0, controlFlowResults.EntryPoints.Count()) Assert.Equal(0, controlFlowResults.ExitPoints.Count()) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <Fact> Public Sub MyClassUsedToQualifierSharedMember() Dim source = <compilation name="MyClassUsedToQualifierSharedMember"> <file name="a.vb"> Class BaseClass Private Sub goo() End Sub End Class Class DerivedClass Inherits BaseClass Shared age As Integer Sub Test() [| Dim x = MyClass.age |] End Sub End Class </file> </compilation> Dim analysisResults = CompileAndAnalyzeControlAndDataFlow(source) Dim controlFlowResults = analysisResults.Item1 Dim dataFlowResults = analysisResults.Item2 Assert.Equal(0, controlFlowResults.EntryPoints.Count()) Assert.Equal(0, controlFlowResults.ExitPoints.Count()) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub #End Region #Region "LookUpSymbol & GetSymbolInfo & GetTypeInfo Test" ' Call Me.[Me] <Fact> Public Sub CallMe() Dim comp = CreateCompilationWithMscorlib40( <compilation name="CallMe"> <file name="a.vb"> Imports System Class MeClass Function [Me]() As String 'BIND1:"[Me]" [Me] = "Hello" Console.WriteLine(Me.Me) End Function Public Shared Sub Main() Dim x = New MeClass x.Me() End Sub End Class </file> </compilation>) Dim symbol = LookUpSymbolTest(comp, "Me", 1, 1, "Function MeClass.Me() As System.String") GetSymbolInfoTest(comp, "Me.Me", symbol) GetTypeInfoTest(comp, "Me.Me", "String") End Sub <Fact> Public Sub AssignMeToVar() Dim comp = CreateCompilationWithMscorlib40( <compilation name="AssignMeToVar"> <file name="a.vb"> Option Infer On Imports System Class C1 Dim var = Me 'BIND1:"Me" End Class </file> </compilation>) ' get Me via the field Dim field = comp.GlobalNamespace.GetTypeMember("C1").GetMember("var") Dim meSymbol = DirectCast(field, SourceFieldSymbol).MeParameter ' must be same parameter as in the initializer GetSymbolInfoTest(comp, "Me", meSymbol) GetTypeInfoTest(comp, "Me", "C1") End Sub <Fact> Public Sub AssignMeToVar_Derived() Dim comp = CreateCompilationWithMscorlib40( <compilation name="AssignMeToVar"> <file name="a.vb"> Option Infer On Imports System Class base End Class Structure s1 Class c1 Inherits base Dim y As base = Me 'BIND1:"Me" Dim x As c1 = Me 'BIND2:"Me" End Class End Structure </file> </compilation>) LookUpSymbolTest(comp, "Me") LookUpSymbolTest(comp, "Me", 2) ' get Me via the field Dim field = comp.GlobalNamespace.GetTypeMember("s1").GetTypeMember("c1").GetMember("y") Dim meSymbol = DirectCast(field, SourceFieldSymbol).MeParameter GetSymbolInfoTest(comp, "Me", meSymbol) GetTypeInfoTest(comp, "Me", "s1.c1") End Sub <Fact> Public Sub CallFunctionInBaseClassByMe() Dim comp = CreateCompilationWithMscorlib40( <compilation name="CallFunctionInBaseClassByMe"> <file name="a.vb"> Option Infer On Imports System Class BaseClass Function Method() As String Return "BaseClass" End Function End Class Class DerivedClass Inherits BaseClass Sub Test() Console.WriteLine(Me.Method) 'BIND1:"Method" End Sub End Class </file> </compilation>) Dim symbol = LookUpSymbolTest(comp, "Method", expectedCount:=1, expectedString:="Function BaseClass.Method() As System.String") GetSymbolInfoTest(comp, "Me.Method", symbol) GetTypeInfoTest(comp, "Me.Method", "String") symbol = LookUpSymbolTest(comp, "DerivedClass", expectedCount:=1, expectedString:="DerivedClass") GetTypeInfoTest(comp, "Me", "DerivedClass") End Sub <WorkItem(529096, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529096")> <Fact()> Public Sub UseMeInLambda() Dim comp = CreateCompilationWithMscorlib40( <compilation name="UseMeInLambda"> <file name="a.vb"> Option Infer On Module Module1 Class Class1 Function Bar() As Integer Return 1 End Function End Class Class Class2 : Inherits Class1 Sub TEST() Dim TEMP = Function(X) Me.Bar 'BIND1:"Bar" End Sub End Class End Module </file> </compilation>) Dim symbol = LookUpSymbolTest(comp, "Bar", expectedCount:=1, expectedString:="Function Module1.Class1.Bar() As System.Int32") GetSymbolInfoTest(comp, "Me.Bar", symbol) GetTypeInfoTest(comp, "Me.Bar", "Integer") End Sub <Fact> Public Sub UseMeInQuery() Dim comp = CreateCompilationWithMscorlib40( <compilation name="UseMeInQuery"> <file name="a.vb"> Option Infer On Imports System.Linq Module Module1 Class Class1 Function Bar1() As String 'BIND1:"Bar1" Bar1 = "hello" End Function End Class Class Class2 : Inherits Class1 Function TEST() TEST = From x In Me.Bar1 Select Me End Function End Class End Module </file> </compilation>) Dim symbol = LookUpSymbolTest(comp, "Bar1", expectedCount:=1, expectedString:="Function Module1.Class1.Bar1() As System.String") GetSymbolInfoTest(comp, "Me.Bar1", symbol) GetTypeInfoTest(comp, "Me.Bar1", "String") End Sub <Fact> Public Sub InvokeMyBaseAutoProperty() Dim comp = CreateCompilationWithMscorlib40( <compilation name="InvokeMyBaseAutoProperty"> <file name="a.vb"> Option Infer On Imports System.Linq Class GenBase Public Property Propabc As Integer = 1 Public abc As Integer = 1 End Class Class GenParent(Of t) Inherits GenBase Dim xyz = 1 Public Property PropXyz = 1 Sub goo() Dim x = Sub() xyz = 2 MyBase.abc = 1 PropXyz = 3 MyBase.Propabc = 4 'BIND1:"Propabc" End Sub x.Invoke() End Sub End Class </file> </compilation>) Dim symbol = LookUpSymbolTest(comp, "Propabc", expectedCount:=1, expectedString:="Property GenBase.Propabc As System.Int32") GetSymbolInfoTest(comp, "MyBase.Propabc", symbol) GetTypeInfoTest(comp, "MyBase.Propabc", "Integer") symbol = LookUpSymbolTest(comp, "GenBase", expectedCount:=1, expectedString:="GenBase") GetTypeInfoTest(comp, "MyBase", "GenBase") End Sub <Fact> Public Sub InvokeMyBaseImplementMultInterface() Dim comp = CreateCompilationWithMscorlib40( <compilation name="InvokeMyBaseImplementMultInterface"> <file name="a.vb"> Option Infer On Imports System.Linq Class C1 Implements System.Collections.Generic.IComparer(Of String) Implements System.Collections.Generic.IComparer(Of Integer) Public Function Compare1(ByVal x As String, ByVal y As String) As Integer Implements System.Collections.Generic.IComparer(Of String).Compare Return 0 End Function Public Function Compare1(ByVal x As Integer, ByVal y As Integer) As Integer Implements System.Collections.Generic.IComparer(Of Integer).Compare Return 0 End Function Sub GOO() Console.WriteLine(MyBase.ToString()) 'BIND1:"MyBase" End Sub End Class </file> </compilation>) GetTypeInfoTest(comp, "MyBase", "Object") End Sub <Fact> Public Sub InvokeExtensionMethodFromMyClass() Dim comp = CreateCompilationWithMscorlib40AndReferences( <compilation name="InvokeExtensionMethodFromMyClass"> <file name="a.vb"> Option Infer On Imports System.Runtime.CompilerServices Imports System Class C1 Sub Goo() Console.WriteLine(MyClass.Sum) 'BIND1:"Sum" End Sub End Class &lt;Extension()&gt; Module MyExtensionModule &lt;Extension()&gt; Function Sum([Me] As C1) As Integer Sum = 1 End Function End Module </file> </compilation>, {TestMetadata.Net40.SystemCore}) Dim symbol = LookUpSymbolTest(comp, "Sum", expectedCount:=1, expectedString:="Function C1.Sum() As System.Int32") GetSymbolInfoTest(comp, "MyClass.Sum", symbol) GetTypeInfoTest(comp, "MyClass.Sum", "Integer") symbol = LookUpSymbolTest(comp, "C1", expectedCount:=1, expectedString:="C1") GetTypeInfoTest(comp, "MyClass", "C1") End Sub <Fact> Public Sub MyClassUsedInStructure() Dim comp = CreateCompilationWithMscorlib40( <compilation name="MyClassUsedInStructure"> <file name="a.vb"> Option Infer On Structure s1 Sub goo() Console.WriteLine(MyClass.ToString()) 'BIND1:"MyClass" End Sub End Structure </file> </compilation>) Dim symbol = LookUpSymbolTest(comp, "s1", expectedCount:=1, expectedString:="s1") GetTypeInfoTest(comp, "MyClass", "s1") End Sub Public Function LookUpSymbolTest(comp As VisualBasicCompilation, name As String, Optional index As Integer = 1, Optional expectedCount As Integer = 0, Optional expectedString As String = "") As ISymbol Dim tree = comp.SyntaxTrees.First Dim nodes As New List(Of VisualBasicSyntaxNode) Dim model = comp.GetSemanticModel(tree) Dim pos As Integer = CompilationUtils.FindBindingTextPosition(comp, "a.vb", Nothing, index) Dim symbol = model.LookupSymbols(pos, name:=name, includeReducedExtensionMethods:=True) Assert.Equal(expectedCount, symbol.Length) If expectedCount <> 0 Then Assert.Equal(expectedString, symbol.Single.ToTestDisplayString()) Return symbol.Single End If Return Nothing End Function Public Sub GetSymbolInfoTest(comp As VisualBasicCompilation, nodeName As String, expectedSymbol As ISymbol) Dim tree = comp.SyntaxTrees.First Dim model = comp.GetSemanticModel(tree) Dim expressions = tree.GetCompilationUnitRoot().DescendantNodesAndSelf.Where(Function(x) x.Kind = SyntaxKind.MeExpression Or x.Kind = SyntaxKind.MyBaseExpression Or x.Kind = SyntaxKind.MyClassExpression Or x.Kind = SyntaxKind.SimpleMemberAccessExpression).ToList() Dim expression = expressions.Where(Function(x) x.ToString = nodeName).First() Dim symbolInfo = model.GetSymbolInfo(DirectCast(expression, ExpressionSyntax)) If (Equals(expectedSymbol, Nothing)) Then Assert.Equal(expectedSymbol, symbolInfo.Symbol) ElseIf (DirectCast(expectedSymbol, Symbol).IsReducedExtensionMethod = False) Then Assert.Equal(expectedSymbol, symbolInfo.Symbol) Else Dim methodActual = DirectCast(symbolInfo.Symbol, MethodSymbol) Dim methodExpected = DirectCast(expectedSymbol, MethodSymbol) Assert.Equal(methodExpected.CallsiteReducedFromMethod, methodActual.CallsiteReducedFromMethod) End If End Sub Public Sub GetTypeInfoTest(comp As VisualBasicCompilation, nodeName As String, expectedTypeInfo As String) Dim tree = comp.SyntaxTrees.First Dim model = comp.GetSemanticModel(tree) Dim expressions = tree.GetCompilationUnitRoot().DescendantNodesAndSelf.Where(Function(x) x.Kind = SyntaxKind.MeExpression Or x.Kind = SyntaxKind.MyBaseExpression Or x.Kind = SyntaxKind.MyClassExpression Or x.Kind = SyntaxKind.SimpleMemberAccessExpression).ToList() Dim expression = expressions.Where(Function(x) x.ToString = nodeName).First() Dim typeInfo = model.GetTypeInfo(DirectCast(expression, ExpressionSyntax)) Assert.NotNull(typeInfo.Type) Assert.Equal(expectedTypeInfo, typeInfo.Type.ToDisplayString()) End Sub #End Region End Class End Namespace
' 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.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Imports VB = Microsoft.CodeAnalysis.VisualBasic Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Public Class MeMyBaseMyClassTests Inherits FlowTestBase #Region "ControlFlowPass and DataflowAnalysis" <Fact> Public Sub SimpleForeachTest() Dim source = <compilation name="MeIsKeyWord"> <file name="a.vb"> Imports System Class MeClass Public Sub test() [| Console.WriteLine(Me Is Me) 'BIND1: Dim x = Me |] End Sub Public Shared Sub Main() Dim x = New MeClass() x.test() End Sub End Class </file> </compilation> Dim analysisResults = CompileAndAnalyzeControlAndDataFlow(source) Dim controlFlowResults = analysisResults.Item1 Dim dataFlowResults = analysisResults.Item2 Assert.Equal(0, controlFlowResults.EntryPoints.Count()) Assert.Equal(0, controlFlowResults.ExitPoints.Count()) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <Fact> Public Sub CallSharedFunctionInBaseClassByMe() Dim source = <compilation name="CallSharedFunctionInBaseClassByMe"> <file name="a.vb"> Imports System Class BaseClass Function Method() As String Return "BaseClass" End Function End Class Class DerivedClass Inherits BaseClass Sub Test() [| Console.WriteLine(Me.Method) Dim x = Me.Method |] End Sub End Class </file> </compilation> Dim analysisResults = CompileAndAnalyzeControlAndDataFlow(source) Dim controlFlowResults = analysisResults.Item1 Dim dataFlowResults = analysisResults.Item2 Assert.Equal(0, controlFlowResults.EntryPoints.Count()) Assert.Equal(0, controlFlowResults.ExitPoints.Count()) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <Fact> Public Sub UseMeInStructure() Dim source = <compilation name="UseMeInStructure"> <file name="a.vb"> Structure s1 Dim x As Integer Sub goo() [| Me.x = 1 Dim y = Me.x |] End Sub End Structure </file> </compilation> Dim analysisResults = CompileAndAnalyzeControlAndDataFlow(source) Dim controlFlowResults = analysisResults.Item1 Dim dataFlowResults = analysisResults.Item2 Assert.Equal(0, controlFlowResults.EntryPoints.Count()) Assert.Equal(0, controlFlowResults.ExitPoints.Count()) Assert.Equal("y", GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal("y", GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("Me, y", GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <Fact()> Public Sub CallMyBaseInLambda() Dim source = <compilation name="CallMyBaseInLambda"> <file name="a.vb"> Imports System Module Module1 Class Class1 Function Bar(n As Integer) As Integer Return n + 1 End Function End Class Class Class2 : Inherits Class1 Sub TEST() Dim TEMP = [| Function(X) MyBase.Bar(x) |] End Sub End Class End Module </file> </compilation> Dim dataFlowResults = CompileAndAnalyzeDataFlow(source) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.Captured)) Assert.Equal("X", GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("Me, X", GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("X", GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal("Me, TEMP", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <Fact> Public Sub UseMyBaseInQuery() Dim source = <compilation name="UseMyBaseInQuery"> <file name="a.vb"> Imports System.Linq Module Module1 Class Class1 Function Bar() As String Bar = "hello" End Function End Class Class Class2 : Inherits Class1 Function TEST() [| TEST = From x In MyBase.Bar Select x |] End Function End Class End Module </file> </compilation> Dim analysisResults = CompileAndAnalyzeControlAndDataFlow(source) Dim controlFlowResults = analysisResults.Item1 Dim dataFlowResults = analysisResults.Item2 Assert.Equal(0, controlFlowResults.EntryPoints.Count()) Assert.Equal(0, controlFlowResults.ExitPoints.Count()) Assert.Equal("x, x", GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal("TEST", GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("Me, x", GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("TEST, x, x", GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <Fact> Public Sub MyClassUsedToRefMethodDefinedInBaseClass() Dim source = <compilation name="MyClassUsedToRefMethodDefinedInBaseClass"> <file name="a.vb"> Class BaseClass Public Function goo() goo = "STRING" End Function End Class Class DerivedClass Inherits BaseClass Sub Test() [| Dim x = MyClass.goo() |] End Sub End Class </file> </compilation> Dim analysisResults = CompileAndAnalyzeControlAndDataFlow(source) Dim controlFlowResults = analysisResults.Item1 Dim dataFlowResults = analysisResults.Item2 Assert.Equal(0, controlFlowResults.EntryPoints.Count()) Assert.Equal(0, controlFlowResults.ExitPoints.Count()) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <Fact> Public Sub MyClassUsedToQualifierSharedMember() Dim source = <compilation name="MyClassUsedToQualifierSharedMember"> <file name="a.vb"> Class BaseClass Private Sub goo() End Sub End Class Class DerivedClass Inherits BaseClass Shared age As Integer Sub Test() [| Dim x = MyClass.age |] End Sub End Class </file> </compilation> Dim analysisResults = CompileAndAnalyzeControlAndDataFlow(source) Dim controlFlowResults = analysisResults.Item1 Dim dataFlowResults = analysisResults.Item2 Assert.Equal(0, controlFlowResults.EntryPoints.Count()) Assert.Equal(0, controlFlowResults.ExitPoints.Count()) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub #End Region #Region "LookUpSymbol & GetSymbolInfo & GetTypeInfo Test" ' Call Me.[Me] <Fact> Public Sub CallMe() Dim comp = CreateCompilationWithMscorlib40( <compilation name="CallMe"> <file name="a.vb"> Imports System Class MeClass Function [Me]() As String 'BIND1:"[Me]" [Me] = "Hello" Console.WriteLine(Me.Me) End Function Public Shared Sub Main() Dim x = New MeClass x.Me() End Sub End Class </file> </compilation>) Dim symbol = LookUpSymbolTest(comp, "Me", 1, 1, "Function MeClass.Me() As System.String") GetSymbolInfoTest(comp, "Me.Me", symbol) GetTypeInfoTest(comp, "Me.Me", "String") End Sub <Fact> Public Sub AssignMeToVar() Dim comp = CreateCompilationWithMscorlib40( <compilation name="AssignMeToVar"> <file name="a.vb"> Option Infer On Imports System Class C1 Dim var = Me 'BIND1:"Me" End Class </file> </compilation>) ' get Me via the field Dim field = comp.GlobalNamespace.GetTypeMember("C1").GetMember("var") Dim meSymbol = DirectCast(field, SourceFieldSymbol).MeParameter ' must be same parameter as in the initializer GetSymbolInfoTest(comp, "Me", meSymbol) GetTypeInfoTest(comp, "Me", "C1") End Sub <Fact> Public Sub AssignMeToVar_Derived() Dim comp = CreateCompilationWithMscorlib40( <compilation name="AssignMeToVar"> <file name="a.vb"> Option Infer On Imports System Class base End Class Structure s1 Class c1 Inherits base Dim y As base = Me 'BIND1:"Me" Dim x As c1 = Me 'BIND2:"Me" End Class End Structure </file> </compilation>) LookUpSymbolTest(comp, "Me") LookUpSymbolTest(comp, "Me", 2) ' get Me via the field Dim field = comp.GlobalNamespace.GetTypeMember("s1").GetTypeMember("c1").GetMember("y") Dim meSymbol = DirectCast(field, SourceFieldSymbol).MeParameter GetSymbolInfoTest(comp, "Me", meSymbol) GetTypeInfoTest(comp, "Me", "s1.c1") End Sub <Fact> Public Sub CallFunctionInBaseClassByMe() Dim comp = CreateCompilationWithMscorlib40( <compilation name="CallFunctionInBaseClassByMe"> <file name="a.vb"> Option Infer On Imports System Class BaseClass Function Method() As String Return "BaseClass" End Function End Class Class DerivedClass Inherits BaseClass Sub Test() Console.WriteLine(Me.Method) 'BIND1:"Method" End Sub End Class </file> </compilation>) Dim symbol = LookUpSymbolTest(comp, "Method", expectedCount:=1, expectedString:="Function BaseClass.Method() As System.String") GetSymbolInfoTest(comp, "Me.Method", symbol) GetTypeInfoTest(comp, "Me.Method", "String") symbol = LookUpSymbolTest(comp, "DerivedClass", expectedCount:=1, expectedString:="DerivedClass") GetTypeInfoTest(comp, "Me", "DerivedClass") End Sub <WorkItem(529096, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529096")> <Fact()> Public Sub UseMeInLambda() Dim comp = CreateCompilationWithMscorlib40( <compilation name="UseMeInLambda"> <file name="a.vb"> Option Infer On Module Module1 Class Class1 Function Bar() As Integer Return 1 End Function End Class Class Class2 : Inherits Class1 Sub TEST() Dim TEMP = Function(X) Me.Bar 'BIND1:"Bar" End Sub End Class End Module </file> </compilation>) Dim symbol = LookUpSymbolTest(comp, "Bar", expectedCount:=1, expectedString:="Function Module1.Class1.Bar() As System.Int32") GetSymbolInfoTest(comp, "Me.Bar", symbol) GetTypeInfoTest(comp, "Me.Bar", "Integer") End Sub <Fact> Public Sub UseMeInQuery() Dim comp = CreateCompilationWithMscorlib40( <compilation name="UseMeInQuery"> <file name="a.vb"> Option Infer On Imports System.Linq Module Module1 Class Class1 Function Bar1() As String 'BIND1:"Bar1" Bar1 = "hello" End Function End Class Class Class2 : Inherits Class1 Function TEST() TEST = From x In Me.Bar1 Select Me End Function End Class End Module </file> </compilation>) Dim symbol = LookUpSymbolTest(comp, "Bar1", expectedCount:=1, expectedString:="Function Module1.Class1.Bar1() As System.String") GetSymbolInfoTest(comp, "Me.Bar1", symbol) GetTypeInfoTest(comp, "Me.Bar1", "String") End Sub <Fact> Public Sub InvokeMyBaseAutoProperty() Dim comp = CreateCompilationWithMscorlib40( <compilation name="InvokeMyBaseAutoProperty"> <file name="a.vb"> Option Infer On Imports System.Linq Class GenBase Public Property Propabc As Integer = 1 Public abc As Integer = 1 End Class Class GenParent(Of t) Inherits GenBase Dim xyz = 1 Public Property PropXyz = 1 Sub goo() Dim x = Sub() xyz = 2 MyBase.abc = 1 PropXyz = 3 MyBase.Propabc = 4 'BIND1:"Propabc" End Sub x.Invoke() End Sub End Class </file> </compilation>) Dim symbol = LookUpSymbolTest(comp, "Propabc", expectedCount:=1, expectedString:="Property GenBase.Propabc As System.Int32") GetSymbolInfoTest(comp, "MyBase.Propabc", symbol) GetTypeInfoTest(comp, "MyBase.Propabc", "Integer") symbol = LookUpSymbolTest(comp, "GenBase", expectedCount:=1, expectedString:="GenBase") GetTypeInfoTest(comp, "MyBase", "GenBase") End Sub <Fact> Public Sub InvokeMyBaseImplementMultInterface() Dim comp = CreateCompilationWithMscorlib40( <compilation name="InvokeMyBaseImplementMultInterface"> <file name="a.vb"> Option Infer On Imports System.Linq Class C1 Implements System.Collections.Generic.IComparer(Of String) Implements System.Collections.Generic.IComparer(Of Integer) Public Function Compare1(ByVal x As String, ByVal y As String) As Integer Implements System.Collections.Generic.IComparer(Of String).Compare Return 0 End Function Public Function Compare1(ByVal x As Integer, ByVal y As Integer) As Integer Implements System.Collections.Generic.IComparer(Of Integer).Compare Return 0 End Function Sub GOO() Console.WriteLine(MyBase.ToString()) 'BIND1:"MyBase" End Sub End Class </file> </compilation>) GetTypeInfoTest(comp, "MyBase", "Object") End Sub <Fact> Public Sub InvokeExtensionMethodFromMyClass() Dim comp = CreateCompilationWithMscorlib40AndReferences( <compilation name="InvokeExtensionMethodFromMyClass"> <file name="a.vb"> Option Infer On Imports System.Runtime.CompilerServices Imports System Class C1 Sub Goo() Console.WriteLine(MyClass.Sum) 'BIND1:"Sum" End Sub End Class &lt;Extension()&gt; Module MyExtensionModule &lt;Extension()&gt; Function Sum([Me] As C1) As Integer Sum = 1 End Function End Module </file> </compilation>, {TestMetadata.Net40.SystemCore}) Dim symbol = LookUpSymbolTest(comp, "Sum", expectedCount:=1, expectedString:="Function C1.Sum() As System.Int32") GetSymbolInfoTest(comp, "MyClass.Sum", symbol) GetTypeInfoTest(comp, "MyClass.Sum", "Integer") symbol = LookUpSymbolTest(comp, "C1", expectedCount:=1, expectedString:="C1") GetTypeInfoTest(comp, "MyClass", "C1") End Sub <Fact> Public Sub MyClassUsedInStructure() Dim comp = CreateCompilationWithMscorlib40( <compilation name="MyClassUsedInStructure"> <file name="a.vb"> Option Infer On Structure s1 Sub goo() Console.WriteLine(MyClass.ToString()) 'BIND1:"MyClass" End Sub End Structure </file> </compilation>) Dim symbol = LookUpSymbolTest(comp, "s1", expectedCount:=1, expectedString:="s1") GetTypeInfoTest(comp, "MyClass", "s1") End Sub Public Function LookUpSymbolTest(comp As VisualBasicCompilation, name As String, Optional index As Integer = 1, Optional expectedCount As Integer = 0, Optional expectedString As String = "") As ISymbol Dim tree = comp.SyntaxTrees.First Dim nodes As New List(Of VisualBasicSyntaxNode) Dim model = comp.GetSemanticModel(tree) Dim pos As Integer = CompilationUtils.FindBindingTextPosition(comp, "a.vb", Nothing, index) Dim symbol = model.LookupSymbols(pos, name:=name, includeReducedExtensionMethods:=True) Assert.Equal(expectedCount, symbol.Length) If expectedCount <> 0 Then Assert.Equal(expectedString, symbol.Single.ToTestDisplayString()) Return symbol.Single End If Return Nothing End Function Public Sub GetSymbolInfoTest(comp As VisualBasicCompilation, nodeName As String, expectedSymbol As ISymbol) Dim tree = comp.SyntaxTrees.First Dim model = comp.GetSemanticModel(tree) Dim expressions = tree.GetCompilationUnitRoot().DescendantNodesAndSelf.Where(Function(x) x.Kind = SyntaxKind.MeExpression Or x.Kind = SyntaxKind.MyBaseExpression Or x.Kind = SyntaxKind.MyClassExpression Or x.Kind = SyntaxKind.SimpleMemberAccessExpression).ToList() Dim expression = expressions.Where(Function(x) x.ToString = nodeName).First() Dim symbolInfo = model.GetSymbolInfo(DirectCast(expression, ExpressionSyntax)) If (Equals(expectedSymbol, Nothing)) Then Assert.Equal(expectedSymbol, symbolInfo.Symbol) ElseIf (DirectCast(expectedSymbol, Symbol).IsReducedExtensionMethod = False) Then Assert.Equal(expectedSymbol, symbolInfo.Symbol) Else Dim methodActual = DirectCast(symbolInfo.Symbol, MethodSymbol) Dim methodExpected = DirectCast(expectedSymbol, MethodSymbol) Assert.Equal(methodExpected.CallsiteReducedFromMethod, methodActual.CallsiteReducedFromMethod) End If End Sub Public Sub GetTypeInfoTest(comp As VisualBasicCompilation, nodeName As String, expectedTypeInfo As String) Dim tree = comp.SyntaxTrees.First Dim model = comp.GetSemanticModel(tree) Dim expressions = tree.GetCompilationUnitRoot().DescendantNodesAndSelf.Where(Function(x) x.Kind = SyntaxKind.MeExpression Or x.Kind = SyntaxKind.MyBaseExpression Or x.Kind = SyntaxKind.MyClassExpression Or x.Kind = SyntaxKind.SimpleMemberAccessExpression).ToList() Dim expression = expressions.Where(Function(x) x.ToString = nodeName).First() Dim typeInfo = model.GetTypeInfo(DirectCast(expression, ExpressionSyntax)) Assert.NotNull(typeInfo.Type) Assert.Equal(expectedTypeInfo, typeInfo.Type.ToDisplayString()) End Sub #End Region End Class End Namespace
-1
dotnet/roslyn
56,011
React to string comparison changing on .NET Core
The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
jaredpar
"2021-08-30T17:18:52Z"
"2021-08-30T20:20:04Z"
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
4d99cda6e446e77dbb302e26388c1093bd3ef569
React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
./src/VisualStudio/Core/Test/CodeModel/AbstractCodeModelObjectTests.NamespaceData.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel Partial Public MustInherit Class AbstractCodeModelObjectTests(Of TCodeModelObject As Class) Protected Class NamespaceData Public Property Name As String Public Property Position As Object End Class End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel Partial Public MustInherit Class AbstractCodeModelObjectTests(Of TCodeModelObject As Class) Protected Class NamespaceData Public Property Name As String Public Property Position As Object End Class End Class End Namespace
-1
dotnet/roslyn
56,011
React to string comparison changing on .NET Core
The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
jaredpar
"2021-08-30T17:18:52Z"
"2021-08-30T20:20:04Z"
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
4d99cda6e446e77dbb302e26388c1093bd3ef569
React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
./src/EditorFeatures/Test2/NavigationBar/VisualBasicNavigationBarTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.Editor.VisualBasic Imports Microsoft.CodeAnalysis.Remote.Testing Imports Microsoft.CodeAnalysis.VisualBasic Namespace Microsoft.CodeAnalysis.Editor.UnitTests.NavigationBar <[UseExportProvider]> Partial Public Class VisualBasicNavigationBarTests <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545000, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545000")> Public Async Function TestEventsInInterfaces(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Interface I Event Goo As EventHandler End Interface </Document> </Project> </Workspace>, host, Item("I", Glyph.InterfaceInternal, bolded:=True, children:={ Item("Goo", Glyph.EventPublic, bolded:=True)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(544996, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544996")> Public Async Function TestEmptyStructure(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Structure S End Structure </Document> </Project> </Workspace>, host, Item("S", Glyph.StructureInternal, bolded:=True, children:={})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(544996, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544996")> Public Async Function TestEmptyInterface(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Interface I End Interface </Document> </Project> </Workspace>, host, Item("I", Glyph.InterfaceInternal, bolded:=True, children:={})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(797455, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/797455")> Public Async Function TestUserDefinedOperators(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Shared Operator -(x As C, y As C) As C End Operator Shared Operator +(x As C, y As C) As C End Operator Shared Operator +(x As C, y As Integer) As C End Operator End Class </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, bolded:=False, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, bolded:=False, hasNavigationSymbolId:=False), Item("Operator +(C, C) As C", Glyph.Operator, bolded:=True), Item("Operator +(C, Integer) As C", Glyph.Operator, bolded:=True), Item("Operator -", Glyph.Operator, bolded:=True)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(797455, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/797455")> Public Async Function TestSingleConversion(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Shared Narrowing Operator CType(x As C) As Integer End Operator End Class </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, bolded:=False, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, bolded:=False, hasNavigationSymbolId:=False), Item("Narrowing Operator CType", Glyph.Operator, bolded:=True)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(797455, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/797455")> Public Async Function TestMultipleConversions(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Shared Narrowing Operator CType(x As C) As Integer End Operator Shared Narrowing Operator CType(x As C) As String End Operator End Class </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, bolded:=False, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, bolded:=False, hasNavigationSymbolId:=False), Item("Narrowing Operator CType(C) As Integer", Glyph.Operator, bolded:=True), Item("Narrowing Operator CType(C) As String", Glyph.Operator, bolded:=True)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(544993, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544993")> Public Async Function TestNestedClass(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Namespace N Class C Class Nested End Class End Class End Namespace </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, bolded:=True), Item("Nested (N.C)", Glyph.ClassPublic, bolded:=True)) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(544997, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544997")> Public Async Function TestDelegate(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Delegate Sub Goo() </Document> </Project> </Workspace>, host, Item("Goo", Glyph.DelegateInternal, children:={}, bolded:=True)) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(544995, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544995"), WorkItem(545283, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545283")> Public Async Function TestGenericType(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Interface C(Of In T) End Interface </Document> </Project> </Workspace>, host, Item("C(Of In T)", Glyph.InterfaceInternal, bolded:=True)) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545113, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545113")> Public Async Function TestMethodGroupWithGenericMethod(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub S() End Sub Sub S(Of T)() End Sub End Class </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, bolded:=False, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, bolded:=False, hasNavigationSymbolId:=False), Item("S()", Glyph.MethodPublic, bolded:=True), Item("S(Of T)()", Glyph.MethodPublic, bolded:=True)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545113, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545113")> Public Async Function TestSingleGenericMethod(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub S(Of T)() End Sub End Class </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, bolded:=False, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, bolded:=False, hasNavigationSymbolId:=False), Item("S(Of T)()", Glyph.MethodPublic, bolded:=True)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545285, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545285")> Public Async Function TestSingleGenericFunction(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Function S(Of T)() As Integer End Sub End Class </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, bolded:=False, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, bolded:=False, hasNavigationSymbolId:=False), Item("S(Of T)() As Integer", Glyph.MethodPublic, bolded:=True)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar)> Public Async Function TestSingleNonGenericMethod(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub S(arg As Integer) End Sub End Class </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, bolded:=False, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, bolded:=False, hasNavigationSymbolId:=False), Item("S", Glyph.MethodPublic, bolded:=True)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(544994, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544994")> Public Async Function TestSelectedItemForNestedClass(host As TestHost) As Task Await AssertSelectedItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Class Nested $$ End Class End Class </Document> </Project> </Workspace>, host, Item("Nested (C)", Glyph.ClassPublic, bolded:=True), False, Nothing, False) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(899330, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/899330")> Public Async Function TestSelectedItemForNestedClassAlphabeticallyBeforeContainingClass(host As TestHost) As Task Await AssertSelectedItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Z Class Nested $$ End Class End Class </Document> </Project> </Workspace>, host, Item("Nested (Z)", Glyph.ClassPublic, bolded:=True), False, Nothing, False) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(544990, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544990")> Public Async Function TestFinalizer(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Protected Overrides Sub Finalize() End Class End Class </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, bolded:=True)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(556, "https://github.com/dotnet/roslyn/issues/556")> Public Async Function TestFieldsAndConstants(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Private Const Co = 1 Private F As Integer End Class </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False), Item("Co", Glyph.ConstantPrivate, bolded:=True), Item("F", Glyph.FieldPrivate, bolded:=True)})) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(544988, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544988")> Public Async Function TestGenerateFinalizer(host As TestHost) As Task Await AssertGeneratedResultIsAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C End Class </Document> </Project> </Workspace>, host, "C", "Finalize", <Result> Class C Protected Overrides Sub Finalize() MyBase.Finalize() End Sub End Class </Result>) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar)> Public Async Function TestGenerateConstructor(host As TestHost) As Task Await AssertGeneratedResultIsAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C End Class </Document> </Project> </Workspace>, host, "C", "New", <Result> Class C Public Sub New() End Sub End Class </Result>) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar)> Public Async Function TestGenerateConstructorInDesignerGeneratedFile(host As TestHost) As Task Await AssertGeneratedResultIsAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> &lt;Microsoft.VisualBasic.CompilerServices.DesignerGeneratedAttribute&gt; Class C Sub InitializeComponent() End Sub End Class </Document> </Project> </Workspace>, host, "C", "New", <Result> &lt;Microsoft.VisualBasic.CompilerServices.DesignerGeneratedAttribute&gt; Class C Public Sub New() ' <%= VBEditorResources.This_call_is_required_by_the_designer %> InitializeComponent() ' <%= VBEditorResources.Add_any_initialization_after_the_InitializeComponent_call %> End Sub Sub InitializeComponent() End Sub End Class </Result>) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar)> Public Async Function TestGeneratePartialMethod(host As TestHost) As Task Await AssertGeneratedResultIsAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Partial Class C End Class </Document> <Document> Partial Class C Private Partial Sub Goo() End Sub End Class </Document> </Project> </Workspace>, host, "C", "Goo", <Result> Partial Class C Private Sub Goo() End Sub End Class </Result>) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar)> Public Async Function TestPartialMethodInDifferentFile(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Partial Class C End Class </Document> <Document> Partial Class C Sub Goo() End Sub End Class </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False), Item("Goo", Glyph.MethodPublic, grayed:=True)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(544991, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544991")> Public Async Function TestWithEventsField(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Private WithEvents goo As System.Console End Class </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False)}), Item("goo", Glyph.FieldPrivate, bolded:=False, hasNavigationSymbolId:=False, indent:=1, children:={ Item("CancelKeyPress", Glyph.EventPublic, hasNavigationSymbolId:=False)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(1185589, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1185589")> Public Async Function TestWithEventsField_EventsFromInheritedInterfaces(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Interface I1 Event I1Event(sender As Object, e As EventArgs) End Interface Interface I2 Event I2Event(sender As Object, e As EventArgs) End Interface Interface I3 Inherits I1, I2 Event I3Event(sender As Object, e As EventArgs) End Interface Class Test WithEvents i3 As I3 End Class </Document> </Project> </Workspace>, host, Item("I1", Glyph.InterfaceInternal, bolded:=True, children:={ Item("I1Event", Glyph.EventPublic, bolded:=True)}), Item("I2", Glyph.InterfaceInternal, bolded:=True, children:={ Item("I2Event", Glyph.EventPublic, bolded:=True)}), Item("I3", Glyph.InterfaceInternal, bolded:=True, children:={ Item("I3Event", Glyph.EventPublic, bolded:=True)}), Item("Test", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False)}), Item("i3", Glyph.FieldPrivate, hasNavigationSymbolId:=False, indent:=1, children:={ Item("I1Event", Glyph.EventPublic, hasNavigationSymbolId:=False), Item("I2Event", Glyph.EventPublic, hasNavigationSymbolId:=False), Item("I3Event", Glyph.EventPublic, hasNavigationSymbolId:=False)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(1185589, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1185589"), WorkItem(530506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530506")> Public Async Function TestDoNotIncludeShadowedEvents(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class B Event E(sender As Object, e As EventArgs) End Class Class C Inherits B Shadows Event E(sender As Object, e As EventArgs) End Class Class Test WithEvents c As C End Class </Document> </Project> </Workspace>, host, Item("B", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False), Item("E", Glyph.EventPublic, bolded:=True)}), Item(String.Format(VBFeaturesResources._0_Events, "B"), Glyph.EventPublic, hasNavigationSymbolId:=False, indent:=1, children:={ Item("E", Glyph.EventPublic, hasNavigationSymbolId:=False)}), Item("C", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False), Item("E", Glyph.EventPublic, bolded:=True)}), Item(String.Format(VBFeaturesResources._0_Events, "C"), Glyph.EventPublic, hasNavigationSymbolId:=False, indent:=1, children:={ Item("E", Glyph.EventPublic, hasNavigationSymbolId:=False)}), ' Only one E under the "(C Events)" node Item("Test", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False)}), Item("c", Glyph.FieldPrivate, hasNavigationSymbolId:=False, indent:=1, children:={ Item("E", Glyph.EventPublic, hasNavigationSymbolId:=False)})) ' Only one E for WithEvents handling End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(1185589, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1185589"), WorkItem(530506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530506")> Public Async Function TestEventList_EnsureInternalEventsInEventListAndInInheritedEventList(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Event E() End Class Class D Inherits C End Class </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False), Item("E", Glyph.EventPublic, bolded:=True)}), Item(String.Format(VBFeaturesResources._0_Events, "C"), Glyph.EventPublic, hasNavigationSymbolId:=False, indent:=1, children:={ Item("E", Glyph.EventPublic, hasNavigationSymbolId:=False)}), Item("D", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False)}), Item(String.Format(VBFeaturesResources._0_Events, "D"), Glyph.EventPublic, hasNavigationSymbolId:=False, indent:=1, children:={ Item("E", Glyph.EventPublic, hasNavigationSymbolId:=False)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(1185589, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1185589"), WorkItem(530506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530506")> Public Async Function TestEventList_EnsurePrivateEventsInEventListButNotInInheritedEventList(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Private Event E() End Class Class D Inherits C End Class </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False), Item("E", Glyph.EventPrivate, bolded:=True)}), Item(String.Format(VBFeaturesResources._0_Events, "C"), Glyph.EventPublic, hasNavigationSymbolId:=False, indent:=1, children:={ Item("E", Glyph.EventPrivate, hasNavigationSymbolId:=False)}), Item("D", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(1185589, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1185589"), WorkItem(530506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530506")> Public Async Function TestEventList_TestAccessibilityThroughNestedAndDerivedTypes(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Public Event E0() Protected Event E1() Private Event E2() Class N1 Class N2 Inherits C End Class End Class End Class Class D2 Inherits C End Class Class T WithEvents c As C End Class </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False), Item("E0", Glyph.EventPublic, bolded:=True), Item("E1", Glyph.EventProtected, bolded:=True), Item("E2", Glyph.EventPrivate, bolded:=True)}), Item(String.Format(VBFeaturesResources._0_Events, "C"), Glyph.EventPublic, hasNavigationSymbolId:=False, indent:=1, children:={ Item("E0", Glyph.EventPublic, hasNavigationSymbolId:=False), Item("E1", Glyph.EventProtected, hasNavigationSymbolId:=False), Item("E2", Glyph.EventPrivate, hasNavigationSymbolId:=False)}), Item("D2", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False)}), Item(String.Format(VBFeaturesResources._0_Events, "D2"), Glyph.EventPublic, hasNavigationSymbolId:=False, indent:=1, children:={ Item("E0", Glyph.EventPublic, hasNavigationSymbolId:=False), Item("E1", Glyph.EventProtected, hasNavigationSymbolId:=False)}), Item("N1 (C)", Glyph.ClassPublic, bolded:=True, children:={ Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False)}), Item("N2 (C.N1)", Glyph.ClassPublic, bolded:=True, children:={ Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False)}), Item(String.Format(VBFeaturesResources._0_Events, "N2"), Glyph.EventPublic, hasNavigationSymbolId:=False, indent:=1, children:={ Item("E0", Glyph.EventPublic, hasNavigationSymbolId:=False), Item("E1", Glyph.EventProtected, hasNavigationSymbolId:=False), Item("E2", Glyph.EventPrivate, hasNavigationSymbolId:=False)}), Item("T", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False)}), Item("c", Glyph.FieldPrivate, hasNavigationSymbolId:=False, indent:=1, children:={ Item("E0", Glyph.EventPublic, hasNavigationSymbolId:=False)})) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar)> Public Async Function TestGenerateEventHandler(host As TestHost) As Task Await AssertGeneratedResultIsAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Private WithEvents goo As System.Console End Class </Document> </Project> </Workspace>, host, "goo", "CancelKeyPress", <Result> Class C Private WithEvents goo As System.Console Private Sub goo_CancelKeyPress(sender As Object, e As ConsoleCancelEventArgs) Handles goo.CancelKeyPress End Sub End Class </Result>) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(529946, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529946")> Public Async Function TestGenerateEventHandlerWithEscapedName(host As TestHost) As Task Await AssertGeneratedResultIsAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Event [Rem] As System.Action End Class </Document> </Project> </Workspace>, host, String.Format(VBFeaturesResources._0_Events, "C"), "Rem", <Result> Class C Event [Rem] As System.Action Private Sub C_Rem() Handles Me.[Rem] End Sub End Class </Result>) End Function <WorkItem(546152, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546152")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar)> Public Async Function TestGenerateEventHandlerWithRemName(host As TestHost) As Task Await AssertGeneratedResultIsAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports System Class C Event E As Action WithEvents [Rem] As C End Class </Document> </Project> </Workspace>, host, "Rem", "E", <Result> Imports System Class C Event E As Action WithEvents [Rem] As C Private Sub Rem_E() Handles [Rem].E End Sub End Class </Result>) End Function <ConditionalWpfTheory(GetType(IsEnglishLocal)), CombinatorialData> <WorkItem(25763, "https://github.com/dotnet/roslyn/issues/25763")> <WorkItem(18792, "https://github.com/dotnet/roslyn/issues/18792")> <Trait(Traits.Feature, Traits.Features.NavigationBar)> Public Async Function TestGenerateEventHandlerWithDuplicate(host As TestHost) As Task Await AssertGeneratedResultIsAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Public Class ExampleClass Public Event ExampleEvent() Public Event ExampleEvent() End Class </Document> </Project> </Workspace>, host, $"(ExampleClass { FeaturesResources.Events })", Function(items) items.First(Function(i) i.Text = "ExampleEvent"), <Result> Public Class ExampleClass Public Event ExampleEvent() Public Event ExampleEvent() Private Sub ExampleClass_ExampleEvent() Handles Me.ExampleEvent End Sub End Class </Result>) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar)> Public Async Function TestNoListedEventToGenerateWithInvalidTypeName(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Event BindingError As System.FogBar End Class </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, children:={ Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False), Item("BindingError", Glyph.EventPublic, hasNavigationSymbolId:=True, bolded:=True)}, bolded:=True)) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(530657, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530657")> Public Async Function TestCodeGenerationItemsShouldNotAppearWhenWorkspaceDoesNotSupportDocumentChanges(host As TestHost) As Task Dim workspaceSupportsChangeDocument = False Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Partial Class C Private WithEvents M As System.Console End Class Partial Class C Partial Private Sub S() End Sub End Class </Document> </Project> </Workspace>, host, workspaceSupportsChangeDocument, Item("C", Glyph.ClassInternal, bolded:=True), Item("M", Glyph.FieldPrivate, indent:=1, hasNavigationSymbolId:=False)) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545220, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545220")> Public Async Function TestEnum(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Enum MyEnum A B C End Enum </Document> </Project> </Workspace>, host, Item("MyEnum", Glyph.EnumInternal, children:={ Item("A", Glyph.EnumMemberPublic), Item("B", Glyph.EnumMemberPublic), Item("C", Glyph.EnumMemberPublic)}, bolded:=True)) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar)> Public Async Function TestEvents(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Public Class Base Public WithEvents o1 As New Class1 Public WithEvents o2 As New Class1 Public Class Class1 ' Declare an event. Public Event Ev_Event() End Class $$ Sub EventHandler() Handles o1.Ev_Event End Sub End Class </Document> </Project> </Workspace>, host, Item("Base", Glyph.ClassPublic, children:={ Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False)}, bolded:=True), Item("o1", Glyph.FieldPublic, children:={ Item("Ev_Event", Glyph.EventPublic, bolded:=True)}, bolded:=False, hasNavigationSymbolId:=False, indent:=1), Item("o2", Glyph.FieldPublic, children:={ Item("Ev_Event", Glyph.EventPublic, hasNavigationSymbolId:=False)}, bolded:=False, hasNavigationSymbolId:=False, indent:=1), Item("Class1 (Base)", Glyph.ClassPublic, children:={ Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False), Item("Ev_Event", Glyph.EventPublic, bolded:=True)}, bolded:=True), Item(String.Format(VBFeaturesResources._0_Events, "Class1"), Glyph.EventPublic, children:={ Item("Ev_Event", Glyph.EventPublic, hasNavigationSymbolId:=False)}, bolded:=False, indent:=1, hasNavigationSymbolId:=False)) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar)> Public Async Function TestNavigationBetweenFiles(host As TestHost) As Task Await AssertNavigationPointAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document FilePath="Source.vb"> Partial Class Program Sub StartingFile() End Sub End Class </Document> <Document FilePath="Sink.vb"> Partial Class Program Sub MethodThatWastesTwoLines() End Sub Sub TargetMethod() $$End Sub End Class </Document> </Project> </Workspace>, host, startingDocumentFilePath:="Source.vb", leftItemToSelectText:="Program", rightItemToSelectText:="TargetMethod") End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(566752, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/566752")> Public Async Function TestNavigationWithMethodWithLineContinuation(host As TestHost) As Task Await AssertNavigationPointAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document FilePath="Code.vb"> Partial Class Program Private Iterator Function SomeNumbers() _ As System.Collections.IEnumerable $$Yield 3 Yield 5 Yield 8 End Function End Class </Document> </Project> </Workspace>, host, startingDocumentFilePath:="Code.vb", leftItemToSelectText:="Program", rightItemToSelectText:="SomeNumbers") End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(531586, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531586")> Public Async Function TestNavigationWithMethodWithNoTerminator(host As TestHost) As Task Await AssertNavigationPointAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document FilePath="Code.vb"> Partial Class Program $$Private Sub S() End Class </Document> </Project> </Workspace>, host, startingDocumentFilePath:="Code.vb", leftItemToSelectText:="Program", rightItemToSelectText:="S") End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(531586, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531586")> Public Async Function TestNavigationWithMethodWithDocumentationComment(host As TestHost) As Task Await AssertNavigationPointAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document FilePath="Code.vb"><![CDATA[ Partial Class Program ''' <summary></summary> $$Private Sub S() End Class ]]></Document> </Project> </Workspace>, host, startingDocumentFilePath:="Code.vb", leftItemToSelectText:="Program", rightItemToSelectText:="S") End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(567914, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/567914")> Public Async Function TestNavigationWithMethodWithMultipleLineDeclaration(host As TestHost) As Task Await AssertNavigationPointAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document FilePath="Code.vb"> Partial Class Program Private Sub S( value As Integer ) $$Exit Sub End Sub End Class </Document> </Project> </Workspace>, host, startingDocumentFilePath:="Code.vb", leftItemToSelectText:="Program", rightItemToSelectText:="S") End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(605074, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/605074")> Public Async Function TestNavigationWithMethodContainingComment(host As TestHost) As Task Await AssertNavigationPointAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document FilePath="Code.vb"> Partial Class Program Private Sub S(value As Integer) $$' Goo End Sub End Class </Document> </Project> </Workspace>, host, startingDocumentFilePath:="Code.vb", leftItemToSelectText:="Program", rightItemToSelectText:="S") End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(605074, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/605074")> Public Async Function TestNavigationWithMethodContainingBlankLineWithSpaces(host As TestHost) As Task Await AssertNavigationPointAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document FilePath="Code.vb"> Partial Class Program Private Sub S(value As Integer) $$ End Sub End Class </Document> </Project> </Workspace>, host, startingDocumentFilePath:="Code.vb", leftItemToSelectText:="Program", rightItemToSelectText:="S") End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(605074, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/605074")> Public Async Function TestNavigationWithMethodContainingBlankLineWithNoSpaces(host As TestHost) As Task Await AssertNavigationPointAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document FilePath="Code.vb"> Partial Class Program Private Sub S(value As Integer) $$ End Sub End Class </Document> </Project> </Workspace>, host, startingDocumentFilePath:="Code.vb", leftItemToSelectText:="Program", rightItemToSelectText:="S", expectedVirtualSpace:=8) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(605074, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/605074")> Public Async Function TestNavigationWithMethodContainingBlankLineWithSomeSpaces(host As TestHost) As Task Await AssertNavigationPointAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document FilePath="Code.vb"> Partial Class Program Private Sub S(value As Integer) $$ End Sub End Class </Document> </Project> </Workspace>, host, startingDocumentFilePath:="Code.vb", leftItemToSelectText:="Program", rightItemToSelectText:="S", expectedVirtualSpace:=4) End Function <WorkItem(187865, "https://devdiv.visualstudio.com:443/defaultcollection/DevDiv/_workitems/edit/187865")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar)> Public Async Function DifferentMembersMetadataName(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Function Get_P(o As Object) As Object Return od End Function ReadOnly Property P As Object Get Return Nothing End Get End Property End Class </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, bolded:=False, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, bolded:=False, hasNavigationSymbolId:=False), Item("Get_P", Glyph.MethodPublic, bolded:=True), Item("P", Glyph.PropertyPublic, bolded:=True)})) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(37621, "https://github.com/dotnet/roslyn/issues/37621")> Public Async Function TestGenerateEventWithAttributedDelegateType(host As TestHost) As Task Await AssertGeneratedResultIsAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <ProjectReference>LibraryWithInaccessibleAttribute</ProjectReference> <Document> Class C Inherits BaseType End Class </Document> </Project> <Project Language="Visual Basic" Name="LibraryWithInaccessibleAttribute" CommonReferences="true"> <Document><![CDATA[[ Friend Class AttributeType Inherits Attribute End Class Delegate Sub DelegateType(<AttributeType> parameterWithInaccessibleAttribute As Object) Public Class BaseType Public Event E As DelegateType End Class ]]></Document></Project> </Workspace>, host, String.Format(VBFeaturesResources._0_Events, "C"), "E", <Result> Class C Inherits BaseType Private Sub C_E(parameterWithInaccessibleAttribute As Object) Handles Me.E End Sub End Class </Result>) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.Editor.VisualBasic Imports Microsoft.CodeAnalysis.Remote.Testing Imports Microsoft.CodeAnalysis.VisualBasic Namespace Microsoft.CodeAnalysis.Editor.UnitTests.NavigationBar <[UseExportProvider]> Partial Public Class VisualBasicNavigationBarTests <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545000, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545000")> Public Async Function TestEventsInInterfaces(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Interface I Event Goo As EventHandler End Interface </Document> </Project> </Workspace>, host, Item("I", Glyph.InterfaceInternal, bolded:=True, children:={ Item("Goo", Glyph.EventPublic, bolded:=True)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(544996, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544996")> Public Async Function TestEmptyStructure(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Structure S End Structure </Document> </Project> </Workspace>, host, Item("S", Glyph.StructureInternal, bolded:=True, children:={})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(544996, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544996")> Public Async Function TestEmptyInterface(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Interface I End Interface </Document> </Project> </Workspace>, host, Item("I", Glyph.InterfaceInternal, bolded:=True, children:={})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(797455, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/797455")> Public Async Function TestUserDefinedOperators(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Shared Operator -(x As C, y As C) As C End Operator Shared Operator +(x As C, y As C) As C End Operator Shared Operator +(x As C, y As Integer) As C End Operator End Class </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, bolded:=False, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, bolded:=False, hasNavigationSymbolId:=False), Item("Operator +(C, C) As C", Glyph.Operator, bolded:=True), Item("Operator +(C, Integer) As C", Glyph.Operator, bolded:=True), Item("Operator -", Glyph.Operator, bolded:=True)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(797455, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/797455")> Public Async Function TestSingleConversion(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Shared Narrowing Operator CType(x As C) As Integer End Operator End Class </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, bolded:=False, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, bolded:=False, hasNavigationSymbolId:=False), Item("Narrowing Operator CType", Glyph.Operator, bolded:=True)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(797455, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/797455")> Public Async Function TestMultipleConversions(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Shared Narrowing Operator CType(x As C) As Integer End Operator Shared Narrowing Operator CType(x As C) As String End Operator End Class </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, bolded:=False, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, bolded:=False, hasNavigationSymbolId:=False), Item("Narrowing Operator CType(C) As Integer", Glyph.Operator, bolded:=True), Item("Narrowing Operator CType(C) As String", Glyph.Operator, bolded:=True)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(544993, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544993")> Public Async Function TestNestedClass(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Namespace N Class C Class Nested End Class End Class End Namespace </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, bolded:=True), Item("Nested (N.C)", Glyph.ClassPublic, bolded:=True)) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(544997, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544997")> Public Async Function TestDelegate(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Delegate Sub Goo() </Document> </Project> </Workspace>, host, Item("Goo", Glyph.DelegateInternal, children:={}, bolded:=True)) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(544995, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544995"), WorkItem(545283, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545283")> Public Async Function TestGenericType(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Interface C(Of In T) End Interface </Document> </Project> </Workspace>, host, Item("C(Of In T)", Glyph.InterfaceInternal, bolded:=True)) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545113, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545113")> Public Async Function TestMethodGroupWithGenericMethod(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub S() End Sub Sub S(Of T)() End Sub End Class </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, bolded:=False, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, bolded:=False, hasNavigationSymbolId:=False), Item("S()", Glyph.MethodPublic, bolded:=True), Item("S(Of T)()", Glyph.MethodPublic, bolded:=True)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545113, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545113")> Public Async Function TestSingleGenericMethod(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub S(Of T)() End Sub End Class </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, bolded:=False, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, bolded:=False, hasNavigationSymbolId:=False), Item("S(Of T)()", Glyph.MethodPublic, bolded:=True)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545285, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545285")> Public Async Function TestSingleGenericFunction(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Function S(Of T)() As Integer End Sub End Class </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, bolded:=False, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, bolded:=False, hasNavigationSymbolId:=False), Item("S(Of T)() As Integer", Glyph.MethodPublic, bolded:=True)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar)> Public Async Function TestSingleNonGenericMethod(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub S(arg As Integer) End Sub End Class </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, bolded:=False, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, bolded:=False, hasNavigationSymbolId:=False), Item("S", Glyph.MethodPublic, bolded:=True)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(544994, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544994")> Public Async Function TestSelectedItemForNestedClass(host As TestHost) As Task Await AssertSelectedItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Class Nested $$ End Class End Class </Document> </Project> </Workspace>, host, Item("Nested (C)", Glyph.ClassPublic, bolded:=True), False, Nothing, False) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(899330, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/899330")> Public Async Function TestSelectedItemForNestedClassAlphabeticallyBeforeContainingClass(host As TestHost) As Task Await AssertSelectedItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Z Class Nested $$ End Class End Class </Document> </Project> </Workspace>, host, Item("Nested (Z)", Glyph.ClassPublic, bolded:=True), False, Nothing, False) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(544990, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544990")> Public Async Function TestFinalizer(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Protected Overrides Sub Finalize() End Class End Class </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, bolded:=True)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(556, "https://github.com/dotnet/roslyn/issues/556")> Public Async Function TestFieldsAndConstants(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Private Const Co = 1 Private F As Integer End Class </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False), Item("Co", Glyph.ConstantPrivate, bolded:=True), Item("F", Glyph.FieldPrivate, bolded:=True)})) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(544988, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544988")> Public Async Function TestGenerateFinalizer(host As TestHost) As Task Await AssertGeneratedResultIsAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C End Class </Document> </Project> </Workspace>, host, "C", "Finalize", <Result> Class C Protected Overrides Sub Finalize() MyBase.Finalize() End Sub End Class </Result>) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar)> Public Async Function TestGenerateConstructor(host As TestHost) As Task Await AssertGeneratedResultIsAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C End Class </Document> </Project> </Workspace>, host, "C", "New", <Result> Class C Public Sub New() End Sub End Class </Result>) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar)> Public Async Function TestGenerateConstructorInDesignerGeneratedFile(host As TestHost) As Task Await AssertGeneratedResultIsAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> &lt;Microsoft.VisualBasic.CompilerServices.DesignerGeneratedAttribute&gt; Class C Sub InitializeComponent() End Sub End Class </Document> </Project> </Workspace>, host, "C", "New", <Result> &lt;Microsoft.VisualBasic.CompilerServices.DesignerGeneratedAttribute&gt; Class C Public Sub New() ' <%= VBEditorResources.This_call_is_required_by_the_designer %> InitializeComponent() ' <%= VBEditorResources.Add_any_initialization_after_the_InitializeComponent_call %> End Sub Sub InitializeComponent() End Sub End Class </Result>) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar)> Public Async Function TestGeneratePartialMethod(host As TestHost) As Task Await AssertGeneratedResultIsAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Partial Class C End Class </Document> <Document> Partial Class C Private Partial Sub Goo() End Sub End Class </Document> </Project> </Workspace>, host, "C", "Goo", <Result> Partial Class C Private Sub Goo() End Sub End Class </Result>) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar)> Public Async Function TestPartialMethodInDifferentFile(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Partial Class C End Class </Document> <Document> Partial Class C Sub Goo() End Sub End Class </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False), Item("Goo", Glyph.MethodPublic, grayed:=True)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(544991, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544991")> Public Async Function TestWithEventsField(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Private WithEvents goo As System.Console End Class </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False)}), Item("goo", Glyph.FieldPrivate, bolded:=False, hasNavigationSymbolId:=False, indent:=1, children:={ Item("CancelKeyPress", Glyph.EventPublic, hasNavigationSymbolId:=False)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(1185589, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1185589")> Public Async Function TestWithEventsField_EventsFromInheritedInterfaces(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Interface I1 Event I1Event(sender As Object, e As EventArgs) End Interface Interface I2 Event I2Event(sender As Object, e As EventArgs) End Interface Interface I3 Inherits I1, I2 Event I3Event(sender As Object, e As EventArgs) End Interface Class Test WithEvents i3 As I3 End Class </Document> </Project> </Workspace>, host, Item("I1", Glyph.InterfaceInternal, bolded:=True, children:={ Item("I1Event", Glyph.EventPublic, bolded:=True)}), Item("I2", Glyph.InterfaceInternal, bolded:=True, children:={ Item("I2Event", Glyph.EventPublic, bolded:=True)}), Item("I3", Glyph.InterfaceInternal, bolded:=True, children:={ Item("I3Event", Glyph.EventPublic, bolded:=True)}), Item("Test", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False)}), Item("i3", Glyph.FieldPrivate, hasNavigationSymbolId:=False, indent:=1, children:={ Item("I1Event", Glyph.EventPublic, hasNavigationSymbolId:=False), Item("I2Event", Glyph.EventPublic, hasNavigationSymbolId:=False), Item("I3Event", Glyph.EventPublic, hasNavigationSymbolId:=False)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(1185589, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1185589"), WorkItem(530506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530506")> Public Async Function TestDoNotIncludeShadowedEvents(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class B Event E(sender As Object, e As EventArgs) End Class Class C Inherits B Shadows Event E(sender As Object, e As EventArgs) End Class Class Test WithEvents c As C End Class </Document> </Project> </Workspace>, host, Item("B", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False), Item("E", Glyph.EventPublic, bolded:=True)}), Item(String.Format(VBFeaturesResources._0_Events, "B"), Glyph.EventPublic, hasNavigationSymbolId:=False, indent:=1, children:={ Item("E", Glyph.EventPublic, hasNavigationSymbolId:=False)}), Item("C", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False), Item("E", Glyph.EventPublic, bolded:=True)}), Item(String.Format(VBFeaturesResources._0_Events, "C"), Glyph.EventPublic, hasNavigationSymbolId:=False, indent:=1, children:={ Item("E", Glyph.EventPublic, hasNavigationSymbolId:=False)}), ' Only one E under the "(C Events)" node Item("Test", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False)}), Item("c", Glyph.FieldPrivate, hasNavigationSymbolId:=False, indent:=1, children:={ Item("E", Glyph.EventPublic, hasNavigationSymbolId:=False)})) ' Only one E for WithEvents handling End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(1185589, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1185589"), WorkItem(530506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530506")> Public Async Function TestEventList_EnsureInternalEventsInEventListAndInInheritedEventList(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Event E() End Class Class D Inherits C End Class </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False), Item("E", Glyph.EventPublic, bolded:=True)}), Item(String.Format(VBFeaturesResources._0_Events, "C"), Glyph.EventPublic, hasNavigationSymbolId:=False, indent:=1, children:={ Item("E", Glyph.EventPublic, hasNavigationSymbolId:=False)}), Item("D", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False)}), Item(String.Format(VBFeaturesResources._0_Events, "D"), Glyph.EventPublic, hasNavigationSymbolId:=False, indent:=1, children:={ Item("E", Glyph.EventPublic, hasNavigationSymbolId:=False)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(1185589, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1185589"), WorkItem(530506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530506")> Public Async Function TestEventList_EnsurePrivateEventsInEventListButNotInInheritedEventList(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Private Event E() End Class Class D Inherits C End Class </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False), Item("E", Glyph.EventPrivate, bolded:=True)}), Item(String.Format(VBFeaturesResources._0_Events, "C"), Glyph.EventPublic, hasNavigationSymbolId:=False, indent:=1, children:={ Item("E", Glyph.EventPrivate, hasNavigationSymbolId:=False)}), Item("D", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(1185589, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1185589"), WorkItem(530506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530506")> Public Async Function TestEventList_TestAccessibilityThroughNestedAndDerivedTypes(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Public Event E0() Protected Event E1() Private Event E2() Class N1 Class N2 Inherits C End Class End Class End Class Class D2 Inherits C End Class Class T WithEvents c As C End Class </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False), Item("E0", Glyph.EventPublic, bolded:=True), Item("E1", Glyph.EventProtected, bolded:=True), Item("E2", Glyph.EventPrivate, bolded:=True)}), Item(String.Format(VBFeaturesResources._0_Events, "C"), Glyph.EventPublic, hasNavigationSymbolId:=False, indent:=1, children:={ Item("E0", Glyph.EventPublic, hasNavigationSymbolId:=False), Item("E1", Glyph.EventProtected, hasNavigationSymbolId:=False), Item("E2", Glyph.EventPrivate, hasNavigationSymbolId:=False)}), Item("D2", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False)}), Item(String.Format(VBFeaturesResources._0_Events, "D2"), Glyph.EventPublic, hasNavigationSymbolId:=False, indent:=1, children:={ Item("E0", Glyph.EventPublic, hasNavigationSymbolId:=False), Item("E1", Glyph.EventProtected, hasNavigationSymbolId:=False)}), Item("N1 (C)", Glyph.ClassPublic, bolded:=True, children:={ Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False)}), Item("N2 (C.N1)", Glyph.ClassPublic, bolded:=True, children:={ Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False)}), Item(String.Format(VBFeaturesResources._0_Events, "N2"), Glyph.EventPublic, hasNavigationSymbolId:=False, indent:=1, children:={ Item("E0", Glyph.EventPublic, hasNavigationSymbolId:=False), Item("E1", Glyph.EventProtected, hasNavigationSymbolId:=False), Item("E2", Glyph.EventPrivate, hasNavigationSymbolId:=False)}), Item("T", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False)}), Item("c", Glyph.FieldPrivate, hasNavigationSymbolId:=False, indent:=1, children:={ Item("E0", Glyph.EventPublic, hasNavigationSymbolId:=False)})) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar)> Public Async Function TestGenerateEventHandler(host As TestHost) As Task Await AssertGeneratedResultIsAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Private WithEvents goo As System.Console End Class </Document> </Project> </Workspace>, host, "goo", "CancelKeyPress", <Result> Class C Private WithEvents goo As System.Console Private Sub goo_CancelKeyPress(sender As Object, e As ConsoleCancelEventArgs) Handles goo.CancelKeyPress End Sub End Class </Result>) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(529946, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529946")> Public Async Function TestGenerateEventHandlerWithEscapedName(host As TestHost) As Task Await AssertGeneratedResultIsAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Event [Rem] As System.Action End Class </Document> </Project> </Workspace>, host, String.Format(VBFeaturesResources._0_Events, "C"), "Rem", <Result> Class C Event [Rem] As System.Action Private Sub C_Rem() Handles Me.[Rem] End Sub End Class </Result>) End Function <WorkItem(546152, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546152")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar)> Public Async Function TestGenerateEventHandlerWithRemName(host As TestHost) As Task Await AssertGeneratedResultIsAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports System Class C Event E As Action WithEvents [Rem] As C End Class </Document> </Project> </Workspace>, host, "Rem", "E", <Result> Imports System Class C Event E As Action WithEvents [Rem] As C Private Sub Rem_E() Handles [Rem].E End Sub End Class </Result>) End Function <ConditionalWpfTheory(GetType(IsEnglishLocal)), CombinatorialData> <WorkItem(25763, "https://github.com/dotnet/roslyn/issues/25763")> <WorkItem(18792, "https://github.com/dotnet/roslyn/issues/18792")> <Trait(Traits.Feature, Traits.Features.NavigationBar)> Public Async Function TestGenerateEventHandlerWithDuplicate(host As TestHost) As Task Await AssertGeneratedResultIsAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Public Class ExampleClass Public Event ExampleEvent() Public Event ExampleEvent() End Class </Document> </Project> </Workspace>, host, $"(ExampleClass { FeaturesResources.Events })", Function(items) items.First(Function(i) i.Text = "ExampleEvent"), <Result> Public Class ExampleClass Public Event ExampleEvent() Public Event ExampleEvent() Private Sub ExampleClass_ExampleEvent() Handles Me.ExampleEvent End Sub End Class </Result>) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar)> Public Async Function TestNoListedEventToGenerateWithInvalidTypeName(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Event BindingError As System.FogBar End Class </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, children:={ Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False), Item("BindingError", Glyph.EventPublic, hasNavigationSymbolId:=True, bolded:=True)}, bolded:=True)) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(530657, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530657")> Public Async Function TestCodeGenerationItemsShouldNotAppearWhenWorkspaceDoesNotSupportDocumentChanges(host As TestHost) As Task Dim workspaceSupportsChangeDocument = False Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Partial Class C Private WithEvents M As System.Console End Class Partial Class C Partial Private Sub S() End Sub End Class </Document> </Project> </Workspace>, host, workspaceSupportsChangeDocument, Item("C", Glyph.ClassInternal, bolded:=True), Item("M", Glyph.FieldPrivate, indent:=1, hasNavigationSymbolId:=False)) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545220, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545220")> Public Async Function TestEnum(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Enum MyEnum A B C End Enum </Document> </Project> </Workspace>, host, Item("MyEnum", Glyph.EnumInternal, children:={ Item("A", Glyph.EnumMemberPublic), Item("B", Glyph.EnumMemberPublic), Item("C", Glyph.EnumMemberPublic)}, bolded:=True)) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar)> Public Async Function TestEvents(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Public Class Base Public WithEvents o1 As New Class1 Public WithEvents o2 As New Class1 Public Class Class1 ' Declare an event. Public Event Ev_Event() End Class $$ Sub EventHandler() Handles o1.Ev_Event End Sub End Class </Document> </Project> </Workspace>, host, Item("Base", Glyph.ClassPublic, children:={ Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False)}, bolded:=True), Item("o1", Glyph.FieldPublic, children:={ Item("Ev_Event", Glyph.EventPublic, bolded:=True)}, bolded:=False, hasNavigationSymbolId:=False, indent:=1), Item("o2", Glyph.FieldPublic, children:={ Item("Ev_Event", Glyph.EventPublic, hasNavigationSymbolId:=False)}, bolded:=False, hasNavigationSymbolId:=False, indent:=1), Item("Class1 (Base)", Glyph.ClassPublic, children:={ Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False), Item("Ev_Event", Glyph.EventPublic, bolded:=True)}, bolded:=True), Item(String.Format(VBFeaturesResources._0_Events, "Class1"), Glyph.EventPublic, children:={ Item("Ev_Event", Glyph.EventPublic, hasNavigationSymbolId:=False)}, bolded:=False, indent:=1, hasNavigationSymbolId:=False)) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar)> Public Async Function TestNavigationBetweenFiles(host As TestHost) As Task Await AssertNavigationPointAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document FilePath="Source.vb"> Partial Class Program Sub StartingFile() End Sub End Class </Document> <Document FilePath="Sink.vb"> Partial Class Program Sub MethodThatWastesTwoLines() End Sub Sub TargetMethod() $$End Sub End Class </Document> </Project> </Workspace>, host, startingDocumentFilePath:="Source.vb", leftItemToSelectText:="Program", rightItemToSelectText:="TargetMethod") End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(566752, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/566752")> Public Async Function TestNavigationWithMethodWithLineContinuation(host As TestHost) As Task Await AssertNavigationPointAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document FilePath="Code.vb"> Partial Class Program Private Iterator Function SomeNumbers() _ As System.Collections.IEnumerable $$Yield 3 Yield 5 Yield 8 End Function End Class </Document> </Project> </Workspace>, host, startingDocumentFilePath:="Code.vb", leftItemToSelectText:="Program", rightItemToSelectText:="SomeNumbers") End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(531586, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531586")> Public Async Function TestNavigationWithMethodWithNoTerminator(host As TestHost) As Task Await AssertNavigationPointAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document FilePath="Code.vb"> Partial Class Program $$Private Sub S() End Class </Document> </Project> </Workspace>, host, startingDocumentFilePath:="Code.vb", leftItemToSelectText:="Program", rightItemToSelectText:="S") End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(531586, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531586")> Public Async Function TestNavigationWithMethodWithDocumentationComment(host As TestHost) As Task Await AssertNavigationPointAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document FilePath="Code.vb"><![CDATA[ Partial Class Program ''' <summary></summary> $$Private Sub S() End Class ]]></Document> </Project> </Workspace>, host, startingDocumentFilePath:="Code.vb", leftItemToSelectText:="Program", rightItemToSelectText:="S") End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(567914, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/567914")> Public Async Function TestNavigationWithMethodWithMultipleLineDeclaration(host As TestHost) As Task Await AssertNavigationPointAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document FilePath="Code.vb"> Partial Class Program Private Sub S( value As Integer ) $$Exit Sub End Sub End Class </Document> </Project> </Workspace>, host, startingDocumentFilePath:="Code.vb", leftItemToSelectText:="Program", rightItemToSelectText:="S") End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(605074, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/605074")> Public Async Function TestNavigationWithMethodContainingComment(host As TestHost) As Task Await AssertNavigationPointAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document FilePath="Code.vb"> Partial Class Program Private Sub S(value As Integer) $$' Goo End Sub End Class </Document> </Project> </Workspace>, host, startingDocumentFilePath:="Code.vb", leftItemToSelectText:="Program", rightItemToSelectText:="S") End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(605074, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/605074")> Public Async Function TestNavigationWithMethodContainingBlankLineWithSpaces(host As TestHost) As Task Await AssertNavigationPointAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document FilePath="Code.vb"> Partial Class Program Private Sub S(value As Integer) $$ End Sub End Class </Document> </Project> </Workspace>, host, startingDocumentFilePath:="Code.vb", leftItemToSelectText:="Program", rightItemToSelectText:="S") End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(605074, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/605074")> Public Async Function TestNavigationWithMethodContainingBlankLineWithNoSpaces(host As TestHost) As Task Await AssertNavigationPointAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document FilePath="Code.vb"> Partial Class Program Private Sub S(value As Integer) $$ End Sub End Class </Document> </Project> </Workspace>, host, startingDocumentFilePath:="Code.vb", leftItemToSelectText:="Program", rightItemToSelectText:="S", expectedVirtualSpace:=8) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(605074, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/605074")> Public Async Function TestNavigationWithMethodContainingBlankLineWithSomeSpaces(host As TestHost) As Task Await AssertNavigationPointAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document FilePath="Code.vb"> Partial Class Program Private Sub S(value As Integer) $$ End Sub End Class </Document> </Project> </Workspace>, host, startingDocumentFilePath:="Code.vb", leftItemToSelectText:="Program", rightItemToSelectText:="S", expectedVirtualSpace:=4) End Function <WorkItem(187865, "https://devdiv.visualstudio.com:443/defaultcollection/DevDiv/_workitems/edit/187865")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar)> Public Async Function DifferentMembersMetadataName(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Function Get_P(o As Object) As Object Return od End Function ReadOnly Property P As Object Get Return Nothing End Get End Property End Class </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, bolded:=False, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, bolded:=False, hasNavigationSymbolId:=False), Item("Get_P", Glyph.MethodPublic, bolded:=True), Item("P", Glyph.PropertyPublic, bolded:=True)})) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(37621, "https://github.com/dotnet/roslyn/issues/37621")> Public Async Function TestGenerateEventWithAttributedDelegateType(host As TestHost) As Task Await AssertGeneratedResultIsAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <ProjectReference>LibraryWithInaccessibleAttribute</ProjectReference> <Document> Class C Inherits BaseType End Class </Document> </Project> <Project Language="Visual Basic" Name="LibraryWithInaccessibleAttribute" CommonReferences="true"> <Document><![CDATA[[ Friend Class AttributeType Inherits Attribute End Class Delegate Sub DelegateType(<AttributeType> parameterWithInaccessibleAttribute As Object) Public Class BaseType Public Event E As DelegateType End Class ]]></Document></Project> </Workspace>, host, String.Format(VBFeaturesResources._0_Events, "C"), "E", <Result> Class C Inherits BaseType Private Sub C_E(parameterWithInaccessibleAttribute As Object) Handles Me.E End Sub End Class </Result>) End Function End Class End Namespace
-1
dotnet/roslyn
56,011
React to string comparison changing on .NET Core
The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
jaredpar
"2021-08-30T17:18:52Z"
"2021-08-30T20:20:04Z"
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
4d99cda6e446e77dbb302e26388c1093bd3ef569
React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
./src/Workspaces/VisualBasic/Portable/Classification/ClassificationHelpers.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading Imports Microsoft.CodeAnalysis.Classification Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.Classification Friend Module ClassificationHelpers ''' <summary> ''' Return the classification type associated with this token. ''' </summary> ''' <param name="token">The token to be classified.</param> ''' <returns>The classification type for the token</returns> ''' <remarks></remarks> Public Function GetClassification(token As SyntaxToken) As String If IsControlKeyword(token) Then Return ClassificationTypeNames.ControlKeyword ElseIf SyntaxFacts.IsKeywordKind(token.Kind) Then Return ClassificationTypeNames.Keyword ElseIf IsStringToken(token) Then Return ClassificationTypeNames.StringLiteral ElseIf SyntaxFacts.IsPunctuation(token.Kind) Then Return ClassifyPunctuation(token) ElseIf token.Kind = SyntaxKind.IdentifierToken Then Return ClassifyIdentifierSyntax(token) ElseIf token.IsNumericLiteral() Then Return ClassificationTypeNames.NumericLiteral ElseIf token.Kind = SyntaxKind.XmlNameToken Then Return ClassificationTypeNames.XmlLiteralName ElseIf token.Kind = SyntaxKind.XmlTextLiteralToken Then Select Case token.Parent.Kind Case SyntaxKind.XmlString Return ClassificationTypeNames.XmlLiteralAttributeValue Case SyntaxKind.XmlProcessingInstruction Return ClassificationTypeNames.XmlLiteralProcessingInstruction Case SyntaxKind.XmlComment Return ClassificationTypeNames.XmlLiteralComment Case SyntaxKind.XmlCDataSection Return ClassificationTypeNames.XmlLiteralCDataSection Case Else Return ClassificationTypeNames.XmlLiteralText End Select ElseIf token.Kind = SyntaxKind.XmlEntityLiteralToken Then Return ClassificationTypeNames.XmlLiteralEntityReference ElseIf token.IsKind(SyntaxKind.None, SyntaxKind.BadToken) Then Return Nothing Else throw ExceptionUtilities.UnexpectedValue(token.Kind()) End If End Function Private Function IsControlKeyword(token As SyntaxToken) As Boolean If token.Parent Is Nothing Then Return False End If ' For Exit Statments classify everything as a control keyword If token.Parent.IsKind( SyntaxKind.ExitFunctionStatement, SyntaxKind.ExitOperatorStatement, SyntaxKind.ExitPropertyStatement, SyntaxKind.ExitSubStatement) Then Return True End If ' Control keywords are used in other contexts so check that it is ' being used in a supported context. Return IsControlKeywordKind(token.Kind) AndAlso IsControlStatementKind(token.Parent.Kind) End Function ''' <summary> ''' Determine if the kind represents a control keyword ''' </summary> Private Function IsControlKeywordKind(kind As SyntaxKind) As Boolean Select Case kind Case _ SyntaxKind.CaseKeyword, SyntaxKind.CatchKeyword, SyntaxKind.ContinueKeyword, SyntaxKind.DoKeyword, SyntaxKind.EachKeyword, SyntaxKind.ElseKeyword, SyntaxKind.ElseIfKeyword, SyntaxKind.EndKeyword, SyntaxKind.ExitKeyword, SyntaxKind.FinallyKeyword, SyntaxKind.ForKeyword, SyntaxKind.GoToKeyword, SyntaxKind.IfKeyword, SyntaxKind.InKeyword, SyntaxKind.LoopKeyword, SyntaxKind.NextKeyword, SyntaxKind.ResumeKeyword, SyntaxKind.ReturnKeyword, SyntaxKind.SelectKeyword, SyntaxKind.ThenKeyword, SyntaxKind.TryKeyword, SyntaxKind.WhileKeyword, SyntaxKind.WendKeyword, SyntaxKind.UntilKeyword, SyntaxKind.EndIfKeyword, SyntaxKind.GosubKeyword, SyntaxKind.YieldKeyword, SyntaxKind.ToKeyword Return True Case Else Return False End Select End Function ''' <summary> ''' Determine if the kind represents a control statement ''' </summary> Private Function IsControlStatementKind(kind As SyntaxKind) As Boolean Select Case kind Case _ SyntaxKind.CallStatement, SyntaxKind.CaseElseStatement, SyntaxKind.CaseStatement, SyntaxKind.CatchStatement, SyntaxKind.ContinueDoStatement, SyntaxKind.ContinueForStatement, SyntaxKind.ContinueWhileStatement, SyntaxKind.DoUntilStatement, SyntaxKind.DoWhileStatement, SyntaxKind.ElseIfStatement, SyntaxKind.ElseStatement, SyntaxKind.EndIfStatement, SyntaxKind.EndSelectStatement, SyntaxKind.EndTryStatement, SyntaxKind.EndWhileStatement, SyntaxKind.ExitDoStatement, SyntaxKind.ExitForStatement, SyntaxKind.ExitSelectStatement, SyntaxKind.ExitTryStatement, SyntaxKind.ExitWhileStatement, SyntaxKind.FinallyStatement, SyntaxKind.ForEachStatement, SyntaxKind.ForStatement, SyntaxKind.GoToStatement, SyntaxKind.IfStatement, SyntaxKind.LoopUntilStatement, SyntaxKind.LoopWhileStatement, SyntaxKind.NextStatement, SyntaxKind.ResumeLabelStatement, SyntaxKind.ResumeNextStatement, SyntaxKind.ReturnStatement, SyntaxKind.SelectStatement, SyntaxKind.SimpleDoStatement, SyntaxKind.SimpleLoopStatement, SyntaxKind.SingleLineIfStatement, SyntaxKind.ThrowStatement, SyntaxKind.TryStatement, SyntaxKind.UntilClause, SyntaxKind.WhileClause, SyntaxKind.WhileStatement, SyntaxKind.YieldStatement, SyntaxKind.TernaryConditionalExpression Return True Case Else Return False End Select End Function Private Function ClassifyPunctuation(token As SyntaxToken) As String If AllOperators.Contains(token.Kind) Then ' special cases... Select Case token.Kind Case SyntaxKind.LessThanToken, SyntaxKind.GreaterThanToken If TypeOf token.Parent Is AttributeListSyntax Then Return ClassificationTypeNames.Punctuation End If End Select Return ClassificationTypeNames.Operator Else Return ClassificationTypeNames.Punctuation End If End Function Private Function ClassifyIdentifierSyntax(identifier As SyntaxToken) As String 'Note: parent might be Nothing, if we are classifying raw tokens. Dim parent = identifier.Parent Dim classification As String = Nothing If TypeOf parent Is IdentifierNameSyntax AndAlso IsNamespaceName(DirectCast(parent, IdentifierNameSyntax)) Then Return ClassificationTypeNames.NamespaceName ElseIf TypeOf parent Is TypeStatementSyntax AndAlso DirectCast(parent, TypeStatementSyntax).Identifier = identifier Then Return ClassifyTypeDeclarationIdentifier(identifier) ElseIf TypeOf parent Is EnumStatementSyntax AndAlso DirectCast(parent, EnumStatementSyntax).Identifier = identifier Then Return ClassificationTypeNames.EnumName ElseIf TypeOf parent Is DelegateStatementSyntax AndAlso DirectCast(parent, DelegateStatementSyntax).Identifier = identifier AndAlso (parent.Kind = SyntaxKind.DelegateSubStatement OrElse parent.Kind = SyntaxKind.DelegateFunctionStatement) Then Return ClassificationTypeNames.DelegateName ElseIf TypeOf parent Is TypeParameterSyntax AndAlso DirectCast(parent, TypeParameterSyntax).Identifier = identifier Then Return ClassificationTypeNames.TypeParameterName ElseIf TypeOf parent Is MethodStatementSyntax AndAlso DirectCast(parent, MethodStatementSyntax).Identifier = identifier Then Return ClassificationTypeNames.MethodName ElseIf TypeOf parent Is DeclareStatementSyntax AndAlso DirectCast(parent, DeclareStatementSyntax).Identifier = identifier Then Return ClassificationTypeNames.MethodName ElseIf TypeOf parent Is PropertyStatementSyntax AndAlso DirectCast(parent, PropertyStatementSyntax).Identifier = identifier Then Return ClassificationTypeNames.PropertyName ElseIf TypeOf parent Is EventStatementSyntax AndAlso DirectCast(parent, EventStatementSyntax).Identifier = identifier Then Return ClassificationTypeNames.EventName ElseIf TypeOf parent Is EnumMemberDeclarationSyntax AndAlso DirectCast(parent, EnumMemberDeclarationSyntax).Identifier = identifier Then Return ClassificationTypeNames.EnumMemberName ElseIf TypeOf parent Is LabelStatementSyntax AndAlso DirectCast(parent, LabelStatementSyntax).LabelToken = identifier Then Return ClassificationTypeNames.LabelName ElseIf TypeOf parent?.Parent Is CatchStatementSyntax AndAlso DirectCast(parent.Parent, CatchStatementSyntax).IdentifierName.Identifier = identifier Then Return ClassificationTypeNames.LocalName ElseIf TryClassifyModifiedIdentifer(parent, identifier, classification) Then Return classification ElseIf (identifier.ToString() = "IsTrue" OrElse identifier.ToString() = "IsFalse") AndAlso TypeOf parent Is OperatorStatementSyntax AndAlso DirectCast(parent, OperatorStatementSyntax).OperatorToken = identifier Then Return ClassificationTypeNames.Keyword End If Return ClassificationTypeNames.Identifier End Function Private Function IsNamespaceName(identifierSyntax As IdentifierNameSyntax) As Boolean Dim parent = identifierSyntax.Parent While TypeOf parent Is QualifiedNameSyntax parent = parent.Parent End While Return TypeOf parent Is NamespaceStatementSyntax End Function Public Function IsStaticallyDeclared(identifier As SyntaxToken) As Boolean 'Note: parent might be Nothing, if we are classifying raw tokens. Dim parent = identifier.Parent If parent.IsKind(SyntaxKind.EnumMemberDeclaration) Then ' EnumMembers are not classified as static since there is no ' instance equivalent of the concept and they have their own ' classification type. Return False ElseIf parent.IsKind(SyntaxKind.ModifiedIdentifier) Then parent = parent.Parent?.Parent ' We are specifically looking for field declarations or constants. If Not parent.IsKind(SyntaxKind.FieldDeclaration) Then Return False End If If parent.GetModifiers().Any(SyntaxKind.ConstKeyword) Then Return True End If End If Return parent.GetModifiers().Any(SyntaxKind.SharedKeyword) End Function Private Function IsStringToken(token As SyntaxToken) As Boolean If token.IsKind(SyntaxKind.StringLiteralToken, SyntaxKind.CharacterLiteralToken, SyntaxKind.InterpolatedStringTextToken) Then Return True End If Return token.IsKind(SyntaxKind.DollarSignDoubleQuoteToken, SyntaxKind.DoubleQuoteToken) AndAlso token.Parent.IsKind(SyntaxKind.InterpolatedStringExpression) End Function Private Function TryClassifyModifiedIdentifer(node As SyntaxNode, identifier As SyntaxToken, ByRef classification As String) As Boolean classification = Nothing If TypeOf node IsNot ModifiedIdentifierSyntax OrElse DirectCast(node, ModifiedIdentifierSyntax).Identifier <> identifier Then Return False End If If TypeOf node.Parent Is ParameterSyntax Then classification = ClassificationTypeNames.ParameterName Return True End If If TypeOf node.Parent IsNot VariableDeclaratorSyntax Then Return False End If If TypeOf node.Parent.Parent Is LocalDeclarationStatementSyntax Then Dim localDeclaration = DirectCast(node.Parent.Parent, LocalDeclarationStatementSyntax) classification = If(localDeclaration.Modifiers.Any(SyntaxKind.ConstKeyword), ClassificationTypeNames.ConstantName, ClassificationTypeNames.LocalName) Return True End If If TypeOf node.Parent.Parent Is FieldDeclarationSyntax Then Dim localDeclaration = DirectCast(node.Parent.Parent, FieldDeclarationSyntax) classification = If(localDeclaration.Modifiers.Any(SyntaxKind.ConstKeyword), ClassificationTypeNames.ConstantName, ClassificationTypeNames.FieldName) Return True End If Return False End Function Private Function ClassifyTypeDeclarationIdentifier(identifier As SyntaxToken) As String Select Case identifier.Parent.Kind Case SyntaxKind.ClassStatement Return ClassificationTypeNames.ClassName Case SyntaxKind.ModuleStatement Return ClassificationTypeNames.ModuleName Case SyntaxKind.InterfaceStatement Return ClassificationTypeNames.InterfaceName Case SyntaxKind.StructureStatement Return ClassificationTypeNames.StructName Case Else throw ExceptionUtilities.UnexpectedValue(identifier.Parent.Kind) End Select End Function Friend Sub AddLexicalClassifications(text As SourceText, textSpan As TextSpan, result As ArrayBuilder(Of ClassifiedSpan), cancellationToken As CancellationToken) Dim text2 = text.ToString(textSpan) Dim tokens = SyntaxFactory.ParseTokens(text2, initialTokenPosition:=textSpan.Start) Worker.CollectClassifiedSpans(tokens, textSpan, result, cancellationToken) End Sub #Disable Warning IDE0060 ' Remove unused parameter - TODO: Do we need to do the same work here that we do in C#? Friend Function AdjustStaleClassification(text As SourceText, classifiedSpan As ClassifiedSpan) As ClassifiedSpan #Enable Warning IDE0060 ' Remove unused parameter Return classifiedSpan End Function End Module End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading Imports Microsoft.CodeAnalysis.Classification Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.Classification Friend Module ClassificationHelpers ''' <summary> ''' Return the classification type associated with this token. ''' </summary> ''' <param name="token">The token to be classified.</param> ''' <returns>The classification type for the token</returns> ''' <remarks></remarks> Public Function GetClassification(token As SyntaxToken) As String If IsControlKeyword(token) Then Return ClassificationTypeNames.ControlKeyword ElseIf SyntaxFacts.IsKeywordKind(token.Kind) Then Return ClassificationTypeNames.Keyword ElseIf IsStringToken(token) Then Return ClassificationTypeNames.StringLiteral ElseIf SyntaxFacts.IsPunctuation(token.Kind) Then Return ClassifyPunctuation(token) ElseIf token.Kind = SyntaxKind.IdentifierToken Then Return ClassifyIdentifierSyntax(token) ElseIf token.IsNumericLiteral() Then Return ClassificationTypeNames.NumericLiteral ElseIf token.Kind = SyntaxKind.XmlNameToken Then Return ClassificationTypeNames.XmlLiteralName ElseIf token.Kind = SyntaxKind.XmlTextLiteralToken Then Select Case token.Parent.Kind Case SyntaxKind.XmlString Return ClassificationTypeNames.XmlLiteralAttributeValue Case SyntaxKind.XmlProcessingInstruction Return ClassificationTypeNames.XmlLiteralProcessingInstruction Case SyntaxKind.XmlComment Return ClassificationTypeNames.XmlLiteralComment Case SyntaxKind.XmlCDataSection Return ClassificationTypeNames.XmlLiteralCDataSection Case Else Return ClassificationTypeNames.XmlLiteralText End Select ElseIf token.Kind = SyntaxKind.XmlEntityLiteralToken Then Return ClassificationTypeNames.XmlLiteralEntityReference ElseIf token.IsKind(SyntaxKind.None, SyntaxKind.BadToken) Then Return Nothing Else throw ExceptionUtilities.UnexpectedValue(token.Kind()) End If End Function Private Function IsControlKeyword(token As SyntaxToken) As Boolean If token.Parent Is Nothing Then Return False End If ' For Exit Statments classify everything as a control keyword If token.Parent.IsKind( SyntaxKind.ExitFunctionStatement, SyntaxKind.ExitOperatorStatement, SyntaxKind.ExitPropertyStatement, SyntaxKind.ExitSubStatement) Then Return True End If ' Control keywords are used in other contexts so check that it is ' being used in a supported context. Return IsControlKeywordKind(token.Kind) AndAlso IsControlStatementKind(token.Parent.Kind) End Function ''' <summary> ''' Determine if the kind represents a control keyword ''' </summary> Private Function IsControlKeywordKind(kind As SyntaxKind) As Boolean Select Case kind Case _ SyntaxKind.CaseKeyword, SyntaxKind.CatchKeyword, SyntaxKind.ContinueKeyword, SyntaxKind.DoKeyword, SyntaxKind.EachKeyword, SyntaxKind.ElseKeyword, SyntaxKind.ElseIfKeyword, SyntaxKind.EndKeyword, SyntaxKind.ExitKeyword, SyntaxKind.FinallyKeyword, SyntaxKind.ForKeyword, SyntaxKind.GoToKeyword, SyntaxKind.IfKeyword, SyntaxKind.InKeyword, SyntaxKind.LoopKeyword, SyntaxKind.NextKeyword, SyntaxKind.ResumeKeyword, SyntaxKind.ReturnKeyword, SyntaxKind.SelectKeyword, SyntaxKind.ThenKeyword, SyntaxKind.TryKeyword, SyntaxKind.WhileKeyword, SyntaxKind.WendKeyword, SyntaxKind.UntilKeyword, SyntaxKind.EndIfKeyword, SyntaxKind.GosubKeyword, SyntaxKind.YieldKeyword, SyntaxKind.ToKeyword Return True Case Else Return False End Select End Function ''' <summary> ''' Determine if the kind represents a control statement ''' </summary> Private Function IsControlStatementKind(kind As SyntaxKind) As Boolean Select Case kind Case _ SyntaxKind.CallStatement, SyntaxKind.CaseElseStatement, SyntaxKind.CaseStatement, SyntaxKind.CatchStatement, SyntaxKind.ContinueDoStatement, SyntaxKind.ContinueForStatement, SyntaxKind.ContinueWhileStatement, SyntaxKind.DoUntilStatement, SyntaxKind.DoWhileStatement, SyntaxKind.ElseIfStatement, SyntaxKind.ElseStatement, SyntaxKind.EndIfStatement, SyntaxKind.EndSelectStatement, SyntaxKind.EndTryStatement, SyntaxKind.EndWhileStatement, SyntaxKind.ExitDoStatement, SyntaxKind.ExitForStatement, SyntaxKind.ExitSelectStatement, SyntaxKind.ExitTryStatement, SyntaxKind.ExitWhileStatement, SyntaxKind.FinallyStatement, SyntaxKind.ForEachStatement, SyntaxKind.ForStatement, SyntaxKind.GoToStatement, SyntaxKind.IfStatement, SyntaxKind.LoopUntilStatement, SyntaxKind.LoopWhileStatement, SyntaxKind.NextStatement, SyntaxKind.ResumeLabelStatement, SyntaxKind.ResumeNextStatement, SyntaxKind.ReturnStatement, SyntaxKind.SelectStatement, SyntaxKind.SimpleDoStatement, SyntaxKind.SimpleLoopStatement, SyntaxKind.SingleLineIfStatement, SyntaxKind.ThrowStatement, SyntaxKind.TryStatement, SyntaxKind.UntilClause, SyntaxKind.WhileClause, SyntaxKind.WhileStatement, SyntaxKind.YieldStatement, SyntaxKind.TernaryConditionalExpression Return True Case Else Return False End Select End Function Private Function ClassifyPunctuation(token As SyntaxToken) As String If AllOperators.Contains(token.Kind) Then ' special cases... Select Case token.Kind Case SyntaxKind.LessThanToken, SyntaxKind.GreaterThanToken If TypeOf token.Parent Is AttributeListSyntax Then Return ClassificationTypeNames.Punctuation End If End Select Return ClassificationTypeNames.Operator Else Return ClassificationTypeNames.Punctuation End If End Function Private Function ClassifyIdentifierSyntax(identifier As SyntaxToken) As String 'Note: parent might be Nothing, if we are classifying raw tokens. Dim parent = identifier.Parent Dim classification As String = Nothing If TypeOf parent Is IdentifierNameSyntax AndAlso IsNamespaceName(DirectCast(parent, IdentifierNameSyntax)) Then Return ClassificationTypeNames.NamespaceName ElseIf TypeOf parent Is TypeStatementSyntax AndAlso DirectCast(parent, TypeStatementSyntax).Identifier = identifier Then Return ClassifyTypeDeclarationIdentifier(identifier) ElseIf TypeOf parent Is EnumStatementSyntax AndAlso DirectCast(parent, EnumStatementSyntax).Identifier = identifier Then Return ClassificationTypeNames.EnumName ElseIf TypeOf parent Is DelegateStatementSyntax AndAlso DirectCast(parent, DelegateStatementSyntax).Identifier = identifier AndAlso (parent.Kind = SyntaxKind.DelegateSubStatement OrElse parent.Kind = SyntaxKind.DelegateFunctionStatement) Then Return ClassificationTypeNames.DelegateName ElseIf TypeOf parent Is TypeParameterSyntax AndAlso DirectCast(parent, TypeParameterSyntax).Identifier = identifier Then Return ClassificationTypeNames.TypeParameterName ElseIf TypeOf parent Is MethodStatementSyntax AndAlso DirectCast(parent, MethodStatementSyntax).Identifier = identifier Then Return ClassificationTypeNames.MethodName ElseIf TypeOf parent Is DeclareStatementSyntax AndAlso DirectCast(parent, DeclareStatementSyntax).Identifier = identifier Then Return ClassificationTypeNames.MethodName ElseIf TypeOf parent Is PropertyStatementSyntax AndAlso DirectCast(parent, PropertyStatementSyntax).Identifier = identifier Then Return ClassificationTypeNames.PropertyName ElseIf TypeOf parent Is EventStatementSyntax AndAlso DirectCast(parent, EventStatementSyntax).Identifier = identifier Then Return ClassificationTypeNames.EventName ElseIf TypeOf parent Is EnumMemberDeclarationSyntax AndAlso DirectCast(parent, EnumMemberDeclarationSyntax).Identifier = identifier Then Return ClassificationTypeNames.EnumMemberName ElseIf TypeOf parent Is LabelStatementSyntax AndAlso DirectCast(parent, LabelStatementSyntax).LabelToken = identifier Then Return ClassificationTypeNames.LabelName ElseIf TypeOf parent?.Parent Is CatchStatementSyntax AndAlso DirectCast(parent.Parent, CatchStatementSyntax).IdentifierName.Identifier = identifier Then Return ClassificationTypeNames.LocalName ElseIf TryClassifyModifiedIdentifer(parent, identifier, classification) Then Return classification ElseIf (identifier.ToString() = "IsTrue" OrElse identifier.ToString() = "IsFalse") AndAlso TypeOf parent Is OperatorStatementSyntax AndAlso DirectCast(parent, OperatorStatementSyntax).OperatorToken = identifier Then Return ClassificationTypeNames.Keyword End If Return ClassificationTypeNames.Identifier End Function Private Function IsNamespaceName(identifierSyntax As IdentifierNameSyntax) As Boolean Dim parent = identifierSyntax.Parent While TypeOf parent Is QualifiedNameSyntax parent = parent.Parent End While Return TypeOf parent Is NamespaceStatementSyntax End Function Public Function IsStaticallyDeclared(identifier As SyntaxToken) As Boolean 'Note: parent might be Nothing, if we are classifying raw tokens. Dim parent = identifier.Parent If parent.IsKind(SyntaxKind.EnumMemberDeclaration) Then ' EnumMembers are not classified as static since there is no ' instance equivalent of the concept and they have their own ' classification type. Return False ElseIf parent.IsKind(SyntaxKind.ModifiedIdentifier) Then parent = parent.Parent?.Parent ' We are specifically looking for field declarations or constants. If Not parent.IsKind(SyntaxKind.FieldDeclaration) Then Return False End If If parent.GetModifiers().Any(SyntaxKind.ConstKeyword) Then Return True End If End If Return parent.GetModifiers().Any(SyntaxKind.SharedKeyword) End Function Private Function IsStringToken(token As SyntaxToken) As Boolean If token.IsKind(SyntaxKind.StringLiteralToken, SyntaxKind.CharacterLiteralToken, SyntaxKind.InterpolatedStringTextToken) Then Return True End If Return token.IsKind(SyntaxKind.DollarSignDoubleQuoteToken, SyntaxKind.DoubleQuoteToken) AndAlso token.Parent.IsKind(SyntaxKind.InterpolatedStringExpression) End Function Private Function TryClassifyModifiedIdentifer(node As SyntaxNode, identifier As SyntaxToken, ByRef classification As String) As Boolean classification = Nothing If TypeOf node IsNot ModifiedIdentifierSyntax OrElse DirectCast(node, ModifiedIdentifierSyntax).Identifier <> identifier Then Return False End If If TypeOf node.Parent Is ParameterSyntax Then classification = ClassificationTypeNames.ParameterName Return True End If If TypeOf node.Parent IsNot VariableDeclaratorSyntax Then Return False End If If TypeOf node.Parent.Parent Is LocalDeclarationStatementSyntax Then Dim localDeclaration = DirectCast(node.Parent.Parent, LocalDeclarationStatementSyntax) classification = If(localDeclaration.Modifiers.Any(SyntaxKind.ConstKeyword), ClassificationTypeNames.ConstantName, ClassificationTypeNames.LocalName) Return True End If If TypeOf node.Parent.Parent Is FieldDeclarationSyntax Then Dim localDeclaration = DirectCast(node.Parent.Parent, FieldDeclarationSyntax) classification = If(localDeclaration.Modifiers.Any(SyntaxKind.ConstKeyword), ClassificationTypeNames.ConstantName, ClassificationTypeNames.FieldName) Return True End If Return False End Function Private Function ClassifyTypeDeclarationIdentifier(identifier As SyntaxToken) As String Select Case identifier.Parent.Kind Case SyntaxKind.ClassStatement Return ClassificationTypeNames.ClassName Case SyntaxKind.ModuleStatement Return ClassificationTypeNames.ModuleName Case SyntaxKind.InterfaceStatement Return ClassificationTypeNames.InterfaceName Case SyntaxKind.StructureStatement Return ClassificationTypeNames.StructName Case Else throw ExceptionUtilities.UnexpectedValue(identifier.Parent.Kind) End Select End Function Friend Sub AddLexicalClassifications(text As SourceText, textSpan As TextSpan, result As ArrayBuilder(Of ClassifiedSpan), cancellationToken As CancellationToken) Dim text2 = text.ToString(textSpan) Dim tokens = SyntaxFactory.ParseTokens(text2, initialTokenPosition:=textSpan.Start) Worker.CollectClassifiedSpans(tokens, textSpan, result, cancellationToken) End Sub #Disable Warning IDE0060 ' Remove unused parameter - TODO: Do we need to do the same work here that we do in C#? Friend Function AdjustStaleClassification(text As SourceText, classifiedSpan As ClassifiedSpan) As ClassifiedSpan #Enable Warning IDE0060 ' Remove unused parameter Return classifiedSpan End Function End Module End Namespace
-1
dotnet/roslyn
56,011
React to string comparison changing on .NET Core
The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
jaredpar
"2021-08-30T17:18:52Z"
"2021-08-30T20:20:04Z"
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
4d99cda6e446e77dbb302e26388c1093bd3ef569
React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
./src/Compilers/VisualBasic/Portable/Emit/EditAndContinue/VisualBasicDefinitionMap.vb
' 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.Reflection.Metadata Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.CodeGen Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Namespace Microsoft.CodeAnalysis.VisualBasic.Emit ''' <summary> ''' Matches symbols from an assembly in one compilation to ''' the corresponding assembly in another. Assumes that only ''' one assembly has changed between the two compilations. ''' </summary> Friend NotInheritable Class VisualBasicDefinitionMap Inherits DefinitionMap Private ReadOnly _metadataDecoder As MetadataDecoder Private ReadOnly _mapToMetadata As VisualBasicSymbolMatcher Private ReadOnly _mapToPrevious As VisualBasicSymbolMatcher Public Sub New(edits As IEnumerable(Of SemanticEdit), metadataDecoder As MetadataDecoder, mapToMetadata As VisualBasicSymbolMatcher, mapToPrevious As VisualBasicSymbolMatcher) MyBase.New(edits) Debug.Assert(metadataDecoder IsNot Nothing) Debug.Assert(mapToMetadata IsNot Nothing) _metadataDecoder = metadataDecoder _mapToMetadata = mapToMetadata _mapToPrevious = If(mapToPrevious, mapToMetadata) End Sub Protected Overrides ReadOnly Property MapToMetadataSymbolMatcher As SymbolMatcher Get Return _mapToMetadata End Get End Property Protected Overrides ReadOnly Property MapToPreviousSymbolMatcher As SymbolMatcher Get Return _mapToPrevious End Get End Property Protected Overrides Function GetISymbolInternalOrNull(symbol As ISymbol) As ISymbolInternal Return TryCast(symbol, Symbol) End Function Friend Overrides ReadOnly Property MessageProvider As CommonMessageProvider Get Return VisualBasic.MessageProvider.Instance End Get End Property Protected Overrides Function GetLambdaSyntaxFacts() As LambdaSyntaxFacts Return VisualBasicLambdaSyntaxFacts.Instance End Function Friend Function TryGetAnonymousTypeName(template As AnonymousTypeManager.AnonymousTypeOrDelegateTemplateSymbol, <Out> ByRef name As String, <Out> ByRef index As Integer) As Boolean Return _mapToPrevious.TryGetAnonymousTypeName(template, name, index) End Function Friend Overrides Function TryGetTypeHandle(def As Cci.ITypeDefinition, <Out> ByRef handle As TypeDefinitionHandle) As Boolean Dim other = TryCast(_mapToMetadata.MapDefinition(def)?.GetInternalSymbol(), PENamedTypeSymbol) If other IsNot Nothing Then handle = other.Handle Return True Else handle = Nothing Return False End If End Function Friend Overrides Function TryGetEventHandle(def As Cci.IEventDefinition, <Out> ByRef handle As EventDefinitionHandle) As Boolean Dim other = TryCast(_mapToMetadata.MapDefinition(def)?.GetInternalSymbol(), PEEventSymbol) If other IsNot Nothing Then handle = other.Handle Return True Else handle = Nothing Return False End If End Function Friend Overrides Function TryGetFieldHandle(def As Cci.IFieldDefinition, <Out> ByRef handle As FieldDefinitionHandle) As Boolean Dim other = TryCast(_mapToMetadata.MapDefinition(def)?.GetInternalSymbol(), PEFieldSymbol) If other IsNot Nothing Then handle = other.Handle Return True Else handle = Nothing Return False End If End Function Friend Overrides Function TryGetMethodHandle(def As Cci.IMethodDefinition, <Out> ByRef handle As MethodDefinitionHandle) As Boolean Dim other = TryCast(_mapToMetadata.MapDefinition(def)?.GetInternalSymbol(), PEMethodSymbol) If other IsNot Nothing Then handle = other.Handle Return True Else handle = Nothing Return False End If End Function Friend Overrides Function TryGetPropertyHandle(def As Cci.IPropertyDefinition, <Out> ByRef handle As PropertyDefinitionHandle) As Boolean Dim other = TryCast(_mapToMetadata.MapDefinition(def)?.GetInternalSymbol(), PEPropertySymbol) If other IsNot Nothing Then handle = other.Handle Return True Else handle = Nothing Return False End If End Function Protected Overrides Function TryGetStateMachineType(methodHandle As EntityHandle) As ITypeSymbolInternal Dim typeName As String = Nothing If _metadataDecoder.Module.HasStringValuedAttribute(methodHandle, AttributeDescription.AsyncStateMachineAttribute, typeName) OrElse _metadataDecoder.Module.HasStringValuedAttribute(methodHandle, AttributeDescription.IteratorStateMachineAttribute, typeName) Then Return _metadataDecoder.GetTypeSymbolForSerializedType(typeName) End If Return Nothing End Function Protected Overrides Sub GetStateMachineFieldMapFromMetadata(stateMachineType As ITypeSymbolInternal, localSlotDebugInfo As ImmutableArray(Of LocalSlotDebugInfo), <Out> ByRef hoistedLocalMap As IReadOnlyDictionary(Of EncHoistedLocalInfo, Integer), <Out> ByRef awaiterMap As IReadOnlyDictionary(Of Cci.ITypeReference, Integer), <Out> ByRef awaiterSlotCount As Integer) ' we are working with PE symbols Debug.Assert(TypeOf stateMachineType.ContainingAssembly Is PEAssemblySymbol) Dim hoistedLocals = New Dictionary(Of EncHoistedLocalInfo, Integer)() Dim awaiters = New Dictionary(Of Cci.ITypeReference, Integer)(DirectCast(Cci.SymbolEquivalentEqualityComparer.Instance, IEqualityComparer(Of Cci.IReference))) Dim maxAwaiterSlotIndex = -1 For Each member In DirectCast(stateMachineType, TypeSymbol).GetMembers() If member.Kind = SymbolKind.Field Then Dim name = member.Name Dim slotIndex As Integer Select Case GeneratedNameParser.GetKind(name) Case GeneratedNameKind.StateMachineAwaiterField If GeneratedNameParser.TryParseSlotIndex(GeneratedNameConstants.StateMachineAwaiterFieldPrefix, name, slotIndex) Then Dim field = DirectCast(member, FieldSymbol) ' Correct metadata won't contain duplicates, but malformed might, ignore the duplicate: awaiters(DirectCast(field.Type.GetCciAdapter(), Cci.ITypeReference)) = slotIndex If slotIndex > maxAwaiterSlotIndex Then maxAwaiterSlotIndex = slotIndex End If End If Case GeneratedNameKind.HoistedSynthesizedLocalField, GeneratedNameKind.StateMachineHoistedUserVariableField Dim _name As String = Nothing If GeneratedNameParser.TryParseSlotIndex(GeneratedNameConstants.HoistedSynthesizedLocalPrefix, name, slotIndex) OrElse GeneratedNameParser.TryParseStateMachineHoistedUserVariableName(name, _name, slotIndex) Then Dim field = DirectCast(member, FieldSymbol) If slotIndex >= localSlotDebugInfo.Length Then ' Invalid metadata Continue For End If Dim key = New EncHoistedLocalInfo(localSlotDebugInfo(slotIndex), DirectCast(field.Type.GetCciAdapter(), Cci.ITypeReference)) ' Correct metadata won't contain duplicates, but malformed might, ignore the duplicate: hoistedLocals(key) = slotIndex End If End Select End If Next hoistedLocalMap = hoistedLocals awaiterMap = awaiters awaiterSlotCount = maxAwaiterSlotIndex + 1 End Sub Protected Overrides Function GetLocalSlotMapFromMetadata(handle As StandaloneSignatureHandle, debugInfo As EditAndContinueMethodDebugInformation) As ImmutableArray(Of EncLocalInfo) Debug.Assert(Not handle.IsNil) Dim localInfos = _metadataDecoder.GetLocalsOrThrow(handle) Dim result = CreateLocalSlotMap(debugInfo, localInfos) Debug.Assert(result.Length = localInfos.Length) Return result End Function ''' <summary> ''' Match local declarations to names to generate a map from ''' declaration to local slot. The names are indexed by slot And the ''' assumption Is that declarations are in the same order as slots. ''' </summary> Private Shared Function CreateLocalSlotMap( methodEncInfo As EditAndContinueMethodDebugInformation, slotMetadata As ImmutableArray(Of LocalInfo(Of TypeSymbol))) As ImmutableArray(Of EncLocalInfo) Dim result(slotMetadata.Length - 1) As EncLocalInfo Dim localSlots = methodEncInfo.LocalSlots If Not localSlots.IsDefault Then ' In case of corrupted PDB or metadata, these lengths might Not match. ' Let's guard against such case. Dim slotCount = Math.Min(localSlots.Length, slotMetadata.Length) Dim map = New Dictionary(Of EncLocalInfo, Integer)() For slotIndex = 0 To slotCount - 1 Dim slot = localSlots(slotIndex) If slot.SynthesizedKind.IsLongLived() Then Dim metadata = slotMetadata(slotIndex) ' We do Not emit custom modifiers on locals so ignore the ' previous version of the local if it had custom modifiers. If metadata.CustomModifiers.IsDefaultOrEmpty Then Dim local = New EncLocalInfo(slot, DirectCast(metadata.Type.GetCciAdapter(), Cci.ITypeReference), metadata.Constraints, metadata.SignatureOpt) map.Add(local, slotIndex) End If End If Next For Each pair In map result(pair.Value) = pair.Key Next End If ' Populate any remaining locals that were Not matched to source. For i = 0 To result.Length - 1 If result(i).IsDefault Then result(i) = New EncLocalInfo(slotMetadata(i).SignatureOpt) End If Next Return ImmutableArray.Create(result) End Function End Class End Namespace
' 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.Reflection.Metadata Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.CodeGen Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Namespace Microsoft.CodeAnalysis.VisualBasic.Emit ''' <summary> ''' Matches symbols from an assembly in one compilation to ''' the corresponding assembly in another. Assumes that only ''' one assembly has changed between the two compilations. ''' </summary> Friend NotInheritable Class VisualBasicDefinitionMap Inherits DefinitionMap Private ReadOnly _metadataDecoder As MetadataDecoder Private ReadOnly _mapToMetadata As VisualBasicSymbolMatcher Private ReadOnly _mapToPrevious As VisualBasicSymbolMatcher Public Sub New(edits As IEnumerable(Of SemanticEdit), metadataDecoder As MetadataDecoder, mapToMetadata As VisualBasicSymbolMatcher, mapToPrevious As VisualBasicSymbolMatcher) MyBase.New(edits) Debug.Assert(metadataDecoder IsNot Nothing) Debug.Assert(mapToMetadata IsNot Nothing) _metadataDecoder = metadataDecoder _mapToMetadata = mapToMetadata _mapToPrevious = If(mapToPrevious, mapToMetadata) End Sub Protected Overrides ReadOnly Property MapToMetadataSymbolMatcher As SymbolMatcher Get Return _mapToMetadata End Get End Property Protected Overrides ReadOnly Property MapToPreviousSymbolMatcher As SymbolMatcher Get Return _mapToPrevious End Get End Property Protected Overrides Function GetISymbolInternalOrNull(symbol As ISymbol) As ISymbolInternal Return TryCast(symbol, Symbol) End Function Friend Overrides ReadOnly Property MessageProvider As CommonMessageProvider Get Return VisualBasic.MessageProvider.Instance End Get End Property Protected Overrides Function GetLambdaSyntaxFacts() As LambdaSyntaxFacts Return VisualBasicLambdaSyntaxFacts.Instance End Function Friend Function TryGetAnonymousTypeName(template As AnonymousTypeManager.AnonymousTypeOrDelegateTemplateSymbol, <Out> ByRef name As String, <Out> ByRef index As Integer) As Boolean Return _mapToPrevious.TryGetAnonymousTypeName(template, name, index) End Function Friend Overrides Function TryGetTypeHandle(def As Cci.ITypeDefinition, <Out> ByRef handle As TypeDefinitionHandle) As Boolean Dim other = TryCast(_mapToMetadata.MapDefinition(def)?.GetInternalSymbol(), PENamedTypeSymbol) If other IsNot Nothing Then handle = other.Handle Return True Else handle = Nothing Return False End If End Function Friend Overrides Function TryGetEventHandle(def As Cci.IEventDefinition, <Out> ByRef handle As EventDefinitionHandle) As Boolean Dim other = TryCast(_mapToMetadata.MapDefinition(def)?.GetInternalSymbol(), PEEventSymbol) If other IsNot Nothing Then handle = other.Handle Return True Else handle = Nothing Return False End If End Function Friend Overrides Function TryGetFieldHandle(def As Cci.IFieldDefinition, <Out> ByRef handle As FieldDefinitionHandle) As Boolean Dim other = TryCast(_mapToMetadata.MapDefinition(def)?.GetInternalSymbol(), PEFieldSymbol) If other IsNot Nothing Then handle = other.Handle Return True Else handle = Nothing Return False End If End Function Friend Overrides Function TryGetMethodHandle(def As Cci.IMethodDefinition, <Out> ByRef handle As MethodDefinitionHandle) As Boolean Dim other = TryCast(_mapToMetadata.MapDefinition(def)?.GetInternalSymbol(), PEMethodSymbol) If other IsNot Nothing Then handle = other.Handle Return True Else handle = Nothing Return False End If End Function Friend Overrides Function TryGetPropertyHandle(def As Cci.IPropertyDefinition, <Out> ByRef handle As PropertyDefinitionHandle) As Boolean Dim other = TryCast(_mapToMetadata.MapDefinition(def)?.GetInternalSymbol(), PEPropertySymbol) If other IsNot Nothing Then handle = other.Handle Return True Else handle = Nothing Return False End If End Function Protected Overrides Function TryGetStateMachineType(methodHandle As EntityHandle) As ITypeSymbolInternal Dim typeName As String = Nothing If _metadataDecoder.Module.HasStringValuedAttribute(methodHandle, AttributeDescription.AsyncStateMachineAttribute, typeName) OrElse _metadataDecoder.Module.HasStringValuedAttribute(methodHandle, AttributeDescription.IteratorStateMachineAttribute, typeName) Then Return _metadataDecoder.GetTypeSymbolForSerializedType(typeName) End If Return Nothing End Function Protected Overrides Sub GetStateMachineFieldMapFromMetadata(stateMachineType As ITypeSymbolInternal, localSlotDebugInfo As ImmutableArray(Of LocalSlotDebugInfo), <Out> ByRef hoistedLocalMap As IReadOnlyDictionary(Of EncHoistedLocalInfo, Integer), <Out> ByRef awaiterMap As IReadOnlyDictionary(Of Cci.ITypeReference, Integer), <Out> ByRef awaiterSlotCount As Integer) ' we are working with PE symbols Debug.Assert(TypeOf stateMachineType.ContainingAssembly Is PEAssemblySymbol) Dim hoistedLocals = New Dictionary(Of EncHoistedLocalInfo, Integer)() Dim awaiters = New Dictionary(Of Cci.ITypeReference, Integer)(DirectCast(Cci.SymbolEquivalentEqualityComparer.Instance, IEqualityComparer(Of Cci.IReference))) Dim maxAwaiterSlotIndex = -1 For Each member In DirectCast(stateMachineType, TypeSymbol).GetMembers() If member.Kind = SymbolKind.Field Then Dim name = member.Name Dim slotIndex As Integer Select Case GeneratedNameParser.GetKind(name) Case GeneratedNameKind.StateMachineAwaiterField If GeneratedNameParser.TryParseSlotIndex(GeneratedNameConstants.StateMachineAwaiterFieldPrefix, name, slotIndex) Then Dim field = DirectCast(member, FieldSymbol) ' Correct metadata won't contain duplicates, but malformed might, ignore the duplicate: awaiters(DirectCast(field.Type.GetCciAdapter(), Cci.ITypeReference)) = slotIndex If slotIndex > maxAwaiterSlotIndex Then maxAwaiterSlotIndex = slotIndex End If End If Case GeneratedNameKind.HoistedSynthesizedLocalField, GeneratedNameKind.StateMachineHoistedUserVariableField Dim _name As String = Nothing If GeneratedNameParser.TryParseSlotIndex(GeneratedNameConstants.HoistedSynthesizedLocalPrefix, name, slotIndex) OrElse GeneratedNameParser.TryParseStateMachineHoistedUserVariableName(name, _name, slotIndex) Then Dim field = DirectCast(member, FieldSymbol) If slotIndex >= localSlotDebugInfo.Length Then ' Invalid metadata Continue For End If Dim key = New EncHoistedLocalInfo(localSlotDebugInfo(slotIndex), DirectCast(field.Type.GetCciAdapter(), Cci.ITypeReference)) ' Correct metadata won't contain duplicates, but malformed might, ignore the duplicate: hoistedLocals(key) = slotIndex End If End Select End If Next hoistedLocalMap = hoistedLocals awaiterMap = awaiters awaiterSlotCount = maxAwaiterSlotIndex + 1 End Sub Protected Overrides Function GetLocalSlotMapFromMetadata(handle As StandaloneSignatureHandle, debugInfo As EditAndContinueMethodDebugInformation) As ImmutableArray(Of EncLocalInfo) Debug.Assert(Not handle.IsNil) Dim localInfos = _metadataDecoder.GetLocalsOrThrow(handle) Dim result = CreateLocalSlotMap(debugInfo, localInfos) Debug.Assert(result.Length = localInfos.Length) Return result End Function ''' <summary> ''' Match local declarations to names to generate a map from ''' declaration to local slot. The names are indexed by slot And the ''' assumption Is that declarations are in the same order as slots. ''' </summary> Private Shared Function CreateLocalSlotMap( methodEncInfo As EditAndContinueMethodDebugInformation, slotMetadata As ImmutableArray(Of LocalInfo(Of TypeSymbol))) As ImmutableArray(Of EncLocalInfo) Dim result(slotMetadata.Length - 1) As EncLocalInfo Dim localSlots = methodEncInfo.LocalSlots If Not localSlots.IsDefault Then ' In case of corrupted PDB or metadata, these lengths might Not match. ' Let's guard against such case. Dim slotCount = Math.Min(localSlots.Length, slotMetadata.Length) Dim map = New Dictionary(Of EncLocalInfo, Integer)() For slotIndex = 0 To slotCount - 1 Dim slot = localSlots(slotIndex) If slot.SynthesizedKind.IsLongLived() Then Dim metadata = slotMetadata(slotIndex) ' We do Not emit custom modifiers on locals so ignore the ' previous version of the local if it had custom modifiers. If metadata.CustomModifiers.IsDefaultOrEmpty Then Dim local = New EncLocalInfo(slot, DirectCast(metadata.Type.GetCciAdapter(), Cci.ITypeReference), metadata.Constraints, metadata.SignatureOpt) map.Add(local, slotIndex) End If End If Next For Each pair In map result(pair.Value) = pair.Key Next End If ' Populate any remaining locals that were Not matched to source. For i = 0 To result.Length - 1 If result(i).IsDefault Then result(i) = New EncLocalInfo(slotMetadata(i).SignatureOpt) End If Next Return ImmutableArray.Create(result) End Function End Class End Namespace
-1
dotnet/roslyn
56,011
React to string comparison changing on .NET Core
The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
jaredpar
"2021-08-30T17:18:52Z"
"2021-08-30T20:20:04Z"
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
4d99cda6e446e77dbb302e26388c1093bd3ef569
React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
./src/EditorFeatures/Test2/Rename/CSharp/OverrideTests.vb
' 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.Remote.Testing Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Rename.CSharp <[UseExportProvider]> Public Class OverrideTests Private ReadOnly _outputHelper As Abstractions.ITestOutputHelper Public Sub New(outputHelper As Abstractions.ITestOutputHelper) _outputHelper = outputHelper End Sub <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameOverrideMemberFromDerivedClass(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" AssemblyName="ClassLibrary1" CommonReferences="true"> <Document> namespace ClassLibrary1 { public class Class1 { public virtual void [|M|]() { } } } </Document> </Project> <Project Language="C#" AssemblyName="ClassLibrary2" CommonReferences="true"> <ProjectReference>ClassLibrary1</ProjectReference> <Document> namespace ClassLibrary2 { public class Class2 : ClassLibrary1.Class1 { public override void [|$$M|]() { } } } </Document> </Project> </Workspace>, host:=host, renameTo:="A") End Using End Sub <WorkItem(25682, "https://github.com/dotnet/roslyn/issues/25682")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameOverrideMemberFromDerivedClassWhenMemberIsPrivate(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" AssemblyName="ClassLibrary1" CommonReferences="true"> <Document> namespace ClassLibrary1 { public class Class1 { public virtual void [|M|]() { } } } </Document> </Project> <Project Language="C#" AssemblyName="ClassLibrary2" CommonReferences="true"> <ProjectReference>ClassLibrary1</ProjectReference> <Document> namespace ClassLibrary2 { public class Class2 : ClassLibrary1.Class1 { override void [|$$M|]() { } } } </Document> </Project> </Workspace>, host:=host, renameTo:="A") End Using End Sub <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameOverrideMemberFromDerivedClass_abstract_virtual(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" AssemblyName="ClassLibrary1" CommonReferences="true"> <Document> namespace ClassLibrary1 { public abstract class Class1 { public abstract void M(); } } </Document> </Project> <Project Language="C#" AssemblyName="ClassLibrary2" CommonReferences="true"> <ProjectReference>ClassLibrary1</ProjectReference> <Document> namespace ClassLibrary2 { public class Class2 : ClassLibrary1.Class1 { virtual void [|$$M|]() { } } } </Document> </Project> </Workspace>, host:=host, renameTo:="A") End Using End Sub <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameOverrideMemberFromDerivedClass_abstract_override(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" AssemblyName="ClassLibrary1" CommonReferences="true"> <Document> namespace ClassLibrary1 { public abstract class Class1 { public virtual void [|M|](); } } </Document> </Project> <Project Language="C#" AssemblyName="ClassLibrary2" CommonReferences="true"> <ProjectReference>ClassLibrary1</ProjectReference> <Document> namespace ClassLibrary2 { public class Class2 : ClassLibrary1.Class1 { override void [|$$M|]() { } } } </Document> </Project> </Workspace>, host:=host, renameTo:="A") End Using End Sub End Class End Namespace
' 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.Remote.Testing Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Rename.CSharp <[UseExportProvider]> Public Class OverrideTests Private ReadOnly _outputHelper As Abstractions.ITestOutputHelper Public Sub New(outputHelper As Abstractions.ITestOutputHelper) _outputHelper = outputHelper End Sub <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameOverrideMemberFromDerivedClass(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" AssemblyName="ClassLibrary1" CommonReferences="true"> <Document> namespace ClassLibrary1 { public class Class1 { public virtual void [|M|]() { } } } </Document> </Project> <Project Language="C#" AssemblyName="ClassLibrary2" CommonReferences="true"> <ProjectReference>ClassLibrary1</ProjectReference> <Document> namespace ClassLibrary2 { public class Class2 : ClassLibrary1.Class1 { public override void [|$$M|]() { } } } </Document> </Project> </Workspace>, host:=host, renameTo:="A") End Using End Sub <WorkItem(25682, "https://github.com/dotnet/roslyn/issues/25682")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameOverrideMemberFromDerivedClassWhenMemberIsPrivate(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" AssemblyName="ClassLibrary1" CommonReferences="true"> <Document> namespace ClassLibrary1 { public class Class1 { public virtual void [|M|]() { } } } </Document> </Project> <Project Language="C#" AssemblyName="ClassLibrary2" CommonReferences="true"> <ProjectReference>ClassLibrary1</ProjectReference> <Document> namespace ClassLibrary2 { public class Class2 : ClassLibrary1.Class1 { override void [|$$M|]() { } } } </Document> </Project> </Workspace>, host:=host, renameTo:="A") End Using End Sub <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameOverrideMemberFromDerivedClass_abstract_virtual(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" AssemblyName="ClassLibrary1" CommonReferences="true"> <Document> namespace ClassLibrary1 { public abstract class Class1 { public abstract void M(); } } </Document> </Project> <Project Language="C#" AssemblyName="ClassLibrary2" CommonReferences="true"> <ProjectReference>ClassLibrary1</ProjectReference> <Document> namespace ClassLibrary2 { public class Class2 : ClassLibrary1.Class1 { virtual void [|$$M|]() { } } } </Document> </Project> </Workspace>, host:=host, renameTo:="A") End Using End Sub <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameOverrideMemberFromDerivedClass_abstract_override(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" AssemblyName="ClassLibrary1" CommonReferences="true"> <Document> namespace ClassLibrary1 { public abstract class Class1 { public virtual void [|M|](); } } </Document> </Project> <Project Language="C#" AssemblyName="ClassLibrary2" CommonReferences="true"> <ProjectReference>ClassLibrary1</ProjectReference> <Document> namespace ClassLibrary2 { public class Class2 : ClassLibrary1.Class1 { override void [|$$M|]() { } } } </Document> </Project> </Workspace>, host:=host, renameTo:="A") End Using End Sub End Class End Namespace
-1
dotnet/roslyn
56,011
React to string comparison changing on .NET Core
The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
jaredpar
"2021-08-30T17:18:52Z"
"2021-08-30T20:20:04Z"
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
4d99cda6e446e77dbb302e26388c1093bd3ef569
React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
./src/Compilers/VisualBasic/Portable/Symbols/AnonymousTypes/SynthesizedSymbols/AnonymousType_ToStringMethodSymbol.vb
' 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.Collections Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Partial Friend NotInheritable Class AnonymousTypeManager Partial Private NotInheritable Class AnonymousTypeToStringMethodSymbol Inherits SynthesizedRegularMethodBase Public Sub New(container As AnonymousTypeTemplateSymbol) MyBase.New(VisualBasic.VisualBasicSyntaxTree.Dummy.GetRoot(), container, WellKnownMemberNames.ObjectToString) End Sub Private ReadOnly Property AnonymousType As AnonymousTypeTemplateSymbol Get Return DirectCast(Me.m_containingType, AnonymousTypeTemplateSymbol) End Get End Property Public Overrides ReadOnly Property IsOverrides As Boolean Get Return True End Get End Property Public Overrides ReadOnly Property OverriddenMethod As MethodSymbol Get Return Me.AnonymousType.Manager.System_Object__ToString End Get End Property Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility Get Return Accessibility.Public End Get End Property Public Overrides ReadOnly Property IsSub As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property ReturnType As TypeSymbol Get Return AnonymousType.Manager.System_String End Get End Property Friend Overrides Sub AddSynthesizedAttributes(compilationState As ModuleCompilationState, ByRef attributes As ArrayBuilder(Of SynthesizedAttributeData)) MyBase.AddSynthesizedAttributes(compilationState, attributes) ' May call user-defined method. Dim compilation = DirectCast(Me.ContainingType, AnonymousTypeTemplateSymbol).Manager.Compilation AddSynthesizedAttribute(attributes, compilation.SynthesizeDebuggerHiddenAttribute()) End Sub 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
' 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.Collections Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Partial Friend NotInheritable Class AnonymousTypeManager Partial Private NotInheritable Class AnonymousTypeToStringMethodSymbol Inherits SynthesizedRegularMethodBase Public Sub New(container As AnonymousTypeTemplateSymbol) MyBase.New(VisualBasic.VisualBasicSyntaxTree.Dummy.GetRoot(), container, WellKnownMemberNames.ObjectToString) End Sub Private ReadOnly Property AnonymousType As AnonymousTypeTemplateSymbol Get Return DirectCast(Me.m_containingType, AnonymousTypeTemplateSymbol) End Get End Property Public Overrides ReadOnly Property IsOverrides As Boolean Get Return True End Get End Property Public Overrides ReadOnly Property OverriddenMethod As MethodSymbol Get Return Me.AnonymousType.Manager.System_Object__ToString End Get End Property Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility Get Return Accessibility.Public End Get End Property Public Overrides ReadOnly Property IsSub As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property ReturnType As TypeSymbol Get Return AnonymousType.Manager.System_String End Get End Property Friend Overrides Sub AddSynthesizedAttributes(compilationState As ModuleCompilationState, ByRef attributes As ArrayBuilder(Of SynthesizedAttributeData)) MyBase.AddSynthesizedAttributes(compilationState, attributes) ' May call user-defined method. Dim compilation = DirectCast(Me.ContainingType, AnonymousTypeTemplateSymbol).Manager.Compilation AddSynthesizedAttribute(attributes, compilation.SynthesizeDebuggerHiddenAttribute()) End Sub 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
-1
dotnet/roslyn
56,011
React to string comparison changing on .NET Core
The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
jaredpar
"2021-08-30T17:18:52Z"
"2021-08-30T20:20:04Z"
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
4d99cda6e446e77dbb302e26388c1093bd3ef569
React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
./src/VisualStudio/Core/Test/CodeModel/VisualBasic/ExternalCodePropertyTests.vb
' 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.Test.Utilities Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel.VisualBasic Public Class ExternalCodePropertyTests Inherits AbstractCodePropertyTests #Region "OverrideKind tests" <WorkItem(9646, "https://github.com/dotnet/roslyn/issues/9646")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestOverrideKind_None() Dim code = <Code> Class C Public Property $$P As Integer Get End Get Set(value As Integer) End Set End Property End Class </Code> TestOverrideKind(code, EnvDTE80.vsCMOverrideKind.vsCMOverrideKindNone) End Sub <WorkItem(9646, "https://github.com/dotnet/roslyn/issues/9646")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestOverrideKind_Abstract() Dim code = <Code> MustInherit Class C Public MustOverride Property $$P As Integer End Class </Code> TestOverrideKind(code, EnvDTE80.vsCMOverrideKind.vsCMOverrideKindAbstract) End Sub <WorkItem(9646, "https://github.com/dotnet/roslyn/issues/9646")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestOverrideKind_Virtual() Dim code = <Code> Class C Public Overridable Property $$P As Integer Get End Get Set(value As Integer) End Set End Property End Class </Code> TestOverrideKind(code, EnvDTE80.vsCMOverrideKind.vsCMOverrideKindVirtual) End Sub <WorkItem(9646, "https://github.com/dotnet/roslyn/issues/9646")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestOverrideKind_Override() Dim code = <Code> MustInherit Class A Public MustOverride Property P As Integer End Class Class C Inherits A Public Overrides Property $$P As Integer Get End Get Set(value As Integer) End Set End Property End Class </Code> TestOverrideKind(code, EnvDTE80.vsCMOverrideKind.vsCMOverrideKindOverride) End Sub <WorkItem(9646, "https://github.com/dotnet/roslyn/issues/9646")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestOverrideKind_Sealed() Dim code = <Code> MustInherit Class A Public MustOverride Property P As Integer End Class Class C Inherits A Public NotOverridable Overrides Property $$P As Integer Get End Get Set(value As Integer) End Set End Property End Class </Code> TestOverrideKind(code, EnvDTE80.vsCMOverrideKind.vsCMOverrideKindOverride Or EnvDTE80.vsCMOverrideKind.vsCMOverrideKindSealed) End Sub #End Region #Region "Parameter name tests" <WorkItem(9646, "https://github.com/dotnet/roslyn/issues/9646")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestParameterName() Dim code = <Code> Class C Property $$P(x As Integer, y as String) As Integer Get Return x * y End Get Set(value As Integer) End Set End Property End Class </Code> TestAllParameterNames(code, "x", "y") End Sub #End Region #Region "ReadWrite tests" <WorkItem(9646, "https://github.com/dotnet/roslyn/issues/9646")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestReadWrite_GetSet() Dim code = <Code> Class C Public Property $$P As Integer Get End Get Set(value As Integer) End Set End Property End Class </Code> TestReadWrite(code, EnvDTE80.vsCMPropertyKind.vsCMPropertyKindReadWrite) End Sub <WorkItem(9646, "https://github.com/dotnet/roslyn/issues/9646")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestReadWrite_Get() Dim code = <Code> Class C Public ReadOnly Property $$P As Integer Get End Get End Property End Class </Code> TestReadWrite(code, EnvDTE80.vsCMPropertyKind.vsCMPropertyKindReadOnly) End Sub <WorkItem(9646, "https://github.com/dotnet/roslyn/issues/9646")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestReadWrite_Set() Dim code = <Code> Class C Public WriteOnly Property $$P As Integer Set(value As Integer) End Set End Property End Class </Code> TestReadWrite(code, EnvDTE80.vsCMPropertyKind.vsCMPropertyKindWriteOnly) End Sub #End Region Protected Overrides ReadOnly Property LanguageName As String = LanguageNames.VisualBasic Protected Overrides ReadOnly Property TargetExternalCodeElements As Boolean = True End Class End Namespace
' 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.Test.Utilities Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel.VisualBasic Public Class ExternalCodePropertyTests Inherits AbstractCodePropertyTests #Region "OverrideKind tests" <WorkItem(9646, "https://github.com/dotnet/roslyn/issues/9646")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestOverrideKind_None() Dim code = <Code> Class C Public Property $$P As Integer Get End Get Set(value As Integer) End Set End Property End Class </Code> TestOverrideKind(code, EnvDTE80.vsCMOverrideKind.vsCMOverrideKindNone) End Sub <WorkItem(9646, "https://github.com/dotnet/roslyn/issues/9646")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestOverrideKind_Abstract() Dim code = <Code> MustInherit Class C Public MustOverride Property $$P As Integer End Class </Code> TestOverrideKind(code, EnvDTE80.vsCMOverrideKind.vsCMOverrideKindAbstract) End Sub <WorkItem(9646, "https://github.com/dotnet/roslyn/issues/9646")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestOverrideKind_Virtual() Dim code = <Code> Class C Public Overridable Property $$P As Integer Get End Get Set(value As Integer) End Set End Property End Class </Code> TestOverrideKind(code, EnvDTE80.vsCMOverrideKind.vsCMOverrideKindVirtual) End Sub <WorkItem(9646, "https://github.com/dotnet/roslyn/issues/9646")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestOverrideKind_Override() Dim code = <Code> MustInherit Class A Public MustOverride Property P As Integer End Class Class C Inherits A Public Overrides Property $$P As Integer Get End Get Set(value As Integer) End Set End Property End Class </Code> TestOverrideKind(code, EnvDTE80.vsCMOverrideKind.vsCMOverrideKindOverride) End Sub <WorkItem(9646, "https://github.com/dotnet/roslyn/issues/9646")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestOverrideKind_Sealed() Dim code = <Code> MustInherit Class A Public MustOverride Property P As Integer End Class Class C Inherits A Public NotOverridable Overrides Property $$P As Integer Get End Get Set(value As Integer) End Set End Property End Class </Code> TestOverrideKind(code, EnvDTE80.vsCMOverrideKind.vsCMOverrideKindOverride Or EnvDTE80.vsCMOverrideKind.vsCMOverrideKindSealed) End Sub #End Region #Region "Parameter name tests" <WorkItem(9646, "https://github.com/dotnet/roslyn/issues/9646")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestParameterName() Dim code = <Code> Class C Property $$P(x As Integer, y as String) As Integer Get Return x * y End Get Set(value As Integer) End Set End Property End Class </Code> TestAllParameterNames(code, "x", "y") End Sub #End Region #Region "ReadWrite tests" <WorkItem(9646, "https://github.com/dotnet/roslyn/issues/9646")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestReadWrite_GetSet() Dim code = <Code> Class C Public Property $$P As Integer Get End Get Set(value As Integer) End Set End Property End Class </Code> TestReadWrite(code, EnvDTE80.vsCMPropertyKind.vsCMPropertyKindReadWrite) End Sub <WorkItem(9646, "https://github.com/dotnet/roslyn/issues/9646")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestReadWrite_Get() Dim code = <Code> Class C Public ReadOnly Property $$P As Integer Get End Get End Property End Class </Code> TestReadWrite(code, EnvDTE80.vsCMPropertyKind.vsCMPropertyKindReadOnly) End Sub <WorkItem(9646, "https://github.com/dotnet/roslyn/issues/9646")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestReadWrite_Set() Dim code = <Code> Class C Public WriteOnly Property $$P As Integer Set(value As Integer) End Set End Property End Class </Code> TestReadWrite(code, EnvDTE80.vsCMPropertyKind.vsCMPropertyKindWriteOnly) End Sub #End Region Protected Overrides ReadOnly Property LanguageName As String = LanguageNames.VisualBasic Protected Overrides ReadOnly Property TargetExternalCodeElements As Boolean = True End Class End Namespace
-1
dotnet/roslyn
56,011
React to string comparison changing on .NET Core
The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
jaredpar
"2021-08-30T17:18:52Z"
"2021-08-30T20:20:04Z"
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
4d99cda6e446e77dbb302e26388c1093bd3ef569
React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
./src/Compilers/VisualBasic/Test/Emit/XmlLiteralTests.vb
' 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.IO Imports System.Text Imports Microsoft.Cci Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class XmlLiteralTests Inherits BasicTestBase <Fact()> Public Sub XComment() Dim compilation = CompileAndVerify( <compilation> <file name="c.vb"><![CDATA[ Module M Private F = <!-- comment --> Sub Main() System.Console.WriteLine("{0}", F) End Sub End Module ]]></file> </compilation>, references:=Net40XmlReferences, expectedOutput:=<![CDATA[ <!-- comment --> ]]>) compilation.VerifyIL("M..cctor", <![CDATA[ { // Code size 16 (0x10) .maxstack 1 IL_0000: ldstr " comment " IL_0005: newobj "Sub System.Xml.Linq.XComment..ctor(String)" IL_000a: stsfld "M.F As Object" IL_000f: ret } ]]>) End Sub <Fact()> Public Sub XDocument() Dim compilation = CompileAndVerify( <compilation> <file name="c.vb"><![CDATA[ Module M Sub Main() Dim x = <?xml version="1.0"?> <!-- A --> <?p?> <x> <!-- B --> <?q?> </x> <?r?> <!-- C--> Report(x) Report(x.Declaration) End Sub Sub Report(o As Object) System.Console.WriteLine("{0}", o) End Sub End Module ]]></file> </compilation>, references:=XmlReferences, expectedOutput:=<![CDATA[ <!-- A --> <?p?> <x> <!-- B --> <?q?> </x> <?r?> <!-- C--> <?xml version="1.0"?> ]]>) compilation.VerifyIL("M.Main", <![CDATA[ { // Code size 172 (0xac) .maxstack 6 IL_0000: ldstr "1.0" IL_0005: ldnull IL_0006: ldnull IL_0007: newobj "Sub System.Xml.Linq.XDeclaration..ctor(String, String, String)" IL_000c: ldnull IL_000d: newobj "Sub System.Xml.Linq.XDocument..ctor(System.Xml.Linq.XDeclaration, ParamArray Object())" IL_0012: dup IL_0013: ldstr " A " IL_0018: newobj "Sub System.Xml.Linq.XComment..ctor(String)" IL_001d: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_0022: dup IL_0023: ldstr "p" IL_0028: ldstr "" IL_002d: newobj "Sub System.Xml.Linq.XProcessingInstruction..ctor(String, String)" IL_0032: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_0037: dup IL_0038: ldstr "x" IL_003d: ldstr "" IL_0042: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0047: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_004c: dup IL_004d: ldstr " B " IL_0052: newobj "Sub System.Xml.Linq.XComment..ctor(String)" IL_0057: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_005c: dup IL_005d: ldstr "q" IL_0062: ldstr "" IL_0067: newobj "Sub System.Xml.Linq.XProcessingInstruction..ctor(String, String)" IL_006c: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_0071: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_0076: dup IL_0077: ldstr "r" IL_007c: ldstr "" IL_0081: newobj "Sub System.Xml.Linq.XProcessingInstruction..ctor(String, String)" IL_0086: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_008b: dup IL_008c: ldstr " C" IL_0091: newobj "Sub System.Xml.Linq.XComment..ctor(String)" IL_0096: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_009b: dup IL_009c: call "Sub M.Report(Object)" IL_00a1: callvirt "Function System.Xml.Linq.XDocument.get_Declaration() As System.Xml.Linq.XDeclaration" IL_00a6: call "Sub M.Report(Object)" IL_00ab: ret } ]]>) End Sub <Fact()> Public Sub AttributeNamespace() Dim compilation = CompileAndVerify( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports System Imports System.Linq Imports System.Xml.Linq Imports <xmlns="http://roslyn/default1"> Class C Private Shared F1 As XElement = <x a="1"/> Private Shared F2 As XElement = <x xmlns="http://roslyn/default2" a="2"/> Private Shared F4 As XElement = <p:x xmlns:p="http://roslyn/p4" a="4"/> Private Shared F5 As XElement = <x xmlns="http://roslyn/default5" xmlns:p="http://roslyn/p5" p:a="5"/> Shared Sub Main() Report(F0) Report(F1) Report(F2) Report(F3) Report(F4) Report(F5) End Sub Shared Sub Report(x As XElement) Console.WriteLine("{0}", x) Dim a = x.Attributes().First(Function(o) o.Name.LocalName = "a") Console.WriteLine("{0}, {1}", x.Name, a.Name) End Sub End Class ]]> </file> <file name="b.vb"><![CDATA[ Option Strict On Imports System.Xml.Linq Partial Class C Private Shared F0 As XElement = <x a="0"/> Private Shared F3 As XElement = <p:x xmlns:p="http://roslyn/p3" a="3"/> End Class ]]> </file> </compilation>, references:=XmlReferences, expectedOutput:=<![CDATA[ <x a="0" /> x, a <x a="1" xmlns="http://roslyn/default1" /> {http://roslyn/default1}x, a <x xmlns="http://roslyn/default2" a="2" /> {http://roslyn/default2}x, a <p:x xmlns:p="http://roslyn/p3" a="3" /> {http://roslyn/p3}x, a <p:x xmlns:p="http://roslyn/p4" a="4" /> {http://roslyn/p4}x, a <x xmlns="http://roslyn/default5" xmlns:p="http://roslyn/p5" p:a="5" /> {http://roslyn/default5}x, {http://roslyn/p5}a ]]>) End Sub <Fact()> Public Sub MemberAccess() Dim compilation = CompileAndVerify( <compilation> <file name="c.vb"><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Imports System.Xml.Linq Imports <xmlns:r1="http://roslyn"> Module M Sub Main() Dim x = <a xmlns:r2="http://roslyn" r1:b="a.b"> <b>1</b> <r2:c>2</r2:c> <c d="c.d">3</c> <b>4</b> <b/> </a> Report(x.<b>) Report(x.<c>) Report(x.<r1:c>) Report(x.@r1:b) Report(x.@xmlns:r2) End Sub Sub Report(x As IEnumerable(Of XElement)) For Each e In x Console.WriteLine("{0}", e.Value) Dim a = e.@d If a IsNot Nothing Then Console.WriteLine(" {0}", a) End If Next End Sub Sub Report(s As String) Console.WriteLine("{0}", s) End Sub End Module ]]></file> </compilation>, references:=XmlReferences, expectedOutput:=<![CDATA[ 1 4 3 c.d 2 a.b http://roslyn ]]>) compilation.VerifyIL("M.Main", <![CDATA[ { // Code size 453 (0x1c5) .maxstack 6 IL_0000: ldstr "a" IL_0005: ldstr "" IL_000a: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_000f: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_0014: dup IL_0015: ldstr "r2" IL_001a: ldstr "http://www.w3.org/2000/xmlns/" IL_001f: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0024: ldstr "http://roslyn" IL_0029: newobj "Sub System.Xml.Linq.XAttribute..ctor(System.Xml.Linq.XName, Object)" IL_002e: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_0033: dup IL_0034: ldstr "b" IL_0039: ldstr "http://roslyn" IL_003e: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0043: ldstr "a.b" IL_0048: newobj "Sub System.Xml.Linq.XAttribute..ctor(System.Xml.Linq.XName, Object)" IL_004d: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_0052: dup IL_0053: ldstr "b" IL_0058: ldstr "" IL_005d: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0062: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_0067: dup IL_0068: ldstr "1" IL_006d: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_0072: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_0077: dup IL_0078: ldstr "c" IL_007d: ldstr "http://roslyn" IL_0082: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0087: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_008c: dup IL_008d: ldstr "2" IL_0092: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_0097: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_009c: dup IL_009d: ldstr "c" IL_00a2: ldstr "" IL_00a7: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_00ac: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_00b1: dup IL_00b2: ldstr "d" IL_00b7: ldstr "" IL_00bc: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_00c1: ldstr "c.d" IL_00c6: newobj "Sub System.Xml.Linq.XAttribute..ctor(System.Xml.Linq.XName, Object)" IL_00cb: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_00d0: dup IL_00d1: ldstr "3" IL_00d6: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_00db: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_00e0: dup IL_00e1: ldstr "b" IL_00e6: ldstr "" IL_00eb: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_00f0: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_00f5: dup IL_00f6: ldstr "4" IL_00fb: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_0100: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_0105: dup IL_0106: ldstr "b" IL_010b: ldstr "" IL_0110: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0115: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_011a: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_011f: dup IL_0120: ldstr "r1" IL_0125: ldstr "http://www.w3.org/2000/xmlns/" IL_012a: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_012f: ldstr "http://roslyn" IL_0134: call "Function System.Xml.Linq.XNamespace.Get(String) As System.Xml.Linq.XNamespace" IL_0139: call "Function My.InternalXmlHelper.CreateNamespaceAttribute(System.Xml.Linq.XName, System.Xml.Linq.XNamespace) As System.Xml.Linq.XAttribute" IL_013e: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_0143: dup IL_0144: ldstr "b" IL_0149: ldstr "" IL_014e: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0153: callvirt "Function System.Xml.Linq.XContainer.Elements(System.Xml.Linq.XName) As System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)" IL_0158: call "Sub M.Report(System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement))" IL_015d: dup IL_015e: ldstr "c" IL_0163: ldstr "" IL_0168: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_016d: callvirt "Function System.Xml.Linq.XContainer.Elements(System.Xml.Linq.XName) As System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)" IL_0172: call "Sub M.Report(System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement))" IL_0177: dup IL_0178: ldstr "c" IL_017d: ldstr "http://roslyn" IL_0182: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0187: callvirt "Function System.Xml.Linq.XContainer.Elements(System.Xml.Linq.XName) As System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)" IL_018c: call "Sub M.Report(System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement))" IL_0191: dup IL_0192: ldstr "b" IL_0197: ldstr "http://roslyn" IL_019c: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_01a1: call "Function My.InternalXmlHelper.get_AttributeValue(System.Xml.Linq.XElement, System.Xml.Linq.XName) As String" IL_01a6: call "Sub M.Report(String)" IL_01ab: ldstr "r2" IL_01b0: ldstr "http://www.w3.org/2000/xmlns/" IL_01b5: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_01ba: call "Function My.InternalXmlHelper.get_AttributeValue(System.Xml.Linq.XElement, System.Xml.Linq.XName) As String" IL_01bf: call "Sub M.Report(String)" IL_01c4: ret } ]]>) End Sub <Fact()> Public Sub MemberAccess_DistinctDefaultNamespaces() Dim compilation = CompileAndVerify( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports System Imports System.Xml.Linq Imports <xmlns:p="http://roslyn/p"> Imports <xmlns:q="http://roslyn/q"> Partial Class C Private Shared F1 As XElement = <x xmlns="http://roslyn/p" a="a1" p:b="b1"/> Private Shared F2 As XElement = <p:x a="a1" q:b="b1"/> Shared Sub Main() Report(F1) Report(F2) Report(F3) Report(F4) End Sub Private Shared Sub Report(x As XElement) Console.WriteLine("{0}", x) Report(x.@<a>) Report(x.@<p:a>) Report(x.@<q:a>) Report(x.@<b>) Report(x.@<p:b>) Report(x.@<q:b>) End Sub Private Shared Sub Report(s As String) Console.WriteLine("{0}", If(s, "[none]")) End Sub End Class ]]></file> <file name="b.vb"><![CDATA[ Option Strict On Imports System.Xml.Linq Imports <xmlns:p1="http://roslyn/p"> Imports <xmlns:p2="http://roslyn/q"> Partial Class C Private Shared F3 As XElement = <x xmlns="http://roslyn/q" a="a2" p1:b="b2"/> Private Shared F4 As XElement = <p1:x a="a2" p2:b="b2"/> End Class ]]></file> </compilation>, references:=XmlReferences, expectedOutput:=<![CDATA[ <p:x xmlns="http://roslyn/p" a="a1" p:b="b1" xmlns:p="http://roslyn/p" /> a1 [none] [none] [none] b1 [none] <p:x a="a1" q:b="b1" xmlns:q="http://roslyn/q" xmlns:p="http://roslyn/p" /> a1 [none] [none] [none] [none] b1 <x xmlns="http://roslyn/q" a="a2" p1:b="b2" xmlns:p1="http://roslyn/p" /> a2 [none] [none] [none] b2 [none] <p1:x a="a2" p2:b="b2" xmlns:p2="http://roslyn/q" xmlns:p1="http://roslyn/p" /> a2 [none] [none] [none] [none] b2 ]]>) End Sub <Fact()> Public Sub MemberAccessXmlns() Dim compilation = CompileAndVerify( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports System Imports System.Linq Module M Sub Main() Console.WriteLine("{0}", <x/>.<xmlns>.Count()) Console.WriteLine("{0}", <x/>.@xmlns) Console.WriteLine("{0}", <x xmlns="http://roslyn/default"/>.@xmlns) Console.WriteLine("{0}", <x xmlns:p="http://roslyn/p"/>.@<xmlns:p>) End Sub End Module ]]></file> </compilation>, references:=XmlReferences, expectedOutput:=<![CDATA[ 0 http://roslyn/default http://roslyn/p ]]>) End Sub <Fact()> Public Sub MemberAccessXmlns_DistinctDefaultNamespaces() Dim compilation = CompileAndVerify( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports System Imports System.Xml.Linq Imports <xmlns="http://roslyn/default1"> Imports <xmlns:default1="http://roslyn/default1"> Imports <xmlns:default2="http://roslyn/default2"> Partial Class C Private Shared F1 As XElement = <x xmlns="http://roslyn/1" xmlns:p="http://roslyn/p"/> Shared Sub Main() Report(F1) Report(F2) End Sub Private Shared Sub Report(x As XElement) Console.WriteLine("{0}", x) Report(x.@<xmlns>) Report(x.@<default1:xmlns>) Report(x.@<default2:xmlns>) End Sub Private Shared Sub Report(s As String) Console.WriteLine("{0}", If(s, "[none]")) End Sub End Class ]]></file> <file name="b.vb"><![CDATA[ Option Strict On Imports System.Xml.Linq Imports <xmlns="http://roslyn/default2"> Partial Class C Private Shared F2 As XElement = <x xmlns="http://roslyn/2" xmlns:q="http://roslyn/q"/> End Class ]]></file> </compilation>, references:=XmlReferences, expectedOutput:=<![CDATA[ <x xmlns="http://roslyn/1" xmlns:p="http://roslyn/p" /> http://roslyn/1 [none] [none] <x xmlns="http://roslyn/2" xmlns:q="http://roslyn/q" /> http://roslyn/2 [none] [none] ]]>) End Sub <Fact()> Public Sub MemberAccessIEnumerableOfXElement() Dim compilation = CompileAndVerify( <compilation> <file name="c.vb"><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Imports System.Xml.Linq Module M Property P1 As XElement = <a><b c="1"/><b c="2"/></a> Property P2 As IEnumerable(Of XElement) = P1.<b> Property P3 As XElement = <a> <b><c>1</c></b> <b><c>2</c></b> </a> Property P4 As IEnumerable(Of XElement) = P3.<b> Sub Main() Report(P1.<b>.@c) Report(P2.@c) Report(P3.<b>.<c>) Report(P4.<c>) End Sub Sub Report(s As String) Console.WriteLine("{0}", s) End Sub Sub Report(c As IEnumerable(Of XElement)) For Each o In c Console.WriteLine("{0}", o) Next End Sub End Module ]]></file> </compilation>, references:=XmlReferences, expectedOutput:=<![CDATA[ 1 1 <c>1</c> <c>2</c> <c>1</c> <c>2</c> ]]>) compilation.VerifyIL("M.Main", <![CDATA[ { // Code size 161 (0xa1) .maxstack 3 IL_0000: call "Function M.get_P1() As System.Xml.Linq.XElement" IL_0005: ldstr "b" IL_000a: ldstr "" IL_000f: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0014: callvirt "Function System.Xml.Linq.XContainer.Elements(System.Xml.Linq.XName) As System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)" IL_0019: ldstr "c" IL_001e: ldstr "" IL_0023: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0028: call "Function My.InternalXmlHelper.get_AttributeValue(System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement), System.Xml.Linq.XName) As String" IL_002d: call "Sub M.Report(String)" IL_0032: call "Function M.get_P2() As System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)" IL_0037: ldstr "c" IL_003c: ldstr "" IL_0041: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0046: call "Function My.InternalXmlHelper.get_AttributeValue(System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement), System.Xml.Linq.XName) As String" IL_004b: call "Sub M.Report(String)" IL_0050: call "Function M.get_P3() As System.Xml.Linq.XElement" IL_0055: ldstr "b" IL_005a: ldstr "" IL_005f: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0064: callvirt "Function System.Xml.Linq.XContainer.Elements(System.Xml.Linq.XName) As System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)" IL_0069: ldstr "c" IL_006e: ldstr "" IL_0073: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0078: call "Function System.Xml.Linq.Extensions.Elements(Of System.Xml.Linq.XElement)(System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement), System.Xml.Linq.XName) As System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)" IL_007d: call "Sub M.Report(System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement))" IL_0082: call "Function M.get_P4() As System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)" IL_0087: ldstr "c" IL_008c: ldstr "" IL_0091: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0096: call "Function System.Xml.Linq.Extensions.Elements(Of System.Xml.Linq.XElement)(System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement), System.Xml.Linq.XName) As System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)" IL_009b: call "Sub M.Report(System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement))" IL_00a0: ret } ]]>) End Sub <Fact()> Public Sub DescendantAccess() Dim compilation = CompileAndVerify( <compilation> <file name="c.vb"><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Xml.Linq Imports <xmlns:p="http://roslyn/p"> Imports <xmlns:q="http://roslyn/q"> Module M Sub Main() M(<a> <c>1</> <b> <q:c>2</> <p3:c xmlns:p3="http://roslyn/p">3</> </b> <b> <c>4</> <p5:c xmlns:p5="http://roslyn/p">5</> </b> </a>) End Sub Sub M(x As XElement) Report(x...<c>) Report(x...<b>...<p:c>) End Sub Sub Report(c As IEnumerable(Of XElement)) For Each x In c Console.WriteLine("{0}", x) Next End Sub End Module ]]></file> </compilation>, references:=XmlReferences, expectedOutput:=<![CDATA[ <c>1</c> <c>4</c> <p3:c xmlns:p3="http://roslyn/p">3</p3:c> <p5:c xmlns:p5="http://roslyn/p">5</p5:c> ]]>) compilation.VerifyIL("M.M", <![CDATA[ { // Code size 73 (0x49) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldstr "c" IL_0006: ldstr "" IL_000b: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0010: callvirt "Function System.Xml.Linq.XContainer.Descendants(System.Xml.Linq.XName) As System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)" IL_0015: call "Sub M.Report(System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement))" IL_001a: ldarg.0 IL_001b: ldstr "b" IL_0020: ldstr "" IL_0025: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_002a: callvirt "Function System.Xml.Linq.XContainer.Descendants(System.Xml.Linq.XName) As System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)" IL_002f: ldstr "c" IL_0034: ldstr "http://roslyn/p" IL_0039: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_003e: call "Function System.Xml.Linq.Extensions.Descendants(Of System.Xml.Linq.XElement)(System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement), System.Xml.Linq.XName) As System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)" IL_0043: call "Sub M.Report(System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement))" IL_0048: ret } ]]>) End Sub <Fact()> Public Sub MemberAccessReceiverNotRValue() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports System.Xml.Linq Module M ReadOnly Property P As XElement Get Return Nothing End Get End Property WriteOnly Property Q As XElement Set(value As XElement) End Set End Property Sub M() Dim o As Object o = P.<x> o = P.@x o = Q.<x> o = Q.@x With P o = ...<x> .@<a> = "b" End With With Q o = ...<y> .@<c> = "d" End With End Sub End Module ]]></file> </compilation>, references:=XmlReferences) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC30524: Property 'Q' is 'WriteOnly'. o = Q.<x> ~ BC30524: Property 'Q' is 'WriteOnly'. o = Q.@x ~ BC30524: Property 'Q' is 'WriteOnly'. With Q ~ ]]></errors>) End Sub ' Should not report cascading member access errors ' if the receiver is an error type. <Fact()> Public Sub MemberAccessUnknownReceiver() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Module M Sub M() Dim x As C = Nothing Dim y As Object y = x.<y> y = x...<y> y = x.@a End Sub End Module ]]></file> </compilation>, references:=XmlReferences) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC30002: Type 'C' is not defined. Dim x As C = Nothing ~ ]]></errors>) End Sub <Fact()> Public Sub MemberAccessUntypedReceiver() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Module M Sub M() Dim o As Object o = Nothing.<x> o = Nothing.@a o = (Function() Nothing)...<x> o = (Function() Nothing).@<a> With Nothing o = .<x> End With With (Function() Nothing) .@a = "b" End With End Sub End Module ]]></file> </compilation>, references:=XmlReferences) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC31168: XML axis properties do not support late binding. o = Nothing.<x> ~~~~~~~~~~~ BC31168: XML axis properties do not support late binding. o = Nothing.@a ~~~~~~~~~~ BC36809: XML descendant elements cannot be selected from type 'Function <generated method>() As Object'. o = (Function() Nothing)...<x> ~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36808: XML attributes cannot be selected from type 'Function <generated method>() As Object'. o = (Function() Nothing).@<a> ~~~~~~~~~~~~~~~~~~~~~~~~~ BC31168: XML axis properties do not support late binding. o = .<x> ~~~~ BC36808: XML attributes cannot be selected from type 'Function <generated method>() As Object'. .@a = "b" ~~~ ]]></errors>) End Sub <Fact()> Public Sub MemberAccessImplicitReceiver() Dim compilation = CompileAndVerify( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports System Imports System.Collections.Generic Imports System.Linq Imports System.Xml.Linq Module M Function F1(x As XElement) As IEnumerable(Of XElement) With x Return .<y> End With End Function Function F2(x As XElement) As IEnumerable(Of XElement) With x Return ...<y> End With End Function Function F3(x As XElement) As Object With x Return .@a End With End Function Function F4(x As XElement) As Object With x .@<b> = .@<a> End With Return x End Function Sub Main() Console.WriteLine("{0}", F1(<x1><y/></x1>).FirstOrDefault()) Console.WriteLine("{0}", F2(<x2><y/></x2>).FirstOrDefault()) Console.WriteLine("{0}", F3(<x3 a="1"/>)) Console.WriteLine("{0}", F4(<x4 a="2"/>)) End Sub End Module ]]></file> </compilation>, references:=XmlReferences, expectedOutput:=<![CDATA[ <y /> <y /> 1 <x4 a="2" b="2" /> ]]>) End Sub <Fact()> Public Sub MemberAccessImplicitReceiverLambda() Dim compilation = CompileAndVerify( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports System Imports System.Collections Imports System.Collections.Generic Imports System.Linq Imports System.Xml.Linq Class C Implements IEnumerable(Of XElement) Private value As IEnumerable(Of XElement) = {<x a="1"><y/></x>} Public Function F1() As IEnumerable(Of XElement) With Me Return (Function() .<y>)() End With End Function Public Function F2() As IEnumerable(Of XElement) With Me Return (Function() ...<y>)() End With End Function Public Function F3() As Object With Me Return (Function() .@a)() End With End Function Public Function F4() As IEnumerable(Of XElement) With Me Dim a As Action = Sub() .@<b> = .@<a> a() End With Return Me End Function Private Function GetEnumerator() As IEnumerator(Of XElement) Implements IEnumerable(Of XElement).GetEnumerator Return value.GetEnumerator() End Function Private Function GetEnumerator1() As IEnumerator Implements IEnumerable.GetEnumerator Return Nothing End Function End Class Module M Sub Main() Dim o As New C() Console.WriteLine("{0}", o.F1().FirstOrDefault()) Console.WriteLine("{0}", o.F2().FirstOrDefault()) Console.WriteLine("{0}", o.F3()) Console.WriteLine("{0}", o.F4().FirstOrDefault()) End Sub End Module ]]></file> </compilation>, references:=XmlReferences, expectedOutput:=<![CDATA[ <y /> <y /> 1 <x a="1" b="1"> <y /> </x> ]]>) End Sub <Fact()> Public Sub MemberAccessImplicitReceiverLambdaCannotLiftMe() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports System Imports System.Collections Imports System.Collections.Generic Imports System.Xml.Linq Structure S Implements IEnumerable(Of XElement) Public Function F1() As IEnumerable(Of XElement) With Me Return (Function() .<y>)() End With End Function Public Function F2() As IEnumerable(Of XElement) With Me Return (Function() ...<y>)() End With End Function Public Function F3() As Object With Me Return (Function() .@a)() End With End Function Public Function F4() As IEnumerable(Of XElement) With Me Dim a As Action = Sub() .@<b> = .@<a> a() End With Return Me End Function Private Function GetEnumerator() As IEnumerator(Of XElement) Implements IEnumerable(Of XElement).GetEnumerator Return Nothing End Function Private Function GetEnumerator1() As IEnumerator Implements IEnumerable.GetEnumerator Return Nothing End Function End Structure ]]></file> </compilation>, references:=XmlReferences) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC36638: Instance members and 'Me' cannot be used within a lambda expression in structures. Return (Function() .<y>)() ~~~~ BC36638: Instance members and 'Me' cannot be used within a lambda expression in structures. Return (Function() ...<y>)() ~~~~~~ BC36638: Instance members and 'Me' cannot be used within a lambda expression in structures. Return (Function() .@a)() ~~~ BC36638: Instance members and 'Me' cannot be used within a lambda expression in structures. Dim a As Action = Sub() .@<b> = .@<a> ~~~~~ BC36638: Instance members and 'Me' cannot be used within a lambda expression in structures. Dim a As Action = Sub() .@<b> = .@<a> ~~~~~ ]]></errors>) End Sub <Fact()> Public Sub MemberAccessIncludeNamespaces() Dim compilation = CompileAndVerify( <compilation> <file name="c.vb"><![CDATA[ Imports <xmlns:p="http://roslyn"> Module M Sub Main() Dim x = <pa:a xmlns:pa="http://roslyn"> <pb:b xmlns:pb="http://roslyn"/> <pa:c/> <p:d/> </pa:a> Report(x.<p:b>) Report(x.<p:c>) Report(x.<p:d>) End Sub Sub Report(c As System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)) For Each x In c System.Console.WriteLine("{0}", x) Next End Sub End Module ]]></file> </compilation>, references:=XmlReferences, expectedOutput:=<![CDATA[ <pb:b xmlns:pb="http://roslyn" /> <pa:c xmlns:pa="http://roslyn" /> <pa:d xmlns:pa="http://roslyn" /> ]]>) End Sub <Fact()> Public Sub MemberAccessAssignment() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports System.Collections.Generic Imports System.Xml.Linq Module M Sub M() Dim x = <x/> x.<y> = Nothing x.<y>.<z> = Nothing x...<y> = Nothing x...<y>...<z> = Nothing N(x.<y>) N(x.<y>.<z>) N(x...<y>) N(x...<y>...<z>) End Sub Sub N(ByRef o As IEnumerable(Of XElement)) End Sub End Module ]]></file> </compilation>, references:=XmlReferences) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC30068: Expression is a value and therefore cannot be the target of an assignment. x.<y> = Nothing ~~~~~ BC30068: Expression is a value and therefore cannot be the target of an assignment. x.<y>.<z> = Nothing ~~~~~~~~~ BC30068: Expression is a value and therefore cannot be the target of an assignment. x...<y> = Nothing ~~~~~~~ BC30068: Expression is a value and therefore cannot be the target of an assignment. x...<y>...<z> = Nothing ~~~~~~~~~~~~~ ]]></errors>) End Sub <Fact()> Public Sub MemberAccessAttributeAssignment() Dim compilation = CompileAndVerify( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports <xmlns:y="http://roslyn"> Module M Sub Main() Dim x = <x a="1"><y/><y/></x> Report(x) x.@a = "2" x.<y>.@y:b = "3" N(x.@c, "4") N(x.<y>.@y:d, "5") Report(x) End Sub Sub N(ByRef x As String, y As String) x = y End Sub Sub Report(o As Object) System.Console.WriteLine("{0}", o) End Sub End Module ]]></file> </compilation>, references:=XmlReferences, expectedOutput:=<![CDATA[ <x a="1"> <y /> <y /> </x> <x a="2" c="4"> <y p2:b="3" p2:d="5" xmlns:p2="http://roslyn" /> <y /> </x> ]]>) End Sub <Fact()> Public Sub MemberAccessAttributeCompoundAssignment() Dim compilation = CompileAndVerify( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Module M Sub Main() Dim x = <x a="1"/> x.@a += "2" x.@b += "3" System.Console.WriteLine("{0}", x) End Sub End Module ]]> </file> </compilation>, references:=XmlReferences, expectedOutput:=<![CDATA[ <x a="12" b="3" /> ]]>) End Sub <Fact()> Public Sub MemberAccessAttributeAsReceiver() Dim compilation = CompileAndVerify( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Module M Sub Main() System.Console.WriteLine("{0}", <x a="b"/>[email protected]()) System.Console.WriteLine("{0}", <x><y>c</y></x>.<y>.Value) End Sub End Module ]]></file> </compilation>, references:=XmlReferences, expectedOutput:=<![CDATA[ b c ]]>) End Sub <Fact()> Public Sub MemberAccessAttributeByRefExtensionMethod() Dim compilation = CompileAndVerify( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports System.Runtime.CompilerServices Module M Sub Main() Dim x = <x a="1"/> [email protected]("2") System.Console.WriteLine("{0}", x) End Sub <Extension()> Sub M(ByRef x As String, y As String) x = y End Sub End Module ]]> </file> </compilation>, references:=Net40XmlReferences, expectedOutput:=<![CDATA[ <x a="2" /> ]]>) End Sub <Fact()> Public Sub MemberAccessAttributeAddressOf() Dim compilation = CompileAndVerify( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports System Module M Sub Main() Dim d As Func(Of String) = AddressOf <x a="b"/>[email protected] Console.WriteLine("{0}", d()) End Sub End Module ]]> </file> </compilation>, references:=Net40XmlReferences, expectedOutput:="b") End Sub ' Project-level imports should be used if file-level ' imports do not contain namespace. <Fact()> Public Sub ProjectImports() Dim options = TestOptions.ReleaseExe.WithGlobalImports(GlobalImport.Parse({"<xmlns=""default1"">", "<xmlns:p=""p1"">", "<xmlns:q=""q1"">"})) Dim compilation = CompileAndVerify( <compilation> <file name="c.vb"><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Xml.Linq Imports <xmlns:q="q2"> Class C Shared Sub Main() Dim x = <a> <b/> <p:b/> <q:b/> </a> Report(x.<b>) Report(x.<p:b>) Report(x.<q:b>) End Sub Shared Sub Report(c As IEnumerable(Of XElement)) For Each i In c Console.WriteLine(i.Name.Namespace) Next End Sub End Class ]]></file> </compilation>, references:=Net40XmlReferences, options:=options, expectedOutput:=<![CDATA[ default1 p1 q2 ]]>) compilation.VerifyIL("C.Main", <![CDATA[ { // Code size 284 (0x11c) .maxstack 4 IL_0000: ldstr "a" IL_0005: ldstr "default1" IL_000a: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_000f: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_0014: dup IL_0015: ldstr "b" IL_001a: ldstr "default1" IL_001f: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0024: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_0029: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_002e: dup IL_002f: ldstr "b" IL_0034: ldstr "p1" IL_0039: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_003e: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_0043: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_0048: dup IL_0049: ldstr "b" IL_004e: ldstr "q2" IL_0053: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0058: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_005d: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_0062: dup IL_0063: ldstr "q" IL_0068: ldstr "http://www.w3.org/2000/xmlns/" IL_006d: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0072: ldstr "q2" IL_0077: call "Function System.Xml.Linq.XNamespace.Get(String) As System.Xml.Linq.XNamespace" IL_007c: call "Function My.InternalXmlHelper.CreateNamespaceAttribute(System.Xml.Linq.XName, System.Xml.Linq.XNamespace) As System.Xml.Linq.XAttribute" IL_0081: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_0086: dup IL_0087: ldstr "p" IL_008c: ldstr "http://www.w3.org/2000/xmlns/" IL_0091: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0096: ldstr "p1" IL_009b: call "Function System.Xml.Linq.XNamespace.Get(String) As System.Xml.Linq.XNamespace" IL_00a0: call "Function My.InternalXmlHelper.CreateNamespaceAttribute(System.Xml.Linq.XName, System.Xml.Linq.XNamespace) As System.Xml.Linq.XAttribute" IL_00a5: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_00aa: dup IL_00ab: ldstr "xmlns" IL_00b0: ldstr "" IL_00b5: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_00ba: ldstr "default1" IL_00bf: call "Function System.Xml.Linq.XNamespace.Get(String) As System.Xml.Linq.XNamespace" IL_00c4: call "Function My.InternalXmlHelper.CreateNamespaceAttribute(System.Xml.Linq.XName, System.Xml.Linq.XNamespace) As System.Xml.Linq.XAttribute" IL_00c9: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_00ce: dup IL_00cf: ldstr "b" IL_00d4: ldstr "default1" IL_00d9: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_00de: callvirt "Function System.Xml.Linq.XContainer.Elements(System.Xml.Linq.XName) As System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)" IL_00e3: call "Sub C.Report(System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement))" IL_00e8: dup IL_00e9: ldstr "b" IL_00ee: ldstr "p1" IL_00f3: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_00f8: callvirt "Function System.Xml.Linq.XContainer.Elements(System.Xml.Linq.XName) As System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)" IL_00fd: call "Sub C.Report(System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement))" IL_0102: ldstr "b" IL_0107: ldstr "q2" IL_010c: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0111: callvirt "Function System.Xml.Linq.XContainer.Elements(System.Xml.Linq.XName) As System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)" IL_0116: call "Sub C.Report(System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement))" IL_011b: ret } ]]>) End Sub <Fact()> Public Sub ImplicitXmlnsAttributes() Dim options = TestOptions.ReleaseExe.WithGlobalImports(GlobalImport.Parse({"<xmlns=""http://roslyn"">", "<xmlns:p=""http://roslyn/p"">"})) Dim compilation = CompileAndVerify( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports System Imports <xmlns:P="http://roslyn/P"> Imports <xmlns:q="http://roslyn/p"> Module M Private F1 As Object = <x><p:y/></x> Private F2 As Object = <x><p:y/><P:z/></x> Private F3 As Object = <p:x><q:y/></p:x> Sub Main() Console.WriteLine("{0}", F1) Console.WriteLine("{0}", F2) Console.WriteLine("{0}", F3) End Sub End Module ]]></file> </compilation>, references:=Net40XmlReferences, options:=options, expectedOutput:=<![CDATA[ <x xmlns:p="http://roslyn/p" xmlns="http://roslyn"> <p:y /> </x> <x xmlns:P="http://roslyn/P" xmlns:p="http://roslyn/p" xmlns="http://roslyn"> <p:y /> <P:z /> </x> <p:x xmlns:q="http://roslyn/p" xmlns:p="http://roslyn/p"> <p:y /> </p:x> ]]>) End Sub <Fact()> Public Sub ImplicitXmlnsAttributes_DefaultAndEmpty() Dim compilation = CompileAndVerify( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports <xmlns="http://roslyn/default"> Imports <xmlns:p="http://roslyn/p"> Imports <xmlns:q=""> Module M Sub Main() Report(<p:x> <y/> <q:z/> </p:x>) End Sub Sub Report(o As Object) System.Console.WriteLine("{0}", o) End Sub End Module ]]></file> </compilation>, references:=Net40XmlReferences, expectedOutput:=<![CDATA[ <p:x xmlns="http://roslyn/default" xmlns:p="http://roslyn/p"> <y /> <z xmlns="" /> </p:x> ]]>) compilation.VerifyIL("M.Main", <![CDATA[ { // Code size 150 (0x96) .maxstack 4 IL_0000: ldstr "x" IL_0005: ldstr "http://roslyn/p" IL_000a: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_000f: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_0014: dup IL_0015: ldstr "y" IL_001a: ldstr "http://roslyn/default" IL_001f: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0024: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_0029: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_002e: dup IL_002f: ldstr "z" IL_0034: ldstr "" IL_0039: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_003e: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_0043: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_0048: dup IL_0049: ldstr "xmlns" IL_004e: ldstr "" IL_0053: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0058: ldstr "http://roslyn/default" IL_005d: call "Function System.Xml.Linq.XNamespace.Get(String) As System.Xml.Linq.XNamespace" IL_0062: call "Function My.InternalXmlHelper.CreateNamespaceAttribute(System.Xml.Linq.XName, System.Xml.Linq.XNamespace) As System.Xml.Linq.XAttribute" IL_0067: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_006c: dup IL_006d: ldstr "p" IL_0072: ldstr "http://www.w3.org/2000/xmlns/" IL_0077: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_007c: ldstr "http://roslyn/p" IL_0081: call "Function System.Xml.Linq.XNamespace.Get(String) As System.Xml.Linq.XNamespace" IL_0086: call "Function My.InternalXmlHelper.CreateNamespaceAttribute(System.Xml.Linq.XName, System.Xml.Linq.XNamespace) As System.Xml.Linq.XAttribute" IL_008b: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_0090: call "Sub M.Report(Object)" IL_0095: ret } ]]>) End Sub <Fact()> Public Sub ImplicitXmlnsAttributes_EmbeddedExpressions() Dim compilation = CompileAndVerify( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports System Imports <xmlns="http://roslyn/default"> Imports <xmlns:p="http://roslyn/p"> Imports <xmlns:q="http://roslyn/q"> Module M Private F0 As Object = <p:y/> Private F1 As Object = <x><%= <p:y1/> %><%= <p:y2/> %><%= <q:y3/> %></x> Private F2 As Object = <x><%= F0 %></x> Private F3 As Object = <p:x><%= <<%= <q:y/> %>/> %></p:x> Private F4 As Object = <p:x><%= (Function() <y/>)() %></p:x> Sub Main() Console.WriteLine("{0}", F1) Console.WriteLine("{0}", F2) Console.WriteLine("{0}", F3) Console.WriteLine("{0}", F4) End Sub End Module ]]></file> </compilation>, references:=Net40XmlReferences, expectedOutput:=<![CDATA[ <x xmlns="http://roslyn/default" xmlns:p="http://roslyn/p" xmlns:q="http://roslyn/q"> <p:y1 /> <p:y2 /> <q:y3 /> </x> <x xmlns="http://roslyn/default" xmlns:p="http://roslyn/p"> <p:y /> </x> <p:x xmlns:p="http://roslyn/p"> <q:y xmlns:q="http://roslyn/q" /> </p:x> <p:x xmlns:p="http://roslyn/p" xmlns="http://roslyn/default"> <y /> </p:x> ]]>) End Sub <Fact()> Public Sub ImplicitXmlnsAttributes_EmbeddedExpressions_2() Dim compilation = CompileAndVerify( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports System.Xml.Linq Imports <xmlns:p1="http://roslyn/1"> Imports <xmlns:p2="http://roslyn/2"> Module M Sub Main() ' Same xmlns merged from sibling children. Report(<a> <b> <%= F(<c> <p1:d/> </c>) %> </b> <b> <%= F(<c> <p1:d/> <p2:d/> </c>) %> </b> </a>) ' Different xmlns at sibling scopes. Report(<a> <b xmlns:p1="http://roslyn/3"> <%= F(<c> <p1:d/> <p2:d/> </c>) %> </b> <b xmlns:p2="http://roslyn/4"> <%= F(<c> <p1:d/> <p2:d/> </c>) %> </b> </a>) ' Different xmlns at nested scopes. Dev11: "Duplicate attribute" exception. Report(<a xmlns:p1="http://roslyn/3"> <b xmlns:p2="http://roslyn/4"> <%= F(<c> <p1:d/> <p2:d/> </c>) %> </b> </a>) End Sub Function F(x As XElement) As XElement Return x End Function Sub Report(x As XElement) System.Console.WriteLine("{0}", x) End Sub End Module ]]></file> </compilation>, references:=Net40XmlReferences, expectedOutput:=<![CDATA[ <a xmlns:p1="http://roslyn/1" xmlns:p2="http://roslyn/2"> <b> <c> <p1:d /> </c> </b> <b> <c> <p1:d /> <p2:d /> </c> </b> </a> <a xmlns:p2="http://roslyn/2" xmlns:p1="http://roslyn/1"> <b xmlns:p1="http://roslyn/3"> <c xmlns:p1="http://roslyn/1"> <p1:d /> <p2:d /> </c> </b> <b xmlns:p2="http://roslyn/4"> <c xmlns:p2="http://roslyn/2"> <p1:d /> <p2:d /> </c> </b> </a> <a xmlns:p1="http://roslyn/3"> <b xmlns:p2="http://roslyn/4"> <c xmlns:p2="http://roslyn/2" xmlns:p1="http://roslyn/1"> <p1:d /> <p2:d /> </c> </b> </a> ]]>) End Sub ' Embedded expression from separate file with distinct default namespaces. <Fact()> Public Sub ImplicitXmlnsAttributes_DistinctDefaultNamespaces() Dim compilation = CompileAndVerify( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports System Partial Class C Private Shared F1 As Object = <x> <%= E1() %> <%= E2() %> <%= E3() %> </x> Private Shared Function E1() As Object Return <y/> End Function Shared Sub Main() Console.WriteLine("{0}", F1) Console.WriteLine("{0}", F2) Console.WriteLine("{0}", F3) End Sub End Class ]]></file> <file name="b.vb"><![CDATA[ Option Strict On Imports <xmlns="http://roslyn/2"> Partial Class C Private Shared F2 As Object = <x> <%= E1() %> <%= E2() %> <%= E3() %> </x> Private Shared Function E2() As Object Return <y/> End Function End Class ]]></file> <file name="c.vb"><![CDATA[ Option Strict On Imports <xmlns="http://roslyn/3"> Partial Class C Private Shared F3 As Object = <x> <%= E1() %> <%= E2() %> <%= E3() %> </x> Private Shared Function E3() As Object Return <y/> End Function End Class ]]></file> </compilation>, references:=Net40XmlReferences, expectedOutput:=<![CDATA[ <x> <y /> <y xmlns="http://roslyn/2" /> <y xmlns="http://roslyn/3" /> </x> <x xmlns="http://roslyn/2"> <y xmlns="" /> <y /> <y xmlns="http://roslyn/3" /> </x> <x xmlns="http://roslyn/3"> <y xmlns="" /> <y xmlns="http://roslyn/2" /> <y /> </x> ]]>) End Sub ' Embedded expression from separate file with distinct Imports. <Fact()> Public Sub ImplicitXmlnsAttributes_DistinctImports() Dim compilation = CompileAndVerify( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports <xmlns:p="http://roslyn/p"> Imports <xmlns:q="http://roslyn/q1"> Imports <xmlns:r="http://roslyn/r"> Module M Public F As Object = <x> <y> <p:z q:a="b" r:c="d"/> <%= N.F %> </y> </x> Sub Main() System.Console.WriteLine("{0}", F) End Sub End Module ]]></file> <file name="b.vb"><![CDATA[ Option Strict On Imports <xmlns:p="http://roslyn/p"> Imports <xmlns:q="http://roslyn/q2"> Imports <xmlns:s="http://roslyn/r"> Module N Public F As Object = <p:z q:a="b" s:c="d"/> End Module ]]></file> </compilation>, references:=Net40XmlReferences, expectedOutput:=<![CDATA[ <x xmlns:r="http://roslyn/r" xmlns:q="http://roslyn/q1" xmlns:p="http://roslyn/p" xmlns:s="http://roslyn/r"> <y> <p:z q:a="b" s:c="d" /> <p:z q:a="b" s:c="d" xmlns:q="http://roslyn/q2" /> </y> </x> ]]>) End Sub ' Embedded expression other than as XElement content. ' (Dev11 does not merge namespaces in <x <%= F %>/> ' although Roslyn does.) <Fact()> Public Sub ImplicitXmlnsAttributes_EmbeddedExpressionOutsideContent() Dim compilation = CompileAndVerify( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports <xmlns:p="http://roslyn/"> Module M Private F1 As Object = <x <%= <p:y/> %>/> Private F2 As Object = <<%= <p:y/> %>/> Private F3 As Object = <?xml version="1.0"?><%= <p:y/> %> Sub Main() System.Console.WriteLine("{0}", F1) System.Console.WriteLine("{0}", F2) System.Console.WriteLine("{0}", F3) End Sub End Module ]]></file> </compilation>, references:=Net40XmlReferences, expectedOutput:=<![CDATA[ <x xmlns:p="http://roslyn/"> <p:y /> </x> <p:y xmlns:p="http://roslyn/" /> <p:y xmlns:p="http://roslyn/" /> ]]>) End Sub ' Opaque embedded expression and XML literal embedded expression ' with duplicate namespace references. (Dev11 generates code ' that throws InvalidOperationException: "Duplicate attribute".) <Fact()> Public Sub ImplicitXmlnsAttributes_EmbeddedExpressionAndEmbeddedLiteral() Dim compilation = CompileAndVerify( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports <xmlns:p="http://roslyn/p"> Imports <xmlns:q="http://roslyn/q"> Module M Private F1 As Object = <x> <%= F() %> <%= <p:z/> %> </x> Private F2 As Object = <x> <%= <p:y><%= F() %></p:y> %> </x> Function F() As Object Return <p:y q:a="b"/> End Function Sub Main() System.Console.WriteLine("{0}", F1) System.Console.WriteLine("{0}", F2) End Sub End Module ]]></file> </compilation>, references:=Net40XmlReferences, expectedOutput:=<![CDATA[ <x xmlns:q="http://roslyn/q" xmlns:p="http://roslyn/p"> <p:y q:a="b" /> <p:z /> </x> <x xmlns:p="http://roslyn/p" xmlns:q="http://roslyn/q"> <p:y> <p:y q:a="b" /> </p:y> </x> ]]>) End Sub ' InternalXmlHelper.RemoveNamespaceAttributes() modifies ' the embedded expression argument so subsequent uses of ' the expression may give different results. <WorkItem(529410, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529410")> <Fact()> Public Sub ImplicitXmlnsAttributes_SideEffects() Dim compilation = CompileAndVerify( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports <xmlns:p="http://roslyn/p"> Imports <xmlns:q="http://roslyn/q"> Module M Private F1 As Object = <q:y/> Private F2 As Object = <p:x><%= F1 %></p:x> Private F3 As Object = <p:x><%= F1 %></p:x> Sub Main() System.Console.WriteLine("{0}", F2) System.Console.WriteLine("{0}", F3) End Sub End Module ]]></file> </compilation>, references:=Net40XmlReferences, expectedOutput:=<![CDATA[ <p:x xmlns:p="http://roslyn/p" xmlns:q="http://roslyn/q"> <q:y /> </p:x> <p:x xmlns:p="http://roslyn/p"> <y xmlns="http://roslyn/q" /> </p:x> ]]>) End Sub <Fact()> Public Sub EmbeddedStringNameExpressions() Dim compilation = CompileAndVerify( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports System Imports System.Xml.Linq Module M Private F As String = "x" Private X As XElement = <<%= F %> <%= F %>="..."/> Sub Main() Console.WriteLine("{0}", X) End Sub End Module ]]></file> </compilation>, references:=Net40XmlReferences, expectedOutput:=<![CDATA[ <x x="..." /> ]]>) compilation.VerifyIL("M..cctor", <![CDATA[ { // Code size 57 (0x39) .maxstack 4 IL_0000: ldstr "x" IL_0005: stsfld "M.F As String" IL_000a: ldsfld "M.F As String" IL_000f: call "Function System.Xml.Linq.XName.op_Implicit(String) As System.Xml.Linq.XName" IL_0014: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_0019: dup IL_001a: ldsfld "M.F As String" IL_001f: call "Function System.Xml.Linq.XName.op_Implicit(String) As System.Xml.Linq.XName" IL_0024: ldstr "..." IL_0029: newobj "Sub System.Xml.Linq.XAttribute..ctor(System.Xml.Linq.XName, Object)" IL_002e: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_0033: stsfld "M.X As System.Xml.Linq.XElement" IL_0038: ret } ]]>) End Sub <Fact()> Public Sub EmbeddedXNameExpressions() Dim compilation = CompileAndVerify( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports System Imports System.Xml.Linq Module M Private F As XName = XName.Get("x", "") Private G As XName = XName.Get("y", "http://roslyn") Private H As XName = XName.Get("z", "") Private X As XElement = <<%= F %> <%= F %>="..."/> Private Y As XElement = <<%= G %> <%= G %>="..."/> Private Z As XElement = <<%= H %> <%= H %>="..."><%= H %></> Sub Main() Console.WriteLine("{0}", X) Console.WriteLine("{0}", Y) Console.WriteLine("{0}", Z) End Sub End Module ]]></file> </compilation>, references:=Net40XmlReferences, expectedOutput:=<![CDATA[ <x x="..." /> <y p1:y="..." xmlns:p1="http://roslyn" xmlns="http://roslyn" /> <z z="...">z</z> ]]>) compilation.VerifyIL("M..cctor", <![CDATA[ { // Code size 180 (0xb4) .maxstack 4 IL_0000: ldstr "x" IL_0005: ldstr "" IL_000a: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_000f: stsfld "M.F As System.Xml.Linq.XName" IL_0014: ldstr "y" IL_0019: ldstr "http://roslyn" IL_001e: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0023: stsfld "M.G As System.Xml.Linq.XName" IL_0028: ldstr "z" IL_002d: ldstr "" IL_0032: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0037: stsfld "M.H As System.Xml.Linq.XName" IL_003c: ldsfld "M.F As System.Xml.Linq.XName" IL_0041: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_0046: dup IL_0047: ldsfld "M.F As System.Xml.Linq.XName" IL_004c: ldstr "..." IL_0051: newobj "Sub System.Xml.Linq.XAttribute..ctor(System.Xml.Linq.XName, Object)" IL_0056: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_005b: stsfld "M.X As System.Xml.Linq.XElement" IL_0060: ldsfld "M.G As System.Xml.Linq.XName" IL_0065: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_006a: dup IL_006b: ldsfld "M.G As System.Xml.Linq.XName" IL_0070: ldstr "..." IL_0075: newobj "Sub System.Xml.Linq.XAttribute..ctor(System.Xml.Linq.XName, Object)" IL_007a: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_007f: stsfld "M.Y As System.Xml.Linq.XElement" IL_0084: ldsfld "M.H As System.Xml.Linq.XName" IL_0089: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_008e: dup IL_008f: ldsfld "M.H As System.Xml.Linq.XName" IL_0094: ldstr "..." IL_0099: newobj "Sub System.Xml.Linq.XAttribute..ctor(System.Xml.Linq.XName, Object)" IL_009e: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_00a3: dup IL_00a4: ldsfld "M.H As System.Xml.Linq.XName" IL_00a9: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_00ae: stsfld "M.Z As System.Xml.Linq.XElement" IL_00b3: ret } ]]>) End Sub ' Use InternalXmlHelper.CreateAttribute to generate attributes ' with embedded expression values since CreateAttribute will ' handle Nothing value. Otherwise, use New XAttribute(). <Fact()> Public Sub EmbeddedAttributeValueExpressions() Dim compilation = CompileAndVerify( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports System.Linq Imports System.Xml.Linq Module M Sub Main() Report(<x a1="b1"/>) Report(<x a2=<%= "b2" %>/>) Report(<x a3=<%= 3 %>/>) Report(<x a4=<%= Nothing %>/>) End Sub Sub Report(x As XElement) System.Console.WriteLine("[{0}] {1}", x.Attributes.Count(), x) End Sub End Module ]]></file> </compilation>, references:=Net40XmlReferences, expectedOutput:=<![CDATA[ [1] <x a1="b1" /> [1] <x a2="b2" /> [1] <x a3="3" /> [0] <x /> ]]>) compilation.VerifyIL("M.Main", <![CDATA[ { // Code size 222 (0xde) .maxstack 4 IL_0000: ldstr "x" IL_0005: ldstr "" IL_000a: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_000f: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_0014: dup IL_0015: ldstr "a1" IL_001a: ldstr "" IL_001f: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0024: ldstr "b1" IL_0029: newobj "Sub System.Xml.Linq.XAttribute..ctor(System.Xml.Linq.XName, Object)" IL_002e: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_0033: call "Sub M.Report(System.Xml.Linq.XElement)" IL_0038: ldstr "x" IL_003d: ldstr "" IL_0042: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0047: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_004c: dup IL_004d: ldstr "a2" IL_0052: ldstr "" IL_0057: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_005c: ldstr "b2" IL_0061: call "Function My.InternalXmlHelper.CreateAttribute(System.Xml.Linq.XName, Object) As System.Xml.Linq.XAttribute" IL_0066: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_006b: call "Sub M.Report(System.Xml.Linq.XElement)" IL_0070: ldstr "x" IL_0075: ldstr "" IL_007a: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_007f: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_0084: dup IL_0085: ldstr "a3" IL_008a: ldstr "" IL_008f: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0094: ldc.i4.3 IL_0095: box "Integer" IL_009a: call "Function My.InternalXmlHelper.CreateAttribute(System.Xml.Linq.XName, Object) As System.Xml.Linq.XAttribute" IL_009f: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_00a4: call "Sub M.Report(System.Xml.Linq.XElement)" IL_00a9: ldstr "x" IL_00ae: ldstr "" IL_00b3: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_00b8: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_00bd: dup IL_00be: ldstr "a4" IL_00c3: ldstr "" IL_00c8: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_00cd: ldnull IL_00ce: call "Function My.InternalXmlHelper.CreateAttribute(System.Xml.Linq.XName, Object) As System.Xml.Linq.XAttribute" IL_00d3: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_00d8: call "Sub M.Report(System.Xml.Linq.XElement)" IL_00dd: ret } ]]>) End Sub <Fact()> Public Sub EmbeddedChildExpressions() Dim compilation = CompileAndVerify( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports System Imports System.Xml.Linq Module M Property F As String = "f" Property G As XElement = <g/> Property H As XElement = <r:h xmlns:r="http://roslyn"/> Property W As XElement = <w w=<%= F %>/> Property X As XElement = <x><%= F %></x> Property Y As XElement = <y><%= G %></y> Property Z As XElement = <z><%= F %><%= G %><%= H %></z> Sub Main() Console.WriteLine("{0}", W) Console.WriteLine("{0}", X) Console.WriteLine("{0}", Y) Console.WriteLine("{0}", Z) End Sub End Module ]]></file> </compilation>, references:=Net40XmlReferences, expectedOutput:=<![CDATA[ <w w="f" /> <x>f</x> <y> <g /> </y> <z>f<g /><r:h xmlns:r="http://roslyn" /></z> ]]>) End Sub <Fact()> Public Sub EmbeddedChildExpressions_2() Dim compilation = CompileAndVerify( <compilation> <file name="c.vb"><![CDATA[ Imports System Imports System.Xml.Linq Module M Private FString = "s" Private FName As XName = XName.Get("n", "") Private FAttribute As XAttribute = New XAttribute(XName.Get("a", ""), "b") Private FElement As XElement = <e/> Private X1 As XElement = <x1 <%= FString %>/> Private X2 As XElement = <x2><%= FString %></x2> Private Y1 As XElement = <y1 <%= FName %>/> Private Y2 As XElement = <y2><%= FName %></y2> Private Z1 As XElement = <z1 <%= FAttribute %>/> Private Z2 As XElement = <z2><%= FAttribute %></z2> Private W1 As XElement = <w1 <%= FElement %>/> Private W2 As XElement = <w2><%= FElement %></w2> Sub Main() Console.WriteLine("{0}", X1) Console.WriteLine("{0}", X2) Console.WriteLine("{0}", Y1) Console.WriteLine("{0}", Y2) Console.WriteLine("{0}", Z1) Console.WriteLine("{0}", Z2) Console.WriteLine("{0}", W1) Console.WriteLine("{0}", W2) End Sub End Module ]]></file> </compilation>, references:=Net40XmlReferences, expectedOutput:=<![CDATA[ <x1>s</x1> <x2>s</x2> <y1>n</y1> <y2>n</y2> <z1 a="b" /> <z2 a="b" /> <w1> <e /> </w1> <w2> <e /> </w2> ]]>) End Sub ' XContainer.Add(ParamArray content As Object()) overload ' should be used if the expression represents an Object(). <Fact()> Public Sub EmbeddedChildCollectionExpressions() Dim compilation = CompileAndVerify( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports System Imports System.Collections.Generic Imports System.Linq Imports System.Xml.Linq Module M Private Function F() As XElement() Dim x = New XElement(1) {} x(0) = <<%= XName.Get("c1", "") %>/> x(1) = <<%= XName.Get("c2", "") %>/> Return x End Function Private Function G() As XElement(,) Dim x = New XElement(1, 1) {} x(0, 0) = <<%= XName.Get("c1", "") %>/> x(0, 1) = <<%= XName.Get("c2", "") %>/> x(1, 0) = <<%= XName.Get("c3", "") %>/> x(1, 1) = <<%= XName.Get("c4", "") %>/> Return x End Function Private Function H() As XElement()() Dim x = New XElement(1)() {} x(0) = F() x(1) = F() Return x End Function Private F0 As Object = F() Private F1 As Object() = F() Private F2 As XElement() = F() Private F3 As IEnumerable(Of Object) = F() Private F4 As IEnumerable(Of XElement) = F() Private F5 As XElement(,) = G() Private F6 As XElement()() = H() Sub Main() Report(<x0 <%= F0 %>/>) Report(<x0><%= F0 %></x0>) Report(<x1 <%= F1 %>/>) Report(<x1><%= F1 %></x1>) Report(<x2 <%= F2 %>/>) Report(<x2><%= F2 %></x2>) Report(<x3 <%= F3 %>/>) Report(<x3><%= F3 %></x3>) Report(<x4 <%= F4 %>/>) Report(<x4><%= F4 %></x4>) Report(<x5 <%= F5 %>/>) Report(<x5><%= F5 %></x5>) Report(<x6 <%= F6 %>/>) Report(<x6><%= F6 %></x6>) End Sub Sub Report(x As XElement) Console.WriteLine("{0}, #={1}", x, x.Elements.Count()) End Sub End Module ]]></file> </compilation>, references:=Net40XmlReferences, expectedOutput:=<![CDATA[ <x0> <c1 /> <c2 /> </x0>, #=2 <x0> <c1 /> <c2 /> </x0>, #=2 <x1> <c1 /> <c2 /> </x1>, #=2 <x1> <c1 /> <c2 /> </x1>, #=2 <x2> <c1 /> <c2 /> </x2>, #=2 <x2> <c1 /> <c2 /> </x2>, #=2 <x3> <c1 /> <c2 /> </x3>, #=2 <x3> <c1 /> <c2 /> </x3>, #=2 <x4> <c1 /> <c2 /> </x4>, #=2 <x4> <c1 /> <c2 /> </x4>, #=2 <x5> <c1 /> <c2 /> <c3 /> <c4 /> </x5>, #=4 <x5> <c1 /> <c2 /> <c3 /> <c4 /> </x5>, #=4 <x6> <c1 /> <c2 /> <c1 /> <c2 /> </x6>, #=4 <x6> <c1 /> <c2 /> <c1 /> <c2 /> </x6>, #=4 ]]>) compilation.VerifyIL("M.Main", <![CDATA[ { // Code size 515 (0x203) .maxstack 3 IL_0000: ldstr "x0" IL_0005: ldstr "" IL_000a: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_000f: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_0014: dup IL_0015: ldsfld "M.F0 As Object" IL_001a: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_001f: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_0024: call "Sub M.Report(System.Xml.Linq.XElement)" IL_0029: ldstr "x0" IL_002e: ldstr "" IL_0033: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0038: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_003d: dup IL_003e: ldsfld "M.F0 As Object" IL_0043: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0048: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_004d: call "Sub M.Report(System.Xml.Linq.XElement)" IL_0052: ldstr "x1" IL_0057: ldstr "" IL_005c: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0061: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_0066: dup IL_0067: ldsfld "M.F1 As Object()" IL_006c: callvirt "Sub System.Xml.Linq.XContainer.Add(ParamArray Object())" IL_0071: call "Sub M.Report(System.Xml.Linq.XElement)" IL_0076: ldstr "x1" IL_007b: ldstr "" IL_0080: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0085: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_008a: dup IL_008b: ldsfld "M.F1 As Object()" IL_0090: callvirt "Sub System.Xml.Linq.XContainer.Add(ParamArray Object())" IL_0095: call "Sub M.Report(System.Xml.Linq.XElement)" IL_009a: ldstr "x2" IL_009f: ldstr "" IL_00a4: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_00a9: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_00ae: dup IL_00af: ldsfld "M.F2 As System.Xml.Linq.XElement()" IL_00b4: callvirt "Sub System.Xml.Linq.XContainer.Add(ParamArray Object())" IL_00b9: call "Sub M.Report(System.Xml.Linq.XElement)" IL_00be: ldstr "x2" IL_00c3: ldstr "" IL_00c8: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_00cd: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_00d2: dup IL_00d3: ldsfld "M.F2 As System.Xml.Linq.XElement()" IL_00d8: callvirt "Sub System.Xml.Linq.XContainer.Add(ParamArray Object())" IL_00dd: call "Sub M.Report(System.Xml.Linq.XElement)" IL_00e2: ldstr "x3" IL_00e7: ldstr "" IL_00ec: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_00f1: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_00f6: dup IL_00f7: ldsfld "M.F3 As System.Collections.Generic.IEnumerable(Of Object)" IL_00fc: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_0101: call "Sub M.Report(System.Xml.Linq.XElement)" IL_0106: ldstr "x3" IL_010b: ldstr "" IL_0110: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0115: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_011a: dup IL_011b: ldsfld "M.F3 As System.Collections.Generic.IEnumerable(Of Object)" IL_0120: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_0125: call "Sub M.Report(System.Xml.Linq.XElement)" IL_012a: ldstr "x4" IL_012f: ldstr "" IL_0134: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0139: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_013e: dup IL_013f: ldsfld "M.F4 As System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)" IL_0144: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_0149: call "Sub M.Report(System.Xml.Linq.XElement)" IL_014e: ldstr "x4" IL_0153: ldstr "" IL_0158: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_015d: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_0162: dup IL_0163: ldsfld "M.F4 As System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)" IL_0168: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_016d: call "Sub M.Report(System.Xml.Linq.XElement)" IL_0172: ldstr "x5" IL_0177: ldstr "" IL_017c: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0181: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_0186: dup IL_0187: ldsfld "M.F5 As System.Xml.Linq.XElement(,)" IL_018c: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_0191: call "Sub M.Report(System.Xml.Linq.XElement)" IL_0196: ldstr "x5" IL_019b: ldstr "" IL_01a0: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_01a5: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_01aa: dup IL_01ab: ldsfld "M.F5 As System.Xml.Linq.XElement(,)" IL_01b0: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_01b5: call "Sub M.Report(System.Xml.Linq.XElement)" IL_01ba: ldstr "x6" IL_01bf: ldstr "" IL_01c4: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_01c9: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_01ce: dup IL_01cf: ldsfld "M.F6 As System.Xml.Linq.XElement()()" IL_01d4: callvirt "Sub System.Xml.Linq.XContainer.Add(ParamArray Object())" IL_01d9: call "Sub M.Report(System.Xml.Linq.XElement)" IL_01de: ldstr "x6" IL_01e3: ldstr "" IL_01e8: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_01ed: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_01f2: dup IL_01f3: ldsfld "M.F6 As System.Xml.Linq.XElement()()" IL_01f8: callvirt "Sub System.Xml.Linq.XContainer.Add(ParamArray Object())" IL_01fd: call "Sub M.Report(System.Xml.Linq.XElement)" IL_0202: ret } ]]>) End Sub <Fact()> Public Sub EmbeddedExpressionConversions() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports System.Xml.Linq Class A End Class Structure S End Structure Class C(Of T) Private Shared F1 As Object = Nothing Private Shared F2 As String = Nothing Private Shared F3 As XName = Nothing Private Shared F4 As XElement = Nothing Private Shared F5 As A = Nothing Private Shared F6 As S = Nothing Private Shared F7 As T = Nothing Private Shared F8 As Unknown = Nothing Shared Sub M() Dim x As XElement x = <a><%= F1 %></a> x = <a><%= F2 %></a> x = <a><%= F3 %></a> x = <a><%= F4 %></a> x = <a><%= F5 %></a> x = <a><%= F6 %></a> x = <a><%= F7 %></a> x = <a><%= F8 %></a> x = <a <%= F1 %>="b"/> x = <a <%= F2 %>="b"/> x = <a <%= F3 %>="b"/> x = <a <%= F4 %>="b"/> x = <a <%= F5 %>="b"/> x = <a <%= F6 %>="b"/> x = <a <%= F7 %>="b"/> x = <a <%= F8 %>="b"/> x = <a b=<%= F1 %>/> x = <a b=<%= F2 %>/> x = <a b=<%= F3 %>/> x = <a b=<%= F4 %>/> x = <a b=<%= F5 %>/> x = <a b=<%= F6 %>/> x = <a b=<%= F7 %>/> x = <a b=<%= F8 %>/> End Sub End Class ]]></file> </compilation>, references:=Net40XmlReferences) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC30002: Type 'Unknown' is not defined. Private Shared F8 As Unknown = Nothing ~~~~~~~ BC30512: Option Strict On disallows implicit conversions from 'Object' to 'XName'. x = <a <%= F1 %>="b"/> ~~~~~~~~~ BC30311: Value of type 'XElement' cannot be converted to 'XName'. x = <a <%= F4 %>="b"/> ~~~~~~~~~ BC30311: Value of type 'A' cannot be converted to 'XName'. x = <a <%= F5 %>="b"/> ~~~~~~~~~ BC30311: Value of type 'S' cannot be converted to 'XName'. x = <a <%= F6 %>="b"/> ~~~~~~~~~ BC30311: Value of type 'T' cannot be converted to 'XName'. x = <a <%= F7 %>="b"/> ~~~~~~~~~ ]]></errors>) End Sub ' Values of constant embedded expressions ' should be inlined in generated code. <Fact()> Public Sub EmbeddedExpressionConstants() Dim compilation = CompileAndVerify( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Module M Private Const F1 As String = "v1" Private F2 As String = "v2" Function F() As Object Return <x a0=<%= "v0" %> a1=<%= F1 %> a2=<%= F2 %>/> End Function End Module ]]></file> </compilation>, references:=Net40XmlReferences) compilation.VerifyIL("M.F", <![CDATA[ { // Code size 114 (0x72) .maxstack 4 IL_0000: ldstr "x" IL_0005: ldstr "" IL_000a: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_000f: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_0014: dup IL_0015: ldstr "a0" IL_001a: ldstr "" IL_001f: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0024: ldstr "v0" IL_0029: call "Function My.InternalXmlHelper.CreateAttribute(System.Xml.Linq.XName, Object) As System.Xml.Linq.XAttribute" IL_002e: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_0033: dup IL_0034: ldstr "a1" IL_0039: ldstr "" IL_003e: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0043: ldstr "v1" IL_0048: call "Function My.InternalXmlHelper.CreateAttribute(System.Xml.Linq.XName, Object) As System.Xml.Linq.XAttribute" IL_004d: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_0052: dup IL_0053: ldstr "a2" IL_0058: ldstr "" IL_005d: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0062: ldsfld "M.F2 As String" IL_0067: call "Function My.InternalXmlHelper.CreateAttribute(System.Xml.Linq.XName, Object) As System.Xml.Linq.XAttribute" IL_006c: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_0071: ret } ]]>) End Sub <Fact()> Public Sub EmbeddedExpressionDelegateConversion() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports System.Xml.Linq Delegate Sub D() Module M Sub M0() End Sub Sub M1() End Sub Function M2() As Object Return Nothing End Function Function M3() As Object Return Nothing End Function Private F0 As D = <%= AddressOf M0 %> Private F1 As Object = <%= AddressOf M1 %> Private F2 As XElement = <x y=<%= AddressOf M2 %>/> Private F3 As XElement = <x><%= AddressOf M3 %></x> End Module ]]></file> </compilation>, references:=Net40XmlReferences) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC31172: An embedded expression cannot be used here. Private F0 As D = <%= AddressOf M0 %> ~~~~~~~~~~~~~~~~~~~ BC30491: Expression does not produce a value. Private F0 As D = <%= AddressOf M0 %> ~~~~~~~~~~~~ BC31172: An embedded expression cannot be used here. Private F1 As Object = <%= AddressOf M1 %> ~~~~~~~~~~~~~~~~~~~ BC30491: Expression does not produce a value. Private F1 As Object = <%= AddressOf M1 %> ~~~~~~~~~~~~ BC30491: Expression does not produce a value. Private F2 As XElement = <x y=<%= AddressOf M2 %>/> ~~~~~~~~~~~~ BC30491: Expression does not produce a value. Private F3 As XElement = <x><%= AddressOf M3 %></x> ~~~~~~~~~~~~ ]]></errors>) End Sub <Fact()> Public Sub EmbeddedExpressionXElementConstructor() Dim compilation = CompileAndVerify( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports System Imports System.Xml.Linq Module M Sub Main() Report(<<%= XName.Get("x", "") %>/>) Report(<<%= XName.Get("x", "") %> a="b">c</>) Report(<<%= <x1 a1="b1">c1</x1> %> a2="b2">c2</>) End Sub Sub Report(o As XElement) Console.WriteLine("{0}", o) End Sub End Module ]]></file> </compilation>, references:=Net40XmlReferences, expectedOutput:=<![CDATA[ <x /> <x a="b">c</x> <x1 a1="b1" a2="b2">c1c2</x1> ]]>) compilation.VerifyIL("M.Main", <![CDATA[ { // Code size 207 (0xcf) .maxstack 4 IL_0000: ldstr "x" IL_0005: ldstr "" IL_000a: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_000f: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_0014: call "Sub M.Report(System.Xml.Linq.XElement)" IL_0019: ldstr "x" IL_001e: ldstr "" IL_0023: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0028: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_002d: dup IL_002e: ldstr "a" IL_0033: ldstr "" IL_0038: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_003d: ldstr "b" IL_0042: newobj "Sub System.Xml.Linq.XAttribute..ctor(System.Xml.Linq.XName, Object)" IL_0047: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_004c: dup IL_004d: ldstr "c" IL_0052: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_0057: call "Sub M.Report(System.Xml.Linq.XElement)" IL_005c: ldstr "x1" IL_0061: ldstr "" IL_0066: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_006b: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_0070: dup IL_0071: ldstr "a1" IL_0076: ldstr "" IL_007b: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0080: ldstr "b1" IL_0085: newobj "Sub System.Xml.Linq.XAttribute..ctor(System.Xml.Linq.XName, Object)" IL_008a: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_008f: dup IL_0090: ldstr "c1" IL_0095: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_009a: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XElement)" IL_009f: dup IL_00a0: ldstr "a2" IL_00a5: ldstr "" IL_00aa: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_00af: ldstr "b2" IL_00b4: newobj "Sub System.Xml.Linq.XAttribute..ctor(System.Xml.Linq.XName, Object)" IL_00b9: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_00be: dup IL_00bf: ldstr "c2" IL_00c4: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_00c9: call "Sub M.Report(System.Xml.Linq.XElement)" IL_00ce: ret } ]]>) End Sub <Fact()> Public Sub EmbeddedExpressionNoXElementConstructor() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports System.Xml.Linq Class A End Class Structure S End Structure Class C(Of T) Private Shared F1 As Object = Nothing Private Shared F2 As String = Nothing Private Shared F3 As XName = Nothing Private Shared F4 As XElement = Nothing Private Shared F5 As A = Nothing Private Shared F6 As S = Nothing Private Shared F7 As T = Nothing Private Shared F8 As Unknown = Nothing Shared Sub M() Dim x As XElement x = <<%= F1 %>/> x = <<%= F2 %>/> x = <<%= F3 %>/> x = <<%= F4 %>/> x = <<%= F5 %>/> x = <<%= F6 %>/> x = <<%= F7 %>/> x = <<%= F8 %>/> End Sub End Class ]]></file> </compilation>, references:=Net40XmlReferences) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC30002: Type 'Unknown' is not defined. Private Shared F8 As Unknown = Nothing ~~~~~~~ BC30518: Overload resolution failed because no accessible 'New' can be called with these arguments: 'Public Overloads Sub New(name As XName)': Option Strict On disallows implicit conversions from 'Object' to 'XName'. 'Public Overloads Sub New(other As XElement)': Option Strict On disallows implicit conversions from 'Object' to 'XElement'. 'Public Overloads Sub New(other As XStreamingElement)': Option Strict On disallows implicit conversions from 'Object' to 'XStreamingElement'. x = <<%= F1 %>/> ~~~~~~~~~ BC30518: Overload resolution failed because no accessible 'New' can be called with these arguments: 'Public Overloads Sub New(name As XName)': Value of type 'A' cannot be converted to 'XName'. 'Public Overloads Sub New(other As XElement)': Value of type 'A' cannot be converted to 'XElement'. 'Public Overloads Sub New(other As XStreamingElement)': Value of type 'A' cannot be converted to 'XStreamingElement'. x = <<%= F5 %>/> ~~~~~~~~~ BC30518: Overload resolution failed because no accessible 'New' can be called with these arguments: 'Public Overloads Sub New(name As XName)': Value of type 'S' cannot be converted to 'XName'. 'Public Overloads Sub New(other As XElement)': Value of type 'S' cannot be converted to 'XElement'. 'Public Overloads Sub New(other As XStreamingElement)': Value of type 'S' cannot be converted to 'XStreamingElement'. x = <<%= F6 %>/> ~~~~~~~~~ BC30518: Overload resolution failed because no accessible 'New' can be called with these arguments: 'Public Overloads Sub New(name As XName)': Value of type 'T' cannot be converted to 'XName'. 'Public Overloads Sub New(other As XElement)': Value of type 'T' cannot be converted to 'XElement'. 'Public Overloads Sub New(other As XStreamingElement)': Value of type 'T' cannot be converted to 'XStreamingElement'. x = <<%= F7 %>/> ~~~~~~~~~ ]]></errors>) End Sub ' Expressions within XmlEmbeddedExpressionSyntax should be ' bound, even if outside of an XML expression (error cases). <Fact()> Public Sub EmbeddedExpressionOutsideXmlExpression() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Class A End Class Class B End Class Module M Property P1 As A ReadOnly Property P2 As A Get Return Nothing End Get End Property WriteOnly Property P3 As A Set(value As A) End Set End Property Private F1 As B = <%= P1 %> Private F2 As B = <%= P2 %> Private F3 As B = <%= P3 %> End Module ]]></file> </compilation>, references:=Net40XmlReferences) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC30311: Value of type 'A' cannot be converted to 'B'. Private F1 As B = <%= P1 %> ~~~~~~~~~ BC31172: An embedded expression cannot be used here. Private F1 As B = <%= P1 %> ~~~~~~~~~ BC30311: Value of type 'A' cannot be converted to 'B'. Private F2 As B = <%= P2 %> ~~~~~~~~~ BC31172: An embedded expression cannot be used here. Private F2 As B = <%= P2 %> ~~~~~~~~~ BC31172: An embedded expression cannot be used here. Private F3 As B = <%= P3 %> ~~~~~~~~~ BC30524: Property 'P3' is 'WriteOnly'. Private F3 As B = <%= P3 %> ~~ ]]></errors>) End Sub ' Embedded expressions should be ignored for xmlns ' declarations, even if the expression is a string constant. <Fact()> Public Sub EmbeddedXmlnsExpressions() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Imports System.Xml.Linq Module M Private F1 As XElement = <x:y xmlns:x="http://roslyn"/> Private F2 As XElement = <x:y <%= "xmlns:x" %>="http://roslyn"/> Private F3 As XElement = <x:y <%= XName.Get("x", "http://www.w3.org/2000/xmlns/") %>="http://roslyn"/> End Module ]]></file> </compilation>, references:=Net40XmlReferences) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC31148: XML namespace prefix 'x' is not defined. Private F2 As XElement = <x:y <%= "xmlns:x" %>="http://roslyn"/> ~ BC31148: XML namespace prefix 'x' is not defined. Private F3 As XElement = <x:y <%= XName.Get("x", "http://www.w3.org/2000/xmlns/") %>="http://roslyn"/> ~ ]]></errors>) End Sub <Fact()> Public Sub EmbeddedExpressionCycle() Dim compilation = CompileAndVerify( <compilation> <file name="c.vb"><![CDATA[ Imports System Imports System.Xml.Linq Class C Private Shared F As XElement = <f><%= F %></f> Shared Sub Main() Dim G As XElement = <g><%= G %></g> Console.WriteLine("{0}", F) Console.WriteLine("{0}", G) End Sub End Class ]]></file> </compilation>, references:=Net40XmlReferences, expectedOutput:=<![CDATA[ <f /> <g /> ]]>) End Sub ' Do not evaluate embedded expressions in Imports to avoid cycles. <Fact()> Public Sub EmbeddedExpressionImportCycle() Dim options = TestOptions.ReleaseDll.WithGlobalImports(GlobalImport.Parse({"<xmlns:p=<%= <p:x/>.@y %>>"})) Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Imports <xmlns:q=<%= <q:x/>.@y %>> Module M Private F As String = <p:x q:y=""/>.@z End Module ]]></file> </compilation>, references:=Net40XmlReferences, options:=options) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC31172: Error in project-level import '<xmlns:p=<%= <p:x/>.@y %>>' at '<%= <p:x/>.@y %>' : An embedded expression cannot be used here. BC31172: An embedded expression cannot be used here. Imports <xmlns:q=<%= <q:x/>.@y %>> ~~~~~~~~~~~~~~~~ BC31148: XML namespace prefix 'p' is not defined. Private F As String = <p:x q:y=""/>.@z ~ BC31148: XML namespace prefix 'q' is not defined. Private F As String = <p:x q:y=""/>.@z ~ ]]></errors>) End Sub <Fact()> Public Sub CharacterAndEntityReferences() Dim compilation = CompileAndVerify( <compilation> <file name="c.vb"><![CDATA[ Imports <xmlns:p="&amp;&apos;&#x30;abc"> Class C Shared Sub Main() Dim x = <x xmlns:p="&amp;&apos;&#x30;abc" p:y="&amp;&apos;&gt;&lt;&quot;&#x0058;&#x59;&#x5a;"/> Dim y = <x>&amp;&apos;&gt;&lt;&quot;<y/>&#x0058;&#x59;&#x5a;</x> System.Console.WriteLine(x.@p:y) System.Console.WriteLine(y.Value) End Sub End Class ]]></file> </compilation>, references:=Net40XmlReferences, expectedOutput:=<![CDATA[ &'><"XYZ &'><"XYZ ]]>) compilation.VerifyIL("C.Main", <![CDATA[ { // Code size 193 (0xc1) .maxstack 4 .locals init (System.Xml.Linq.XElement V_0) //x IL_0000: ldstr "x" IL_0005: ldstr "" IL_000a: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_000f: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_0014: dup IL_0015: ldstr "y" IL_001a: ldstr "&'0abc" IL_001f: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0024: ldstr "&'><"XYZ" IL_0029: newobj "Sub System.Xml.Linq.XAttribute..ctor(System.Xml.Linq.XName, Object)" IL_002e: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_0033: dup IL_0034: ldstr "p" IL_0039: ldstr "http://www.w3.org/2000/xmlns/" IL_003e: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0043: ldstr "&'0abc" IL_0048: call "Function System.Xml.Linq.XNamespace.Get(String) As System.Xml.Linq.XNamespace" IL_004d: call "Function My.InternalXmlHelper.CreateNamespaceAttribute(System.Xml.Linq.XName, System.Xml.Linq.XNamespace) As System.Xml.Linq.XAttribute" IL_0052: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_0057: stloc.0 IL_0058: ldstr "x" IL_005d: ldstr "" IL_0062: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0067: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_006c: dup IL_006d: ldstr "&'><"" IL_0072: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_0077: dup IL_0078: ldstr "y" IL_007d: ldstr "" IL_0082: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0087: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_008c: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_0091: dup IL_0092: ldstr "XYZ" IL_0097: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_009c: ldloc.0 IL_009d: ldstr "y" IL_00a2: ldstr "&'0abc" IL_00a7: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_00ac: call "Function My.InternalXmlHelper.get_AttributeValue(System.Xml.Linq.XElement, System.Xml.Linq.XName) As String" IL_00b1: call "Sub System.Console.WriteLine(String)" IL_00b6: callvirt "Function System.Xml.Linq.XElement.get_Value() As String" IL_00bb: call "Sub System.Console.WriteLine(String)" IL_00c0: ret } ]]>) End Sub <Fact()> Public Sub CDATA() Dim compilation = CompileAndVerify( <compilation> <file name="c.vb"> Option Strict On Module M Sub Main() Dim o = &lt;![CDATA[value]]&gt; System.Console.WriteLine("{0}: {1}", o.GetType(), o) End Sub End Module </file> </compilation>, references:=Net40XmlReferences, expectedOutput:="System.Xml.Linq.XCData: <![CDATA[value]]>") compilation.VerifyIL("M.Main", <![CDATA[ { // Code size 29 (0x1d) .maxstack 3 .locals init (System.Xml.Linq.XCData V_0) //o IL_0000: ldstr "value" IL_0005: newobj "Sub System.Xml.Linq.XCData..ctor(String)" IL_000a: stloc.0 IL_000b: ldstr "{0}: {1}" IL_0010: ldloc.0 IL_0011: callvirt "Function Object.GetType() As System.Type" IL_0016: ldloc.0 IL_0017: call "Sub System.Console.WriteLine(String, Object, Object)" IL_001c: ret } ]]>) End Sub <Fact()> Public Sub CDATAContent() Dim compilation = CompileAndVerify( <compilation> <file name="c.vb"> Imports System Imports System.Xml.Linq Module M Sub Main() Dim x As XElement = &lt;a&gt; &lt;![CDATA[&lt;b&gt; &lt;c/&gt; &lt;/&gt;]]&gt; &lt;/a&gt; Console.WriteLine("{0}", x.Value) End Sub End Module </file> </compilation>, references:=Net40XmlReferences, expectedOutput:="<b>" & vbLf & " <c/>" & vbLf & "</>") End Sub <Fact()> Public Sub [GetXmlNamespace]() Dim compilation = CompileAndVerify( <compilation> <file name="c.vb"><![CDATA[ Imports <xmlns:F="http://roslyn/F"> Imports <xmlns:p-q="http://roslyn/p-q"> Module M Private F As Object Sub Main() Report(GetXmlNamespace(xml)) Report(GetXmlNamespace(xmlns)) Report(GetXmlNamespace()) Report(GetXmlNamespace(F)) Report(GetXmlNamespace(p-q)) End Sub Sub Report(o As Object) System.Console.WriteLine("{0}", o) End Sub End Module ]]></file> </compilation>, references:=Net40XmlReferences, expectedOutput:=<![CDATA[ http://www.w3.org/XML/1998/namespace http://www.w3.org/2000/xmlns/ http://roslyn/F http://roslyn/p-q ]]>) compilation.VerifyIL("M.Main", <![CDATA[ { // Code size 76 (0x4c) .maxstack 1 IL_0000: ldstr "http://www.w3.org/XML/1998/namespace" IL_0005: call "Function System.Xml.Linq.XNamespace.Get(String) As System.Xml.Linq.XNamespace" IL_000a: call "Sub M.Report(Object)" IL_000f: ldstr "http://www.w3.org/2000/xmlns/" IL_0014: call "Function System.Xml.Linq.XNamespace.Get(String) As System.Xml.Linq.XNamespace" IL_0019: call "Sub M.Report(Object)" IL_001e: ldstr "" IL_0023: call "Function System.Xml.Linq.XNamespace.Get(String) As System.Xml.Linq.XNamespace" IL_0028: call "Sub M.Report(Object)" IL_002d: ldstr "http://roslyn/F" IL_0032: call "Function System.Xml.Linq.XNamespace.Get(String) As System.Xml.Linq.XNamespace" IL_0037: call "Sub M.Report(Object)" IL_003c: ldstr "http://roslyn/p-q" IL_0041: call "Function System.Xml.Linq.XNamespace.Get(String) As System.Xml.Linq.XNamespace" IL_0046: call "Sub M.Report(Object)" IL_004b: ret } ]]>) End Sub ' Dev10 reports an error (BC31146: "XML name expected.") for ' leading or trailing trivia around the GetXmlNamespace ' argument. Those cases are not treated as errors in Roslyn. <Fact()> Public Sub GetXmlNamespaceWithTrivia() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Imports <xmlns:p="http://roslyn/"> Module M Private F1 = GetXmlNamespace( ) Private F2 = GetXmlNamespace(xml ) Private F3 = GetXmlNamespace( p) End Module ]]></file> </compilation>, references:=Net40XmlReferences) compilation.AssertNoErrors() End Sub <WorkItem(544261, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544261")> <Fact()> Public Sub IncompleteProjectLevelImport() Assert.Throws(Of ArgumentException)(Sub() TestOptions.ReleaseDll.WithGlobalImports(GlobalImport.Parse({"<xmlns:p=""..."""}))) Assert.Throws(Of ArgumentException)(Sub() TestOptions.ReleaseDll.WithGlobalImports(GlobalImport.Parse({"<xmlns:p=""..."">, <xmlns:q=""..."""}))) End Sub <WorkItem(544360, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544360")> <Fact()> Public Sub ExplicitDefaultXmlnsAttribute_1() Dim compilation = CompileAndVerify( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Module M Sub Main() Report(<x xmlns=" "/>) Report(<y xmlns="http://roslyn"/>) End Sub Sub Report(x As System.Xml.Linq.XElement) System.Console.WriteLine("[{0}, {1}]: {2}", x.Name.LocalName, x.Name.NamespaceName, x) End Sub End Module ]]></file> </compilation>, references:=Net40XmlReferences, expectedOutput:=<![CDATA[ [x, ]: <x xmlns=" " /> [y, http://roslyn]: <y xmlns="http://roslyn" /> ]]>) End Sub <Fact()> Public Sub ExplicitDefaultXmlnsAttribute_2() Dim compilation = CompileAndVerify( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports <xmlns="http://roslyn/1"> Module M Sub Main() Report(<x xmlns="http://roslyn/2"/>) End Sub Sub Report(x As System.Xml.Linq.XElement) System.Console.WriteLine("[{0}, {1}]: {2}", x.Name.LocalName, x.Name.NamespaceName, x) End Sub End Module ]]></file> </compilation>, references:=Net40XmlReferences, expectedOutput:=<![CDATA[ [x, http://roslyn/2]: <x xmlns="http://roslyn/2" /> ]]>) End Sub <WorkItem(544461, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544461")> <Fact()> Public Sub ValueExtensionProperty() Dim compilation = CompileAndVerify( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports System.Collections.Generic Imports System.Xml.Linq Class X Inherits XElement Public Sub New(name As XName) MyBase.New(name) End Sub End Class Structure S Implements IEnumerable(Of XElement) Public Function GetEnumerator() As IEnumerator(Of XElement) Implements IEnumerable(Of XElement).GetEnumerator Return Nothing End Function Public Function GetEnumerator1() As System.Collections.IEnumerator Implements System.Collections.IEnumerable.GetEnumerator Return Nothing End Function End Structure Interface IEnumerableOfXElement Inherits IEnumerable(Of XElement) End Interface Module M Sub M(Of T As XElement)( _1 As XElement, _2 As X, _3 As T, _4 As IEnumerable(Of XElement), _5 As IEnumerable(Of X), _6 As IEnumerable(Of T), _7 As IEnumerableOfXElement, _8 As XElement(), _9 As List(Of XElement), _10 As S) Dim o As Object o = <x/>.Value o = <x/>.<y>.Value o = _1.Value o = _2.Value o = _3.Value o = _4.Value o = _5.Value o = _6.Value o = _7.Value o = _8.Value o = _9.Value o = _10.Value End Sub End Module ]]></file> </compilation>, references:=Net40XmlReferences) compilation.VerifyIL("M.M(Of T)", <![CDATA[ { // Code size 166 (0xa6) .maxstack 3 IL_0000: ldstr "x" IL_0005: ldstr "" IL_000a: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_000f: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_0014: call "Function System.Xml.Linq.XElement.get_Value() As String" IL_0019: pop IL_001a: ldstr "x" IL_001f: ldstr "" IL_0024: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0029: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_002e: ldstr "y" IL_0033: ldstr "" IL_0038: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_003d: call "Function System.Xml.Linq.XContainer.Elements(System.Xml.Linq.XName) As System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)" IL_0042: call "Function My.InternalXmlHelper.get_Value(System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)) As String" IL_0047: pop IL_0048: ldarg.0 IL_0049: callvirt "Function System.Xml.Linq.XElement.get_Value() As String" IL_004e: pop IL_004f: ldarg.1 IL_0050: callvirt "Function System.Xml.Linq.XElement.get_Value() As String" IL_0055: pop IL_0056: ldarga.s V_2 IL_0058: constrained. "T" IL_005e: callvirt "Function System.Xml.Linq.XElement.get_Value() As String" IL_0063: pop IL_0064: ldarg.3 IL_0065: call "Function My.InternalXmlHelper.get_Value(System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)) As String" IL_006a: pop IL_006b: ldarg.s V_4 IL_006d: call "Function My.InternalXmlHelper.get_Value(System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)) As String" IL_0072: pop IL_0073: ldarg.s V_5 IL_0075: call "Function My.InternalXmlHelper.get_Value(System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)) As String" IL_007a: pop IL_007b: ldarg.s V_6 IL_007d: call "Function My.InternalXmlHelper.get_Value(System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)) As String" IL_0082: pop IL_0083: ldarg.s V_7 IL_0085: call "Function My.InternalXmlHelper.get_Value(System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)) As String" IL_008a: pop IL_008b: ldarg.s V_8 IL_008d: call "Function My.InternalXmlHelper.get_Value(System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)) As String" IL_0092: pop IL_0093: ldarg.s V_9 IL_0095: box "S" IL_009a: castclass "System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)" IL_009f: call "Function My.InternalXmlHelper.get_Value(System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)) As String" IL_00a4: pop IL_00a5: ret } ]]>) End Sub <Fact()> Public Sub ValueExtensionProperty_2() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports System Imports System.Collections.Generic Imports System.Runtime.CompilerServices Imports System.Xml.Linq Class A Inherits List(Of XElement) Public Property P As String End Class Class B Inherits A Public Property Value As String End Class Class C Inherits A Public Value As String End Class Class D Inherits A Public Property Value(o As Object) As String Get Return Nothing End Get Set(value As String) End Set End Property End Class Class E Inherits A Public Function Value() As String Return Nothing End Function End Class Class F Inherits A End Class Module M <Extension()> Public Function Value(o As F) As String Return Nothing End Function Sub M() Dim _a As New A() With {.Value = .P, .P = .Value} Dim _b As New B() With {.Value = .P, .P = .Value} Dim _c As New C() With {.Value = .P, .P = .Value} Dim _d As New D() With {.Value = .P, .P = .Value} Dim _e As New E() With {.Value = .P, .P = .Value} Dim _f As New F() With {.Value = .P, .P = .Value} _a.VALUE = Nothing _b.VALUE = Nothing _c.VALUE = Nothing _d.value = Nothing _e.value = Nothing _f.value = Nothing End Sub End Module ]]></file> </compilation>, references:=Net40XmlReferences) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC30991: Member 'Value' cannot be initialized in an object initializer expression because it is shared. Dim _a As New A() With {.Value = .P, .P = .Value} ~~~~~ BC30992: Property 'Value' cannot be initialized in an object initializer expression because it requires arguments. Dim _d As New D() With {.Value = .P, .P = .Value} ~~~~~ BC30455: Argument not specified for parameter 'o' of 'Public Property Value(o As Object) As String'. Dim _d As New D() With {.Value = .P, .P = .Value} ~~~~~ BC30990: Member 'Value' cannot be initialized in an object initializer expression because it is not a field or property. Dim _e As New E() With {.Value = .P, .P = .Value} ~~~~~ BC30990: Member 'Value' cannot be initialized in an object initializer expression because it is not a field or property. Dim _f As New F() With {.Value = .P, .P = .Value} ~~~~~ BC30455: Argument not specified for parameter 'o' of 'Public Property Value(o As Object) As String'. _d.value = Nothing ~~~~~ BC30068: Expression is a value and therefore cannot be the target of an assignment. _e.value = Nothing ~~~~~~~~ BC30068: Expression is a value and therefore cannot be the target of an assignment. _f.value = Nothing ~~~~~~~~ ]]></errors>) End Sub <Fact()> Public Sub ValueExtensionProperty_3() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports System.Collections.Generic Imports System.Xml.Linq Class C Inherits List(Of XElement) Sub M() Me.Value = F(Me.Value) MyBase.Value = F(MyBase.Value) Value = F(Value) Dim c As Char = Me.Value(0) c = Me.Value()(1) Me.Value() = Me.Value(Of Object)() End Sub Function F(o As String) As String Return Nothing End Function End Class ]]></file> </compilation>, references:=Net40XmlReferences) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC30469: Reference to a non-shared member requires an object reference. Value = F(Value) ~~~~~ BC30469: Reference to a non-shared member requires an object reference. Value = F(Value) ~~~~~ BC30456: 'Value' is not a member of 'C'. Me.Value() = Me.Value(Of Object)() ~~~~~~~~~~~~~~~~~~~ ]]></errors>) End Sub <Fact()> Public Sub ValueExtensionProperty_4() Dim compilation = CompileAndVerify( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports System Imports System.Collections.Generic Imports System.Xml.Linq Module M Sub Main() Dim x = <x> <y>content</y> <z/> </x> x.<x>.Value += "1" x.<y>.Value += "2" Add(x.<z>.Value, "3") Console.WriteLine("{0}", x) End Sub Sub Add(ByRef s As String, value As String) s += value End Sub End Module ]]></file> </compilation>, references:=Net40XmlReferences, expectedOutput:=<![CDATA[ <x> <y>content2</y> <z>3</z> </x> ]]>) End Sub ''' <summary> ''' If there is an accessible extension method named "Value", the InternalXmlHelper ''' Value extension property should be dropped, since we do not perform overload ''' resolution between methods and properties. If the extension method is inaccessible ''' however, the InternalXmlHelper property should be used. ''' </summary> <Fact()> Public Sub ValueExtensionPropertyAndExtensionMethod() ' Accessible extension method. Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Imports System.Collections.Generic Imports System.Runtime.CompilerServices Imports System.Xml.Linq Class C Sub M() Dim x = <x/>.<y> Dim o = x.Value() x.Value(o) End Sub End Class Module M <Extension()> Function Value(x As IEnumerable(Of XElement), y As Object) As Object Return Nothing End Function End Module ]]></file> </compilation>, references:=Net40XmlReferences) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC36586: Argument not specified for parameter 'y' of extension method 'Public Function Value(y As Object) As Object' defined in 'M'. Dim o = x.Value() ~~~~~ ]]></errors>) ' Inaccessible extension method. compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Imports System.Collections.Generic Imports System.Runtime.CompilerServices Imports System.Xml.Linq Class C Sub M() Dim x = <x/>.<y> Dim o = x.Value() x.Value(o) End Sub End Class Module M <Extension()> Private Function Value(x As IEnumerable(Of XElement), y As Object) As Object Return Nothing End Function End Module ]]></file> </compilation>, references:=Net40XmlReferences) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC30057: Too many arguments to 'Public Property Value As String'. x.Value(o) ~ ]]></errors>) End Sub ''' <summary> ''' Bind to InternalXmlHelper Value extension property if a member named "Value" is inaccessible. ''' Note that Dev11 ignores the InternalXmlHelper property if regular binding finds a ''' member (in this case, the inaccessible member). Therefore this is a breaking change. ''' </summary> <Fact()> Public Sub ValueExtensionPropertyAndInaccessibleMember() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Imports System.Collections Imports System.Collections.Generic Imports System.Xml.Linq Structure S Implements IEnumerable(Of XElement) Public Function GetEnumerator() As IEnumerator(Of XElement) Implements IEnumerable(Of XElement).GetEnumerator Return Nothing End Function Public Function GetEnumerator1() As IEnumerator Implements IEnumerable.GetEnumerator Return Nothing End Function Private Property Value As Object End Structure Module M Function F(o As S) ' Dev11: BC30390: 'S.Value' is not accessible in this context because it is 'Private'. Return o.Value End Function End Module ]]></file> </compilation>, references:=Net40XmlReferences) compilation.AssertNoErrors() End Sub ' The InternalXmlHelper.Value extension property should be available ' for IEnumerable(Of XElement) only. The AttributeValue extension property ' is overloaded for XElement and IEnumerable(Of XElement) but should ' only be available if the namespace is imported. <Fact()> Public Sub ValueAndAttributeValueExtensionProperties() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports System.Collections.Generic Imports System.Xml.Linq Class X Inherits XElement Public Sub New(name As XName) MyBase.New(name) End Sub End Class Interface IEnumerableOfXElement Inherits IEnumerable(Of XElement) End Interface Module M Sub M(Of T As XElement)( _1 As XObject, _2 As XElement, _3 As X, _4 As T, _5 As IEnumerable(Of XObject), _6 As IEnumerable(Of XElement), _7 As IEnumerable(Of X), _8 As IEnumerable(Of T), _9 As IEnumerableOfXElement, _10 As XElement(), _11 As List(Of XElement), _12 As IEnumerable(Of XElement)()) Dim name As XName = Nothing Dim o As Object o = <x/>.Value o = <x/>.AttributeValue(name) o = <x/>.<y>.Value o = <x/>.<y>.AttributeValue(name) o = <x/>[email protected] o = <x/>[email protected](name) o = _1.Value o = _1.AttributeValue(name) o = _2.Value o = _2.AttributeValue(name) o = _3.Value o = _3.AttributeValue(name) o = _4.Value o = _4.AttributeValue(name) o = _5.Value o = _5.AttributeValue(name) o = _6.Value o = _6.AttributeValue(name) o = _7.Value o = _7.AttributeValue(name) o = _8.Value o = _8.AttributeValue(name) o = _9.Value o = _9.AttributeValue(name) o = _10.Value o = _10.AttributeValue(name) o = _11.Value o = _11.AttributeValue(name) o = _12.Value o = _12.AttributeValue(name) End Sub End Module ]]></file> </compilation>, references:=Net40XmlReferences) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC30456: 'AttributeValue' is not a member of 'XElement'. o = <x/>.AttributeValue(name) ~~~~~~~~~~~~~~~~~~~ BC30456: 'AttributeValue' is not a member of 'IEnumerable(Of XElement)'. o = <x/>.<y>.AttributeValue(name) ~~~~~~~~~~~~~~~~~~~~~~~ BC30456: 'Value' is not a member of 'String'. o = <x/>[email protected] ~~~~~~~~~~~~~ BC30456: 'AttributeValue' is not a member of 'String'. o = <x/>[email protected](name) ~~~~~~~~~~~~~~~~~~~~~~ BC30456: 'Value' is not a member of 'XObject'. o = _1.Value ~~~~~~~~ BC30456: 'AttributeValue' is not a member of 'XObject'. o = _1.AttributeValue(name) ~~~~~~~~~~~~~~~~~ BC30456: 'AttributeValue' is not a member of 'XElement'. o = _2.AttributeValue(name) ~~~~~~~~~~~~~~~~~ BC30456: 'AttributeValue' is not a member of 'X'. o = _3.AttributeValue(name) ~~~~~~~~~~~~~~~~~ BC30456: 'AttributeValue' is not a member of 'T'. o = _4.AttributeValue(name) ~~~~~~~~~~~~~~~~~ BC30456: 'Value' is not a member of 'IEnumerable(Of XObject)'. o = _5.Value ~~~~~~~~ BC30456: 'AttributeValue' is not a member of 'IEnumerable(Of XObject)'. o = _5.AttributeValue(name) ~~~~~~~~~~~~~~~~~ BC30456: 'AttributeValue' is not a member of 'IEnumerable(Of XElement)'. o = _6.AttributeValue(name) ~~~~~~~~~~~~~~~~~ BC30456: 'AttributeValue' is not a member of 'IEnumerable(Of X)'. o = _7.AttributeValue(name) ~~~~~~~~~~~~~~~~~ BC30456: 'AttributeValue' is not a member of 'IEnumerable(Of T As XElement)'. o = _8.AttributeValue(name) ~~~~~~~~~~~~~~~~~ BC30456: 'AttributeValue' is not a member of 'IEnumerableOfXElement'. o = _9.AttributeValue(name) ~~~~~~~~~~~~~~~~~ BC30456: 'AttributeValue' is not a member of 'XElement()'. o = _10.AttributeValue(name) ~~~~~~~~~~~~~~~~~~ BC30456: 'AttributeValue' is not a member of 'List(Of XElement)'. o = _11.AttributeValue(name) ~~~~~~~~~~~~~~~~~~ BC30456: 'Value' is not a member of 'IEnumerable(Of XElement)()'. o = _12.Value ~~~~~~~~~ BC30456: 'AttributeValue' is not a member of 'IEnumerable(Of XElement)()'. o = _12.AttributeValue(name) ~~~~~~~~~~~~~~~~~~ ]]></errors>) End Sub <Fact()> Public Sub TrimElementContent() Dim compilation = CompileAndVerify( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports Microsoft.VisualBasic Imports System Imports System.Xml.Linq Module M Private F As XElement = <x> <y> <z> nested </z> </y> <y> &#x20; <z> nested </z> &#x20; </y> <y> begin <z> nested </z> end </y> <y xml:space="default"> begin <z> nested </z> end </y> <y xml:space="preserve"> begin <z> nested </z> end </y> </x> Sub Main() For Each y In F.<y> Console.Write("{0}" & Environment.NewLine, y.ToString()) Console.Write("[{0}]" & Environment.NewLine, y.Value.Replace(vbLf, Environment.NewLine)) Next End Sub End Module ]]></file> </compilation>, references:=Net40XmlReferences, expectedOutput:=<![CDATA[ <y> <z> nested </z> </y> [ nested ] <y> <z> nested </z> </y> [ nested ] <y> begin <z> nested </z> end </y> [ begin nested end ] <y xml:space="default"> begin <z> nested </z> end </y> [ begin nested end ] <y xml:space="preserve"> begin <z> nested </z> end </y> [ begin nested end ] ]]>) End Sub ''' <summary> ''' CR/LF and single CR characters should be ''' replaced by single LF characters. ''' </summary> <WorkItem(545508, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545508")> <Fact()> Public Sub NormalizeNewlinesTest() For Each eol In {vbCr, vbLf, vbCrLf} Dim sourceBuilder = New StringBuilder() sourceBuilder.AppendLine("Module M") sourceBuilder.AppendLine(" Sub Main()") sourceBuilder.AppendLine(" Report(<x>[" & eol & "|" & eol & eol & "]</>.Value)") sourceBuilder.AppendLine(" Report(<x><![CDATA[[" & eol & "|" & eol & eol & "]]]></>.Value)") sourceBuilder.AppendLine(" End Sub") sourceBuilder.AppendLine(" Sub Report(s As String)") sourceBuilder.AppendLine(" For Each c As Char in s") sourceBuilder.AppendLine(" System.Console.WriteLine(""{0}"", Microsoft.VisualBasic.AscW(c))") sourceBuilder.AppendLine(" Next") sourceBuilder.AppendLine(" End Sub") sourceBuilder.AppendLine("End Module") Dim sourceTree = VisualBasicSyntaxTree.ParseText(sourceBuilder.ToString()) Dim comp = VisualBasicCompilation.Create(Guid.NewGuid().ToString(), {sourceTree}, DefaultVbReferences.Concat(Net40XmlReferences)) CompileAndVerify(comp, expectedOutput:=<![CDATA[ 91 10 124 10 10 93 91 10 124 10 10 93 ]]>) Next End Sub <Fact()> Public Sub NormalizeAttributeValue() Const space = " " Dim strs = {space, vbCr, vbLf, vbCrLf, vbTab, "&#x20;", "&#xD;", "&#xA;", "&#x9;"} ' Empty string. NormalizeAttributeValueCore("") ' Single characters. For Each str0 In strs NormalizeAttributeValueCore(str0) NormalizeAttributeValueCore("[" & str0 & "]") Next ' Pairs of characters. For Each str1 In strs For Each str2 In strs Dim str = str1 & str2 NormalizeAttributeValueCore(str) NormalizeAttributeValueCore("[" & str & "]") Next Next End Sub Private Sub NormalizeAttributeValueCore(str As String) Dim sourceBuilder = New StringBuilder() sourceBuilder.AppendLine("Module M") sourceBuilder.AppendLine(" Sub Main()") sourceBuilder.AppendLine(" System.Console.WriteLine(""[[{0}]]"", <x a=""" & str & """/>.@a)") sourceBuilder.AppendLine(" End Sub") sourceBuilder.AppendLine("End Module") Dim sourceTree = VisualBasicSyntaxTree.ParseText(sourceBuilder.ToString()) Dim comp = VisualBasicCompilation.Create(Guid.NewGuid().ToString(), {sourceTree}, DefaultVbReferences.Concat(Net40XmlReferences)) CompileAndVerify(comp, expectedOutput:="[[" & NormalizeValue(str) & "]]") End Sub Private Function NormalizeValue(str As String) As String Const space = " " str = str.Replace(vbCrLf, space) str = str.Replace(vbCr, space) str = str.Replace(vbLf, space) str = str.Replace(vbTab, space) str = str.Replace("&#x20;", space) str = str.Replace("&#xD;", vbCr) str = str.Replace("&#xA;", vbLf) str = str.Replace("&#x9;", vbTab) Return str End Function ' Dev11 treats p:xmlns="..." as an xmlns declaration for the default ' namespace. Roslyn issues warnings for these cases and only considers ' p:xmlns="..." an xmlns declaration if 'p' maps to the default namespace. <WorkItem(544366, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544366")> <Fact()> Public Sub PrefixAndXmlnsLocalName() Dim compilation = CompileAndVerify( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports System Imports System.Xml.Linq Imports <xmlns="N0"> Imports <xmlns:p1=""> Imports <xmlns:p2="N2"> Module M Sub Main() Report(<x1 p1:a="b"/>) Report(<x2 p2:a="b"/>) Report(<y1 p1:xmlns="A1"/>) Report(<y2 p2:xmlns="A2"/>) Report(<y3 xmlns:p3="N3" p3:xmlns="A3"/>) End Sub Sub Report(x As XElement) Console.WriteLine("{0}: {1}", x.Name, x) For Each a In x.Attributes Console.WriteLine(" {0}", a.Name) Next End Sub End Module ]]></file> </compilation>, references:=Net40XmlReferences, expectedOutput:=<![CDATA[ {N0}x1: <x1 a="b" xmlns="N0" /> a xmlns {N0}x2: <x2 p2:a="b" xmlns:p2="N2" xmlns="N0" /> {N2}a {http://www.w3.org/2000/xmlns/}p2 xmlns {A1}y1: <y1 xmlns="A1" /> xmlns {N0}y2: <y2 p2:xmlns="A2" xmlns:p2="N2" xmlns="N0" /> {N2}xmlns {http://www.w3.org/2000/xmlns/}p2 xmlns {N0}y3: <y3 xmlns:p3="N3" p3:xmlns="A3" xmlns="N0" /> {http://www.w3.org/2000/xmlns/}p3 {N3}xmlns xmlns ]]>) compilation.Compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC42368: The xmlns attribute has special meaning and should not be written with a prefix. Report(<y1 p1:xmlns="A1"/>) ~~~~~~~~ BC42360: It is not recommended to have attributes named xmlns. Did you mean to write 'xmlns:p2' to define a prefix named 'p2'? Report(<y2 p2:xmlns="A2"/>) ~~~~~~~~ BC42360: It is not recommended to have attributes named xmlns. Did you mean to write 'xmlns:p3' to define a prefix named 'p3'? Report(<y3 xmlns:p3="N3" p3:xmlns="A3"/>) ~~~~~~~~ ]]></errors>) End Sub ' BC42361 is a warning only and should not prevent code gen. <Fact()> Public Sub BC42361WRN_UseValueForXmlExpression3() Dim compilation = CompileAndVerify( <compilation> <file name="c.vb"><![CDATA[ Option Strict Off Module M Sub Main() System.Console.WriteLine("{0}", If(TryCast(<x/>.<y>, String), "[Nothing]")) End Sub End Module ]]></file> </compilation>, references:=Net40XmlReferences, expectedOutput:=<![CDATA[ [Nothing] ]]>) compilation.Compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC42361: Cannot convert 'IEnumerable(Of XElement)' to 'String'. You can use the 'Value' property to get the string value of the first element of 'IEnumerable(Of XElement)'. System.Console.WriteLine("{0}", If(TryCast(<x/>.<y>, String), "[Nothing]")) ~~~~~~~~ ]]></errors>) End Sub <Fact()> Public Sub UseLocallyRedefinedImport() Dim compilation = CompileAndVerify( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports <xmlns:p="http://roslyn/"> Module M Sub Main() ' Local declaration never used. Report(<x0 xmlns:p="http://roslyn/" a="b"/>) ' Local declaration used at root. Report(<x1 xmlns:p="http://roslyn/" p:a="b"/>) ' Local declaration used beneath root. Report(<x2 xmlns:p="http://roslyn/"> <y p:a="b"/> </x2>) ' Local declaration defined and used beneath root. Report(<x3> <y xmlns:p="http://roslyn/" p:a="b"/> </x3>) ' Local declaration defined beneath root and used below. Report(<x4> <y xmlns:p="http://roslyn/"> <z p:a="b"/> </y> </x4>) ' Local declaration defined beneath root and used on sibling. Report(<x5> <y xmlns:p="http://roslyn/"/> <z p:a="b"/> </x5>) ' Local declaration re-defined at root. Report(<x6 xmlns:p="http://roslyn/other" p:a="b"/>) ' Local declaration re-defined beneath root. Report(<x7> <y xmlns:p="http://roslyn/other" p:a="b"/> </x7>) ' Local declaration defined and re-defined. Report(<x8 xmlns:p="http://roslyn/" p:a1="b1"> <y xmlns:p="http://roslyn/other" p:a2="b2"> <z xmlns:p="http://roslyn/" p:a3="b3"/> </y> </x8>) End Sub Sub Report(o As Object) System.Console.WriteLine("{0}", o) End Sub End Module ]]></file> </compilation>, references:=Net40XmlReferences, expectedOutput:=<![CDATA[ <x0 a="b" xmlns:p="http://roslyn/" /> <x1 p:a="b" xmlns:p="http://roslyn/" /> <x2 xmlns:p="http://roslyn/"> <y p:a="b" /> </x2> <x3 xmlns:p="http://roslyn/"> <y p:a="b" /> </x3> <x4 xmlns:p="http://roslyn/"> <y> <z p:a="b" /> </y> </x4> <x5 xmlns:p="http://roslyn/"> <y /> <z p:a="b" /> </x5> <x6 xmlns:p="http://roslyn/other" p:a="b" /> <x7> <y xmlns:p="http://roslyn/other" p:a="b" /> </x7> <x8 p:a1="b1" xmlns:p="http://roslyn/"> <y xmlns:p="http://roslyn/other" p:a2="b2"> <z xmlns:p="http://roslyn/" p:a3="b3" /> </y> </x8> ]]>) End Sub ' If the xmlns attribute is a re-definition of an Imports xmlns ' declaration, the attribute should be created with CreateNamespaceAttribute ' (so the attribute can be removed if the element is embedded). ' Otherwise, the attribute should be created with XAttribute .ctor. <Fact()> Public Sub ConstructingXmlnsAttributes() ' The only difference between b.vb and c.vb is that c.vb ' contains an Imports <xmlns:...> declaration that matches ' the explicit xmlns declaration within the XElement. Dim compilation = CompileAndVerify( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Partial Class C Shared Sub Main() M1() M2() End Sub Shared Sub Report(o As Object) System.Console.WriteLine("{0}", o) End Sub End Class ]]></file> <file name="b.vb"><![CDATA[ Option Strict On Partial Class C Shared Sub M1() Report(<x xmlns:p="http://roslyn/"/>) End Sub End Class ]]></file> <file name="c.vb"><![CDATA[ Option Strict On Imports <xmlns:p="http://roslyn/"> Partial Class C Shared Sub M2() Report(<x xmlns:p="http://roslyn/"/>) End Sub End Class ]]></file> </compilation>, references:=Net40XmlReferences, expectedOutput:=<![CDATA[ <x xmlns:p="http://roslyn/" /> <x xmlns:p="http://roslyn/" /> ]]>) ' If no matching Imports, use XAttribute .ctor. compilation.VerifyIL("C.M1()", <![CDATA[ { // Code size 57 (0x39) .maxstack 4 IL_0000: ldstr "x" IL_0005: ldstr "" IL_000a: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_000f: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_0014: dup IL_0015: ldstr "p" IL_001a: ldstr "http://www.w3.org/2000/xmlns/" IL_001f: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0024: ldstr "http://roslyn/" IL_0029: newobj "Sub System.Xml.Linq.XAttribute..ctor(System.Xml.Linq.XName, Object)" IL_002e: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_0033: call "Sub C.Report(Object)" IL_0038: ret } ]]>) ' If matching Imports, use CreateNamespaceAttribute. compilation.VerifyIL("C.M2()", <![CDATA[ { // Code size 62 (0x3e) .maxstack 4 IL_0000: ldstr "x" IL_0005: ldstr "" IL_000a: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_000f: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_0014: dup IL_0015: ldstr "p" IL_001a: ldstr "http://www.w3.org/2000/xmlns/" IL_001f: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0024: ldstr "http://roslyn/" IL_0029: call "Function System.Xml.Linq.XNamespace.Get(String) As System.Xml.Linq.XNamespace" IL_002e: call "Function My.InternalXmlHelper.CreateNamespaceAttribute(System.Xml.Linq.XName, System.Xml.Linq.XNamespace) As System.Xml.Linq.XAttribute" IL_0033: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_0038: call "Sub C.Report(Object)" IL_003d: ret } ]]>) End Sub <WorkItem(545345, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545345")> <Fact()> Public Sub RemoveExistingNamespaceAttribute() Dim compilation = CompileAndVerify( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports System.Xml.Linq Imports <xmlns:p="http://roslyn/p"> Partial Class C Shared Function F1() As XElement Return <p:y/> End Function Shared Sub Main() Report(<x xmlns:p="http://roslyn/p"><%= F1() %></x>) Report(<x xmlns:p="http://roslyn/q"><%= F1() %></x>) Report(<x xmlns:p="http://roslyn/q"><%= F2() %></x>) Report(<x xmlns:q="http://roslyn/q"><%= F2() %></x>) Report(<x xmlns:p="http://Roslyn/p"><%= F1() %></x>) End Sub Shared Sub Report(x As XElement) System.Console.WriteLine("{0}", x) End Sub End Class ]]></file> <file name="b.vb"><![CDATA[ Option Strict On Imports System.Xml.Linq Imports <xmlns:q="http://roslyn/q"> Partial Class C Shared Function F2() As XElement Return <q:y/> End Function End Class ]]></file> </compilation>, references:=Net40XmlReferences, expectedOutput:=<![CDATA[ <x xmlns:p="http://roslyn/p"> <p:y /> </x> <x xmlns:p="http://roslyn/q"> <p:y xmlns:p="http://roslyn/p" /> </x> <x xmlns:p="http://roslyn/q" xmlns:q="http://roslyn/q"> <q:y /> </x> <x xmlns:q="http://roslyn/q"> <q:y /> </x> <x xmlns:p="http://Roslyn/p"> <p:y xmlns:p="http://roslyn/p" /> </x> ]]>) End Sub <Fact()> Public Sub DefaultAndEmptyNamespaces_1() Dim compilation = CompileAndVerify( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports <xmlns=""> Imports <xmlns:e=""> Module M Sub Main() Report(<x e:a="1"/>) Report(<e:x a="1"/>) Report(<e:x><y/></e:x>) Report(<x><e:y/></x>) End Sub Sub Report(o As Object) System.Console.WriteLine("{0}", o) End Sub End Module ]]></file> </compilation>, references:=Net40XmlReferences, expectedOutput:=<![CDATA[ <x a="1" /> <x a="1" xmlns="" /> <x xmlns=""> <y /> </x> <x xmlns=""> <y /> </x> ]]>) End Sub <WorkItem(545401, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545401")> <Fact()> Public Sub DefaultAndEmptyNamespaces_2() Dim compilation = CompileAndVerify( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports <xmlns="default"> Imports <xmlns:e=""> Imports <xmlns:p="ns"> Module M Sub Main() Report(<x e:a="1" p:b="2"/>) Report(<e:x a="1" p:b="2"/>) Report(<p:x e:a="1" b="2"/>) Report(<e:x><y/><p:z/></e:x>) Report(<x><e:y/><p:z/></x>) Report(<p:x><e:y/><z/></p:x>) End Sub Sub Report(o As Object) System.Console.WriteLine("{0}", o) End Sub End Module ]]></file> </compilation>, references:=Net40XmlReferences, expectedOutput:=<![CDATA[ <x a="1" p:b="2" xmlns:p="ns" xmlns="default" /> <x a="1" p:b="2" xmlns:p="ns" xmlns="" /> <p:x a="1" b="2" xmlns:p="ns" /> <x xmlns:p="ns" xmlns=""> <y xmlns="default" /> <p:z /> </x> <x xmlns:p="ns" xmlns="default"> <y xmlns="" /> <p:z /> </x> <p:x xmlns="" xmlns:p="ns"> <y /> <z xmlns="default" /> </p:x> ]]>) End Sub ''' <summary> ''' Should not call RemoveNamespaceAttributes ''' on intrinsic types or enums. ''' </summary> <WorkItem(546191, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546191")> <Fact()> Public Sub RemoveNamespaceAttributes_OtherContentTypes() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"><![CDATA[ Imports System Imports <xmlns:p="http://roslyn"> Enum E A End Enum Structure S End Structure Class C(Of T) Private _1 As Object = Nothing Private _2 As Boolean = False Private _3 As Byte = 0 Private _4 As SByte = 0 Private _5 As Int16 = 0 Private _6 As UInt16 = 0 Private _7 As Int32 = 0 Private _8 As UInt32 = 0 Private _9 As Int64 = 0 Private _10 As UInt64 = 0 Private _11 As Single = 0 Private _12 As Double = 0 Private _13 As Decimal = 0 Private _14 As DateTime = Nothing Private _15 As Char = Nothing Private _16 As String = "" Private _17 As E = E.A Private _18 As Integer? = Nothing Private _19 As S = Nothing Private _20 As T = Nothing Private _21 As ValueType = E.A Private _22 As System.Enum = E.A Private _23 As Object() = Nothing Private _24 As Array = Nothing Function F1() As Object Return <x><%= _1 %></x> End Function Function F2() As Object Return <x><%= _2 %></x> End Function Function F3() As Object Return <x><%= _3 %></x> End Function Function F4() As Object Return <x><%= _4 %></x> End Function Function F5() As Object Return <x><%= _5 %></x> End Function Function F6() As Object Return <x><%= _6 %></x> End Function Function F7() As Object Return <x><%= _7 %></x> End Function Function F8() As Object Return <x><%= _8 %></x> End Function Function F9() As Object Return <x><%= _9 %></x> End Function Function F10() As Object Return <x><%= _10 %></x> End Function Function F11() As Object Return <x><%= _11 %></x> End Function Function F12() As Object Return <x><%= _12 %></x> End Function Function F13() As Object Return <x><%= _13 %></x> End Function Function F14() As Object Return <x><%= _14 %></x> End Function Function F15() As Object Return <x><%= _15 %></x> End Function Function F16() As Object Return <x><%= _16 %></x> End Function Function F17() As Object Return <x><%= _17 %></x> End Function Function F18() As Object Return <x><%= _18 %></x> End Function Function F19() As Object Return <x><%= _19 %></x> End Function Function F20() As Object Return <x><%= _20 %></x> End Function Function F21() As Object Return <x><%= _21 %></x> End Function Function F22() As Object Return <x><%= _22 %></x> End Function Function F23() As Object Return <x><%= _23 %></x> End Function Function F24() As Object Return <x><%= _24 %></x> End Function End Class ]]></file> </compilation>, references:=Net40XmlReferences) Assert.True(CallsRemoveNamespaceAttributes(verifier.VisualizeIL("C(Of T).F1()"))) Assert.False(CallsRemoveNamespaceAttributes(verifier.VisualizeIL("C(Of T).F2()"))) Assert.False(CallsRemoveNamespaceAttributes(verifier.VisualizeIL("C(Of T).F3()"))) Assert.False(CallsRemoveNamespaceAttributes(verifier.VisualizeIL("C(Of T).F4()"))) Assert.False(CallsRemoveNamespaceAttributes(verifier.VisualizeIL("C(Of T).F5()"))) Assert.False(CallsRemoveNamespaceAttributes(verifier.VisualizeIL("C(Of T).F6()"))) Assert.False(CallsRemoveNamespaceAttributes(verifier.VisualizeIL("C(Of T).F7()"))) Assert.False(CallsRemoveNamespaceAttributes(verifier.VisualizeIL("C(Of T).F8()"))) Assert.False(CallsRemoveNamespaceAttributes(verifier.VisualizeIL("C(Of T).F9()"))) Assert.False(CallsRemoveNamespaceAttributes(verifier.VisualizeIL("C(Of T).F10()"))) Assert.False(CallsRemoveNamespaceAttributes(verifier.VisualizeIL("C(Of T).F11()"))) Assert.False(CallsRemoveNamespaceAttributes(verifier.VisualizeIL("C(Of T).F12()"))) Assert.False(CallsRemoveNamespaceAttributes(verifier.VisualizeIL("C(Of T).F13()"))) Assert.False(CallsRemoveNamespaceAttributes(verifier.VisualizeIL("C(Of T).F14()"))) Assert.False(CallsRemoveNamespaceAttributes(verifier.VisualizeIL("C(Of T).F15()"))) Assert.False(CallsRemoveNamespaceAttributes(verifier.VisualizeIL("C(Of T).F16()"))) Assert.False(CallsRemoveNamespaceAttributes(verifier.VisualizeIL("C(Of T).F17()"))) Assert.True(CallsRemoveNamespaceAttributes(verifier.VisualizeIL("C(Of T).F18()"))) Assert.True(CallsRemoveNamespaceAttributes(verifier.VisualizeIL("C(Of T).F19()"))) Assert.True(CallsRemoveNamespaceAttributes(verifier.VisualizeIL("C(Of T).F20()"))) Assert.True(CallsRemoveNamespaceAttributes(verifier.VisualizeIL("C(Of T).F21()"))) Assert.True(CallsRemoveNamespaceAttributes(verifier.VisualizeIL("C(Of T).F22()"))) Assert.True(CallsRemoveNamespaceAttributes(verifier.VisualizeIL("C(Of T).F23()"))) Assert.True(CallsRemoveNamespaceAttributes(verifier.VisualizeIL("C(Of T).F24()"))) End Sub ''' <summary> ''' Should not call RemoveNamespaceAttributes ''' unless there are xmlns Imports in scope. ''' </summary> <WorkItem(546191, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546191")> <Fact()> Public Sub RemoveNamespaceAttributes_XmlnsInScope() ' No xmlns. Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"><![CDATA[ Imports System.Xml.Linq Module M Function F1() As XElement Return <x><%= F2() %></x> End Function Function F2() As XElement Return <y/> End Function End Module ]]></file> </compilation>, references:=Net40XmlReferences) Assert.False(CallsRemoveNamespaceAttributes(verifier.VisualizeIL("M.F1()"))) ' xmlns attribute. verifier = CompileAndVerify( <compilation> <file name="a.vb"><![CDATA[ Imports System.Xml.Linq Module M Function F1() As XElement Return <x xmlns:p="http://roslyn"><%= F2() %></x> End Function Function F2() As XElement Return <y/> End Function End Module ]]></file> </compilation>, references:=Net40XmlReferences) Assert.False(CallsRemoveNamespaceAttributes(verifier.VisualizeIL("M.F1()"))) ' Imports <...> in file. verifier = CompileAndVerify( <compilation> <file name="a.vb"><![CDATA[ Imports System.Xml.Linq Imports <xmlns:p="http://roslyn"> Module M Function F1() As XElement Return <x><%= F2() %></x> End Function Function F2() As XElement Return <y/> End Function End Module ]]></file> </compilation>, references:=Net40XmlReferences) Assert.True(CallsRemoveNamespaceAttributes(verifier.VisualizeIL("M.F1()"))) ' Imports <...> at project scope. Dim options = TestOptions.ReleaseDll.WithGlobalImports(GlobalImport.Parse({"<xmlns:p=""http://roslyn"">"})) verifier = CompileAndVerify( <compilation> <file name="c.vb"><![CDATA[ Imports System.Xml.Linq Module M Function F1() As XElement Return <x><%= F2() %></x> End Function Function F2() As XElement Return <y/> End Function End Module ]]></file> </compilation>, references:=Net40XmlReferences, options:=options) Assert.True(CallsRemoveNamespaceAttributes(verifier.VisualizeIL("M.F1()"))) End Sub Private Function CallsRemoveNamespaceAttributes(actualIL As String) As Boolean Return actualIL.Contains("My.InternalXmlHelper.RemoveNamespaceAttributes") End Function <WorkItem(546480, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546480")> <Fact()> Public Sub OpenCloseTag() Dim compilation = CompileAndVerify( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports System.Linq Imports System.Xml.Linq Module M Sub Main() Report(<x/>) Report(<x></>) Report(<x> </>) Report(<x> </>) Report(<x><!-- --></>) Report(<x> <!----> <!----> </>) Report(<x> <y/> </>) End Sub Sub Report(x As XElement) System.Console.WriteLine("[{0}] {1}", x.Nodes.Count(), x) End Sub End Module ]]></file> </compilation>, references:=Net40XmlReferences, expectedOutput:=<![CDATA[ [0] <x /> [0] <x></x> [0] <x></x> [0] <x></x> [1] <x> <!-- --> </x> [2] <x> <!----> <!----> </x> [1] <x> <y /> </x> ]]>) End Sub <Fact(), WorkItem(530882, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530882")> Public Sub SelectFromIEnumerableOfXElementMultitargetingNetFX35() Dim source = <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports System Imports System.Linq Imports System.Xml.Linq Module Module1 Dim stuff As XElement = <root> <output someattrib="goo1"> <value>1</value> </output> <output> <value>2</value> </output> </root> Sub Main() For Each value In stuff.<output>.<value> Console.WriteLine(value.Value) Next dim stuffArray() as XElement = {stuff, stuff} for each value in stuffArray.<output> Console.WriteLine(value.Value) next Console.WriteLine(stuff.<output>.@someattrib) End Sub End Module]]> </file> </compilation> Dim comp = CreateEmptyCompilationWithReferences( source, references:={MscorlibRef_v20, SystemRef_v20, MsvbRef, SystemXmlRef, SystemXmlLinqRef, SystemCoreRef}, options:=TestOptions.ReleaseExe.WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default)) CompileAndVerify(comp, expectedOutput:="1" & Environment.NewLine & "2" & Environment.NewLine & "1" & Environment.NewLine & "2" & Environment.NewLine & "1" & Environment.NewLine & "2" & Environment.NewLine & "goo1") End Sub <Fact(), WorkItem(530882, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530882")> Public Sub SelectFromIEnumerableOfXElementMultitargetingNetFX35_Errors() Dim source = <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports System Module Module1 Sub Main() Dim objArray() As Object = {New Object(), New Object()} For Each value In objArray.<output> Next Console.WriteLine(objArray.@someAttrib) End Sub End Module ]]></file> </compilation> Dim comp = CreateEmptyCompilationWithReferences( source, references:={MscorlibRef_v20, SystemRef_v20, MsvbRef, SystemXmlRef, SystemXmlLinqRef, SystemCoreRef}, options:=TestOptions.ReleaseExe.WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default)) VerifyDiagnostics(comp, Diagnostic(ERRID.ERR_TypeDisallowsElements, "objArray.<output>").WithArguments("Object()"), Diagnostic(ERRID.ERR_TypeDisallowsAttributes, "objArray.@someAttrib").WithArguments("Object()")) End Sub <Fact(), WorkItem(531351, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531351")> Public Sub Bug17985() Dim compilation = CompileAndVerify( <compilation> <file name="c.vb"><![CDATA[ Imports System.Xml.Linq Class scen1(Of T As XElement) Sub goo(ByVal o As T) Dim res = o.<moo> End Sub End Class ]]></file> </compilation>, references:=Net40XmlReferences, options:=TestOptions.ReleaseDll). VerifyIL("scen1(Of T).goo(T)", <![CDATA[ { // Code size 30 (0x1e) .maxstack 3 IL_0000: ldarga.s V_1 IL_0002: ldstr "moo" IL_0007: ldstr "" IL_000c: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0011: constrained. "T" IL_0017: callvirt "Function System.Xml.Linq.XContainer.Elements(System.Xml.Linq.XName) As System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)" IL_001c: pop IL_001d: ret } ]]>) End Sub <WorkItem(531445, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531445")> <WorkItem(101597, "https://devdiv.visualstudio.com/defaultcollection/DevDiv/_workitems#_a=edit&id=101597")> <Fact> Public Sub SameNamespaceDifferentPrefixes() Dim options = TestOptions.ReleaseExe.WithGlobalImports(GlobalImport.Parse({"<xmlns:r=""http://roslyn/"">", "<xmlns:s=""http://roslyn/"">"})) Dim expectedOutput As Xml.Linq.XCData Const bug101597IsFixed = False If bug101597IsFixed Then expectedOutput = <![CDATA[ <p:x xmlns:s="http://roslyn/" xmlns:r="http://roslyn/" xmlns:q="http://roslyn/" xmlns:p="http://roslyn/"> <p:y p:a="" p:b="" /> </p:x> ]]> Else expectedOutput = <![CDATA[ <q:x xmlns:p="http://roslyn/" xmlns:s="http://roslyn/" xmlns:r="http://roslyn/" xmlns:q="http://roslyn/"> <q:y q:a="" q:b="" /> </q:x> ]]> End If Dim compilation = CompileAndVerify( <compilation> <file name="a.vb"><![CDATA[ Imports <xmlns:p="http://roslyn/"> Imports <xmlns:q="http://roslyn/"> Module M Sub Main() Dim x = <p:x> <%= <q:y r:a="" s:b=""/> %> </p:x> System.Console.WriteLine("{0}", x) End Sub End Module ]]></file> </compilation>, references:=Net40XmlReferences, options:=options, expectedOutput:=expectedOutput) End Sub <WorkItem(623035, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/623035")> <Fact()> Public Sub Bug623035() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="a.vb"><![CDATA[ Friend Module Program Sub Main() Dim o2 As Object = "E" o2 = System.Xml.Linq.XName.Get("HELLO") Dim y2 = <<%= o2 %>></> System.Console.WriteLine(y2) End Sub End Module ]]></file> </compilation>, Net40XmlReferences, TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.Off)) CompileAndVerify(compilation, <![CDATA[ <HELLO></HELLO> ]]>) compilation = compilation.WithOptions(compilation.Options.WithOptionStrict(OptionStrict.Custom)) CompileAndVerify(compilation, <![CDATA[ <HELLO></HELLO> ]]>) compilation = compilation.WithOptions(compilation.Options.WithOptionStrict(OptionStrict.On)) AssertTheseDiagnostics(compilation, <expected><![CDATA[ BC30518: Overload resolution failed because no accessible 'New' can be called with these arguments: 'Public Overloads Sub New(name As XName)': Option Strict On disallows implicit conversions from 'Object' to 'XName'. 'Public Overloads Sub New(other As XElement)': Option Strict On disallows implicit conversions from 'Object' to 'XElement'. 'Public Overloads Sub New(other As XStreamingElement)': Option Strict On disallows implicit conversions from 'Object' to 'XStreamingElement'. Dim y2 = <<%= o2 %>></> ~~~~~~~~~ ]]></expected>) End Sub <WorkItem(631047, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/631047")> <Fact()> Public Sub Regress631047() CompileAndVerify( <compilation> <file name="a.vb"> <![CDATA[ Imports System Module Program Sub Main() Console.Write(<?goo                       ?>.ToString() = "<?goo                       ?>") End Sub End Module ]]> </file> </compilation>, references:=Net40XmlReferences, expectedOutput:=<![CDATA[True]]>) End Sub <WorkItem(814075, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/814075")> <Fact()> Public Sub ExpressionTreeContainingExtensionProperty() Dim compilation = CompileAndVerify( <compilation> <file name="c.vb"><![CDATA[ Imports System Imports System.Linq.Expressions Imports System.Xml.Linq Module M Sub Main() M(Function(x) x.<y>.Value) End Sub Sub M(e As Expression(Of Func(Of XElement, String))) Console.WriteLine(e) Dim c = e.Compile() Dim s = c.Invoke(<x><y>content</></>) Console.WriteLine(s) End Sub End Module ]]></file> </compilation>, references:=Net40XmlReferences, expectedOutput:=<![CDATA[ x => get_Value(x.Elements(Get("y", ""))) content ]]>) compilation.VerifyIL("M.Main", <![CDATA[ { // Code size 175 (0xaf) .maxstack 17 .locals init (System.Linq.Expressions.ParameterExpression V_0) IL_0000: ldtoken "System.Xml.Linq.XElement" IL_0005: call "Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type" IL_000a: ldstr "x" IL_000f: call "Function System.Linq.Expressions.Expression.Parameter(System.Type, String) As System.Linq.Expressions.ParameterExpression" IL_0014: stloc.0 IL_0015: ldnull IL_0016: ldtoken "Function My.InternalXmlHelper.get_Value(System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)) As String" IL_001b: call "Function System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle) As System.Reflection.MethodBase" IL_0020: castclass "System.Reflection.MethodInfo" IL_0025: ldc.i4.1 IL_0026: newarr "System.Linq.Expressions.Expression" IL_002b: dup IL_002c: ldc.i4.0 IL_002d: ldloc.0 IL_002e: ldtoken "Function System.Xml.Linq.XContainer.Elements(System.Xml.Linq.XName) As System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)" IL_0033: call "Function System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle) As System.Reflection.MethodBase" IL_0038: castclass "System.Reflection.MethodInfo" IL_003d: ldc.i4.1 IL_003e: newarr "System.Linq.Expressions.Expression" IL_0043: dup IL_0044: ldc.i4.0 IL_0045: ldnull IL_0046: ldtoken "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_004b: call "Function System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle) As System.Reflection.MethodBase" IL_0050: castclass "System.Reflection.MethodInfo" IL_0055: ldc.i4.2 IL_0056: newarr "System.Linq.Expressions.Expression" IL_005b: dup IL_005c: ldc.i4.0 IL_005d: ldstr "y" IL_0062: ldtoken "String" IL_0067: call "Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type" IL_006c: call "Function System.Linq.Expressions.Expression.Constant(Object, System.Type) As System.Linq.Expressions.ConstantExpression" IL_0071: stelem.ref IL_0072: dup IL_0073: ldc.i4.1 IL_0074: ldstr "" IL_0079: ldtoken "String" IL_007e: call "Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type" IL_0083: call "Function System.Linq.Expressions.Expression.Constant(Object, System.Type) As System.Linq.Expressions.ConstantExpression" IL_0088: stelem.ref IL_0089: call "Function System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, ParamArray System.Linq.Expressions.Expression()) As System.Linq.Expressions.MethodCallExpression" IL_008e: stelem.ref IL_008f: call "Function System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, ParamArray System.Linq.Expressions.Expression()) As System.Linq.Expressions.MethodCallExpression" IL_0094: stelem.ref IL_0095: call "Function System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, ParamArray System.Linq.Expressions.Expression()) As System.Linq.Expressions.MethodCallExpression" IL_009a: ldc.i4.1 IL_009b: newarr "System.Linq.Expressions.ParameterExpression" IL_00a0: dup IL_00a1: ldc.i4.0 IL_00a2: ldloc.0 IL_00a3: stelem.ref IL_00a4: call "Function System.Linq.Expressions.Expression.Lambda(Of System.Func(Of System.Xml.Linq.XElement, String))(System.Linq.Expressions.Expression, ParamArray System.Linq.Expressions.ParameterExpression()) As System.Linq.Expressions.Expression(Of System.Func(Of System.Xml.Linq.XElement, String))" IL_00a9: call "Sub M.M(System.Linq.Expressions.Expression(Of System.Func(Of System.Xml.Linq.XElement, String)))" IL_00ae: ret } ]]>) End Sub <WorkItem(814052, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/814052")> <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub XmlnsNamespaceTooLong() Dim identifier = New String("a"c, MetadataWriter.PdbLengthLimit) XmlnsNamespaceTooLongCore(identifier.Substring(6), tooLong:=False) XmlnsNamespaceTooLongCore(identifier, tooLong:=True) End Sub Private Sub XmlnsNamespaceTooLongCore(identifier As String, tooLong As Boolean) Dim [imports] = GlobalImport.Parse({String.Format("<xmlns:p=""{0}"">", identifier)}) Dim options = TestOptions.DebugDll.WithGlobalImports([imports]) Dim source = String.Format(<![CDATA[ Imports <xmlns="{0}"> Imports <xmlns:q="{0}"> Module M Private F As Object = <x xmlns="{0}" xmlns:r="{0}" p:a="{0}" q:b="" /> End Module ]]>.Value, identifier) Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation><file name="c.vb"><%= source %></file></compilation>, references:=Net40XmlReferences, options:=options) If Not tooLong Then compilation.AssertTheseDiagnostics(<errors/>) compilation.AssertTheseEmitDiagnostics(<errors/>) Else Dim squiggles = New String("~"c, identifier.Length) Dim errors = String.Format(<![CDATA[ BC42374: Import string '@FX:={0}' is too long for PDB. Consider shortening or compiling without /debug. Module M ~ BC42374: Import string '@FX:q={0}' is too long for PDB. Consider shortening or compiling without /debug. Module M ~ BC42374: Import string '@PX:p={0}' is too long for PDB. Consider shortening or compiling without /debug. Module M ~ ]]>.Value, identifier) compilation.AssertTheseDiagnostics(<errors/>) compilation.AssertTheseEmitDiagnostics(<errors><%= errors %></errors>) End If End Sub ''' <summary> ''' Constant embedded expression with duplicate xmlns attribute. ''' </summary> <WorkItem(863159, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/863159")> <Fact()> Public Sub XmlnsPrefixUsedInEmbeddedExpressionAndSibling_Constant() CompileAndVerify( <compilation> <file name="a.vb"><![CDATA[ Imports <xmlns:p="http://roslyn/"> Module M Sub Main() Dim x = <x> <y> <%= <p:z/> %> </y> <p:z/> </x> System.Console.WriteLine("{0}", x) End Sub End Module ]]></file> </compilation>, references:=Net40XmlReferences, expectedOutput:=<![CDATA[ <x xmlns:p="http://roslyn/"> <y> <p:z /> </y> <p:z /> </x> ]]>) End Sub ''' <summary> ''' Non-constant embedded expression with duplicate xmlns attribute. ''' </summary> <WorkItem(863159, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/863159")> <Fact()> Public Sub XmlnsPrefixUsedInEmbeddedExpressionAndSibling_NonConstant() ' Dev12 generates code that throws "InvalidOperationException: Duplicate attribute". Dim compilation = CompileAndVerify( <compilation> <file name="a.vb"><![CDATA[ Imports <xmlns:p="http://roslyn/p"> Imports <xmlns:q="http://roslyn/q"> Imports <xmlns:r="http://roslyn/r"> Class A Friend Shared Function F() As System.Xml.Linq.XElement Return <a> <p:x/> <q:y/> <r:z/> </> End Function End Class ]]></file> <file name="b.vb"><![CDATA[ Imports <xmlns:p="http://roslyn/q"> Imports <xmlns:q="http://roslyn/p"> Class B Friend Shared Function F() As System.Xml.Linq.XElement Return <b> <p:x/> <q:y/> </> End Function End Class ]]></file> <file name="c.vb"><![CDATA[ Imports System Imports <xmlns:p="http://roslyn/p"> Imports <xmlns:q="http://roslyn/q"> Class C Shared Sub Main() Console.WriteLine(<x> <y> <%= A.F() %> </> <z> <%= B.F() %> </> </>) Console.WriteLine(<x> <y> <%= A.F() %> <%= B.F() %> </> <p:z> <%= A.F() %> <%= B.F() %> </> </>) Console.WriteLine(<x> <p:y> <%= A.F() %> <%= B.F() %> </> <z> <%= A.F() %> <%= B.F() %> </> </>) Console.WriteLine(<x> <p:y> <%= A.F() %> <%= B.F() %> </> <q:z> <%= A.F() %> <%= B.F() %> </> </>) Console.WriteLine(<x> <p:y> <%= B.F() %> <%= A.F() %> </> <q:z xmlns:q="http://roslyn/q"> <%= A.F() %> <%= B.F() %> </> </>) Console.WriteLine(<x xmlns:q="http://roslyn/q"> <p:y xmlns:p="http://roslyn/p"> <%= B.F() %> <%= A.F() %> </> <z> <%= A.F() %> <%= B.F() %> </> </>) Console.WriteLine(<x> <p:y xmlns:p="http://roslyn/p"> <%= B.F() %> <%= A.F() %> </> <q:z> <%= A.F() %> <%= B.F() %> </> </>) End Sub End Class ]]></file> </compilation>, references:=Net40XmlReferences, expectedOutput:=<![CDATA[ <x xmlns:r="http://roslyn/r" xmlns:q="http://roslyn/q" xmlns:p="http://roslyn/p"> <y> <a> <p:x /> <q:y /> <r:z /> </a> </y> <z> <b xmlns:q="http://roslyn/p" xmlns:p="http://roslyn/q"> <p:x /> <q:y /> </b> </z> </x> <x xmlns:p="http://roslyn/p" xmlns:r="http://roslyn/r" xmlns:q="http://roslyn/q"> <y> <a> <p:x /> <q:y /> <r:z /> </a> <b xmlns:q="http://roslyn/p" xmlns:p="http://roslyn/q"> <p:x /> <q:y /> </b> </y> <p:z> <a> <p:x /> <q:y /> <r:z /> </a> <b xmlns:q="http://roslyn/p" xmlns:p="http://roslyn/q"> <p:x /> <q:y /> </b> </p:z> </x> <x xmlns:p="http://roslyn/p" xmlns:r="http://roslyn/r" xmlns:q="http://roslyn/q"> <p:y> <a> <p:x /> <q:y /> <r:z /> </a> <b xmlns:q="http://roslyn/p" xmlns:p="http://roslyn/q"> <p:x /> <q:y /> </b> </p:y> <z> <a> <p:x /> <q:y /> <r:z /> </a> <b xmlns:q="http://roslyn/p" xmlns:p="http://roslyn/q"> <p:x /> <q:y /> </b> </z> </x> <x xmlns:q="http://roslyn/q" xmlns:p="http://roslyn/p" xmlns:r="http://roslyn/r"> <p:y> <a> <p:x /> <q:y /> <r:z /> </a> <b xmlns:q="http://roslyn/p" xmlns:p="http://roslyn/q"> <p:x /> <q:y /> </b> </p:y> <q:z> <a> <p:x /> <q:y /> <r:z /> </a> <b xmlns:q="http://roslyn/p" xmlns:p="http://roslyn/q"> <p:x /> <q:y /> </b> </q:z> </x> <x xmlns:q="http://roslyn/q" xmlns:p="http://roslyn/p" xmlns:r="http://roslyn/r"> <p:y> <b xmlns:q="http://roslyn/p" xmlns:p="http://roslyn/q"> <p:x /> <q:y /> </b> <a> <p:x /> <q:y /> <r:z /> </a> </p:y> <q:z> <a> <p:x /> <q:y /> <r:z /> </a> <b xmlns:q="http://roslyn/p" xmlns:p="http://roslyn/q"> <p:x /> <q:y /> </b> </q:z> </x> <x xmlns:p="http://roslyn/p" xmlns:q="http://roslyn/q" xmlns:r="http://roslyn/r"> <p:y> <b xmlns:q="http://roslyn/p" xmlns:p="http://roslyn/q"> <p:x /> <q:y /> </b> <a> <p:x /> <q:y /> <r:z /> </a> </p:y> <z> <a> <p:x /> <q:y /> <r:z /> </a> <b xmlns:q="http://roslyn/p" xmlns:p="http://roslyn/q"> <p:x /> <q:y /> </b> </z> </x> <x xmlns:q="http://roslyn/q" xmlns:p="http://roslyn/p" xmlns:r="http://roslyn/r"> <p:y> <b xmlns:q="http://roslyn/p" xmlns:p="http://roslyn/q"> <p:x /> <q:y /> </b> <a> <p:x /> <q:y /> <r:z /> </a> </p:y> <q:z> <a> <p:x /> <q:y /> <r:z /> </a> <b xmlns:q="http://roslyn/p" xmlns:p="http://roslyn/q"> <p:x /> <q:y /> </b> </q:z> </x> ]]>) End Sub <WorkItem(863159, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/863159")> <Fact()> Public Sub XmlnsPrefixUsedInEmbeddedExpressionAndSibling_ExpressionTree() CompileAndVerify( <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Linq.Expressions Imports System.Xml.Linq Imports <xmlns:p="http://roslyn/p"> Module M Function F() As XElement Return <p:z/> End Function Sub Main() Dim e As Expression(Of Func(Of Object)) = Function() <x xmlns:q="http://roslyn/q"> <y> <%= F() %> </y> <p:z/> </x> Dim c = e.Compile() Console.WriteLine(c()) End Sub End Module ]]></file> </compilation>, references:=Net40XmlReferences, expectedOutput:=<![CDATA[ <x xmlns:q="http://roslyn/q" xmlns:p="http://roslyn/p"> <y> <p:z /> </y> <p:z /> </x> ]]>) End Sub ''' <summary> ''' Should not traverse into embedded expressions ''' to determine set of used Imports. ''' </summary> <Fact()> Public Sub XmlnsPrefix_UnusedExpression() CompileAndVerify( <compilation> <file name="a.vb"><![CDATA[ Imports <xmlns:p="http://roslyn/p"> Imports <xmlns:q="http://roslyn/q"> Imports <xmlns:r="http://roslyn/r"> Imports System Imports System.Xml.Linq Module M Function F(x As XElement) As XElement Console.WriteLine(x) Return <r:z/> End Function Sub Main() Dim x = <p:x> <%= F(<q:y/>) %> </p:x> Console.WriteLine(x) End Sub End Module ]]></file> </compilation>, references:=Net40XmlReferences, expectedOutput:=<![CDATA[ <q:y xmlns:q="http://roslyn/q" /> <p:x xmlns:p="http://roslyn/p" xmlns:r="http://roslyn/r"> <r:z /> </p:x> ]]>) End Sub ''' <summary> ''' My.InternalXmlHelper should be emitted into the root namespace. ''' </summary> <Fact()> Public Sub InternalXmlHelper_RootNamespace() Const source = " Imports System Imports System.Xml.Linq Class C Sub M() Dim a = <element attr='value'/>.@attr End Sub End Class " Dim tree = VisualBasicSyntaxTree.ParseText(source) Dim refBuilder = ArrayBuilder(Of MetadataReference).GetInstance() refBuilder.Add(TestMetadata.Net40.mscorlib) refBuilder.Add(TestMetadata.Net40.System) refBuilder.Add(TestMetadata.Net40.MicrosoftVisualBasic) refBuilder.AddRange(Net40XmlReferences) Dim refs = refBuilder.ToImmutableAndFree() CompileAndVerify( CreateEmptyCompilationWithReferences(tree, refs, TestOptions.DebugDll), symbolValidator:= Sub(moduleSymbol) moduleSymbol.GlobalNamespace. GetMember(Of NamespaceSymbol)("My"). GetMember(Of NamedTypeSymbol)("InternalXmlHelper") End Sub) CompileAndVerify( CreateEmptyCompilationWithReferences(tree, refs, TestOptions.DebugDll.WithRootNamespace("Root")), symbolValidator:= Sub(moduleSymbol) moduleSymbol.GlobalNamespace. GetMember(Of NamespaceSymbol)("Root"). GetMember(Of NamespaceSymbol)("My"). GetMember(Of NamedTypeSymbol)("InternalXmlHelper") End Sub) End Sub End Class End Namespace
' 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.IO Imports System.Text Imports Microsoft.Cci Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class XmlLiteralTests Inherits BasicTestBase <Fact()> Public Sub XComment() Dim compilation = CompileAndVerify( <compilation> <file name="c.vb"><![CDATA[ Module M Private F = <!-- comment --> Sub Main() System.Console.WriteLine("{0}", F) End Sub End Module ]]></file> </compilation>, references:=Net40XmlReferences, expectedOutput:=<![CDATA[ <!-- comment --> ]]>) compilation.VerifyIL("M..cctor", <![CDATA[ { // Code size 16 (0x10) .maxstack 1 IL_0000: ldstr " comment " IL_0005: newobj "Sub System.Xml.Linq.XComment..ctor(String)" IL_000a: stsfld "M.F As Object" IL_000f: ret } ]]>) End Sub <Fact()> Public Sub XDocument() Dim compilation = CompileAndVerify( <compilation> <file name="c.vb"><![CDATA[ Module M Sub Main() Dim x = <?xml version="1.0"?> <!-- A --> <?p?> <x> <!-- B --> <?q?> </x> <?r?> <!-- C--> Report(x) Report(x.Declaration) End Sub Sub Report(o As Object) System.Console.WriteLine("{0}", o) End Sub End Module ]]></file> </compilation>, references:=XmlReferences, expectedOutput:=<![CDATA[ <!-- A --> <?p?> <x> <!-- B --> <?q?> </x> <?r?> <!-- C--> <?xml version="1.0"?> ]]>) compilation.VerifyIL("M.Main", <![CDATA[ { // Code size 172 (0xac) .maxstack 6 IL_0000: ldstr "1.0" IL_0005: ldnull IL_0006: ldnull IL_0007: newobj "Sub System.Xml.Linq.XDeclaration..ctor(String, String, String)" IL_000c: ldnull IL_000d: newobj "Sub System.Xml.Linq.XDocument..ctor(System.Xml.Linq.XDeclaration, ParamArray Object())" IL_0012: dup IL_0013: ldstr " A " IL_0018: newobj "Sub System.Xml.Linq.XComment..ctor(String)" IL_001d: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_0022: dup IL_0023: ldstr "p" IL_0028: ldstr "" IL_002d: newobj "Sub System.Xml.Linq.XProcessingInstruction..ctor(String, String)" IL_0032: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_0037: dup IL_0038: ldstr "x" IL_003d: ldstr "" IL_0042: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0047: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_004c: dup IL_004d: ldstr " B " IL_0052: newobj "Sub System.Xml.Linq.XComment..ctor(String)" IL_0057: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_005c: dup IL_005d: ldstr "q" IL_0062: ldstr "" IL_0067: newobj "Sub System.Xml.Linq.XProcessingInstruction..ctor(String, String)" IL_006c: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_0071: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_0076: dup IL_0077: ldstr "r" IL_007c: ldstr "" IL_0081: newobj "Sub System.Xml.Linq.XProcessingInstruction..ctor(String, String)" IL_0086: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_008b: dup IL_008c: ldstr " C" IL_0091: newobj "Sub System.Xml.Linq.XComment..ctor(String)" IL_0096: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_009b: dup IL_009c: call "Sub M.Report(Object)" IL_00a1: callvirt "Function System.Xml.Linq.XDocument.get_Declaration() As System.Xml.Linq.XDeclaration" IL_00a6: call "Sub M.Report(Object)" IL_00ab: ret } ]]>) End Sub <Fact()> Public Sub AttributeNamespace() Dim compilation = CompileAndVerify( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports System Imports System.Linq Imports System.Xml.Linq Imports <xmlns="http://roslyn/default1"> Class C Private Shared F1 As XElement = <x a="1"/> Private Shared F2 As XElement = <x xmlns="http://roslyn/default2" a="2"/> Private Shared F4 As XElement = <p:x xmlns:p="http://roslyn/p4" a="4"/> Private Shared F5 As XElement = <x xmlns="http://roslyn/default5" xmlns:p="http://roslyn/p5" p:a="5"/> Shared Sub Main() Report(F0) Report(F1) Report(F2) Report(F3) Report(F4) Report(F5) End Sub Shared Sub Report(x As XElement) Console.WriteLine("{0}", x) Dim a = x.Attributes().First(Function(o) o.Name.LocalName = "a") Console.WriteLine("{0}, {1}", x.Name, a.Name) End Sub End Class ]]> </file> <file name="b.vb"><![CDATA[ Option Strict On Imports System.Xml.Linq Partial Class C Private Shared F0 As XElement = <x a="0"/> Private Shared F3 As XElement = <p:x xmlns:p="http://roslyn/p3" a="3"/> End Class ]]> </file> </compilation>, references:=XmlReferences, expectedOutput:=<![CDATA[ <x a="0" /> x, a <x a="1" xmlns="http://roslyn/default1" /> {http://roslyn/default1}x, a <x xmlns="http://roslyn/default2" a="2" /> {http://roslyn/default2}x, a <p:x xmlns:p="http://roslyn/p3" a="3" /> {http://roslyn/p3}x, a <p:x xmlns:p="http://roslyn/p4" a="4" /> {http://roslyn/p4}x, a <x xmlns="http://roslyn/default5" xmlns:p="http://roslyn/p5" p:a="5" /> {http://roslyn/default5}x, {http://roslyn/p5}a ]]>) End Sub <Fact()> Public Sub MemberAccess() Dim compilation = CompileAndVerify( <compilation> <file name="c.vb"><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Imports System.Xml.Linq Imports <xmlns:r1="http://roslyn"> Module M Sub Main() Dim x = <a xmlns:r2="http://roslyn" r1:b="a.b"> <b>1</b> <r2:c>2</r2:c> <c d="c.d">3</c> <b>4</b> <b/> </a> Report(x.<b>) Report(x.<c>) Report(x.<r1:c>) Report(x.@r1:b) Report(x.@xmlns:r2) End Sub Sub Report(x As IEnumerable(Of XElement)) For Each e In x Console.WriteLine("{0}", e.Value) Dim a = e.@d If a IsNot Nothing Then Console.WriteLine(" {0}", a) End If Next End Sub Sub Report(s As String) Console.WriteLine("{0}", s) End Sub End Module ]]></file> </compilation>, references:=XmlReferences, expectedOutput:=<![CDATA[ 1 4 3 c.d 2 a.b http://roslyn ]]>) compilation.VerifyIL("M.Main", <![CDATA[ { // Code size 453 (0x1c5) .maxstack 6 IL_0000: ldstr "a" IL_0005: ldstr "" IL_000a: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_000f: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_0014: dup IL_0015: ldstr "r2" IL_001a: ldstr "http://www.w3.org/2000/xmlns/" IL_001f: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0024: ldstr "http://roslyn" IL_0029: newobj "Sub System.Xml.Linq.XAttribute..ctor(System.Xml.Linq.XName, Object)" IL_002e: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_0033: dup IL_0034: ldstr "b" IL_0039: ldstr "http://roslyn" IL_003e: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0043: ldstr "a.b" IL_0048: newobj "Sub System.Xml.Linq.XAttribute..ctor(System.Xml.Linq.XName, Object)" IL_004d: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_0052: dup IL_0053: ldstr "b" IL_0058: ldstr "" IL_005d: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0062: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_0067: dup IL_0068: ldstr "1" IL_006d: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_0072: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_0077: dup IL_0078: ldstr "c" IL_007d: ldstr "http://roslyn" IL_0082: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0087: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_008c: dup IL_008d: ldstr "2" IL_0092: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_0097: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_009c: dup IL_009d: ldstr "c" IL_00a2: ldstr "" IL_00a7: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_00ac: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_00b1: dup IL_00b2: ldstr "d" IL_00b7: ldstr "" IL_00bc: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_00c1: ldstr "c.d" IL_00c6: newobj "Sub System.Xml.Linq.XAttribute..ctor(System.Xml.Linq.XName, Object)" IL_00cb: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_00d0: dup IL_00d1: ldstr "3" IL_00d6: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_00db: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_00e0: dup IL_00e1: ldstr "b" IL_00e6: ldstr "" IL_00eb: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_00f0: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_00f5: dup IL_00f6: ldstr "4" IL_00fb: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_0100: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_0105: dup IL_0106: ldstr "b" IL_010b: ldstr "" IL_0110: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0115: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_011a: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_011f: dup IL_0120: ldstr "r1" IL_0125: ldstr "http://www.w3.org/2000/xmlns/" IL_012a: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_012f: ldstr "http://roslyn" IL_0134: call "Function System.Xml.Linq.XNamespace.Get(String) As System.Xml.Linq.XNamespace" IL_0139: call "Function My.InternalXmlHelper.CreateNamespaceAttribute(System.Xml.Linq.XName, System.Xml.Linq.XNamespace) As System.Xml.Linq.XAttribute" IL_013e: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_0143: dup IL_0144: ldstr "b" IL_0149: ldstr "" IL_014e: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0153: callvirt "Function System.Xml.Linq.XContainer.Elements(System.Xml.Linq.XName) As System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)" IL_0158: call "Sub M.Report(System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement))" IL_015d: dup IL_015e: ldstr "c" IL_0163: ldstr "" IL_0168: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_016d: callvirt "Function System.Xml.Linq.XContainer.Elements(System.Xml.Linq.XName) As System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)" IL_0172: call "Sub M.Report(System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement))" IL_0177: dup IL_0178: ldstr "c" IL_017d: ldstr "http://roslyn" IL_0182: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0187: callvirt "Function System.Xml.Linq.XContainer.Elements(System.Xml.Linq.XName) As System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)" IL_018c: call "Sub M.Report(System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement))" IL_0191: dup IL_0192: ldstr "b" IL_0197: ldstr "http://roslyn" IL_019c: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_01a1: call "Function My.InternalXmlHelper.get_AttributeValue(System.Xml.Linq.XElement, System.Xml.Linq.XName) As String" IL_01a6: call "Sub M.Report(String)" IL_01ab: ldstr "r2" IL_01b0: ldstr "http://www.w3.org/2000/xmlns/" IL_01b5: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_01ba: call "Function My.InternalXmlHelper.get_AttributeValue(System.Xml.Linq.XElement, System.Xml.Linq.XName) As String" IL_01bf: call "Sub M.Report(String)" IL_01c4: ret } ]]>) End Sub <Fact()> Public Sub MemberAccess_DistinctDefaultNamespaces() Dim compilation = CompileAndVerify( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports System Imports System.Xml.Linq Imports <xmlns:p="http://roslyn/p"> Imports <xmlns:q="http://roslyn/q"> Partial Class C Private Shared F1 As XElement = <x xmlns="http://roslyn/p" a="a1" p:b="b1"/> Private Shared F2 As XElement = <p:x a="a1" q:b="b1"/> Shared Sub Main() Report(F1) Report(F2) Report(F3) Report(F4) End Sub Private Shared Sub Report(x As XElement) Console.WriteLine("{0}", x) Report(x.@<a>) Report(x.@<p:a>) Report(x.@<q:a>) Report(x.@<b>) Report(x.@<p:b>) Report(x.@<q:b>) End Sub Private Shared Sub Report(s As String) Console.WriteLine("{0}", If(s, "[none]")) End Sub End Class ]]></file> <file name="b.vb"><![CDATA[ Option Strict On Imports System.Xml.Linq Imports <xmlns:p1="http://roslyn/p"> Imports <xmlns:p2="http://roslyn/q"> Partial Class C Private Shared F3 As XElement = <x xmlns="http://roslyn/q" a="a2" p1:b="b2"/> Private Shared F4 As XElement = <p1:x a="a2" p2:b="b2"/> End Class ]]></file> </compilation>, references:=XmlReferences, expectedOutput:=<![CDATA[ <p:x xmlns="http://roslyn/p" a="a1" p:b="b1" xmlns:p="http://roslyn/p" /> a1 [none] [none] [none] b1 [none] <p:x a="a1" q:b="b1" xmlns:q="http://roslyn/q" xmlns:p="http://roslyn/p" /> a1 [none] [none] [none] [none] b1 <x xmlns="http://roslyn/q" a="a2" p1:b="b2" xmlns:p1="http://roslyn/p" /> a2 [none] [none] [none] b2 [none] <p1:x a="a2" p2:b="b2" xmlns:p2="http://roslyn/q" xmlns:p1="http://roslyn/p" /> a2 [none] [none] [none] [none] b2 ]]>) End Sub <Fact()> Public Sub MemberAccessXmlns() Dim compilation = CompileAndVerify( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports System Imports System.Linq Module M Sub Main() Console.WriteLine("{0}", <x/>.<xmlns>.Count()) Console.WriteLine("{0}", <x/>.@xmlns) Console.WriteLine("{0}", <x xmlns="http://roslyn/default"/>.@xmlns) Console.WriteLine("{0}", <x xmlns:p="http://roslyn/p"/>.@<xmlns:p>) End Sub End Module ]]></file> </compilation>, references:=XmlReferences, expectedOutput:=<![CDATA[ 0 http://roslyn/default http://roslyn/p ]]>) End Sub <Fact()> Public Sub MemberAccessXmlns_DistinctDefaultNamespaces() Dim compilation = CompileAndVerify( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports System Imports System.Xml.Linq Imports <xmlns="http://roslyn/default1"> Imports <xmlns:default1="http://roslyn/default1"> Imports <xmlns:default2="http://roslyn/default2"> Partial Class C Private Shared F1 As XElement = <x xmlns="http://roslyn/1" xmlns:p="http://roslyn/p"/> Shared Sub Main() Report(F1) Report(F2) End Sub Private Shared Sub Report(x As XElement) Console.WriteLine("{0}", x) Report(x.@<xmlns>) Report(x.@<default1:xmlns>) Report(x.@<default2:xmlns>) End Sub Private Shared Sub Report(s As String) Console.WriteLine("{0}", If(s, "[none]")) End Sub End Class ]]></file> <file name="b.vb"><![CDATA[ Option Strict On Imports System.Xml.Linq Imports <xmlns="http://roslyn/default2"> Partial Class C Private Shared F2 As XElement = <x xmlns="http://roslyn/2" xmlns:q="http://roslyn/q"/> End Class ]]></file> </compilation>, references:=XmlReferences, expectedOutput:=<![CDATA[ <x xmlns="http://roslyn/1" xmlns:p="http://roslyn/p" /> http://roslyn/1 [none] [none] <x xmlns="http://roslyn/2" xmlns:q="http://roslyn/q" /> http://roslyn/2 [none] [none] ]]>) End Sub <Fact()> Public Sub MemberAccessIEnumerableOfXElement() Dim compilation = CompileAndVerify( <compilation> <file name="c.vb"><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Imports System.Xml.Linq Module M Property P1 As XElement = <a><b c="1"/><b c="2"/></a> Property P2 As IEnumerable(Of XElement) = P1.<b> Property P3 As XElement = <a> <b><c>1</c></b> <b><c>2</c></b> </a> Property P4 As IEnumerable(Of XElement) = P3.<b> Sub Main() Report(P1.<b>.@c) Report(P2.@c) Report(P3.<b>.<c>) Report(P4.<c>) End Sub Sub Report(s As String) Console.WriteLine("{0}", s) End Sub Sub Report(c As IEnumerable(Of XElement)) For Each o In c Console.WriteLine("{0}", o) Next End Sub End Module ]]></file> </compilation>, references:=XmlReferences, expectedOutput:=<![CDATA[ 1 1 <c>1</c> <c>2</c> <c>1</c> <c>2</c> ]]>) compilation.VerifyIL("M.Main", <![CDATA[ { // Code size 161 (0xa1) .maxstack 3 IL_0000: call "Function M.get_P1() As System.Xml.Linq.XElement" IL_0005: ldstr "b" IL_000a: ldstr "" IL_000f: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0014: callvirt "Function System.Xml.Linq.XContainer.Elements(System.Xml.Linq.XName) As System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)" IL_0019: ldstr "c" IL_001e: ldstr "" IL_0023: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0028: call "Function My.InternalXmlHelper.get_AttributeValue(System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement), System.Xml.Linq.XName) As String" IL_002d: call "Sub M.Report(String)" IL_0032: call "Function M.get_P2() As System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)" IL_0037: ldstr "c" IL_003c: ldstr "" IL_0041: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0046: call "Function My.InternalXmlHelper.get_AttributeValue(System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement), System.Xml.Linq.XName) As String" IL_004b: call "Sub M.Report(String)" IL_0050: call "Function M.get_P3() As System.Xml.Linq.XElement" IL_0055: ldstr "b" IL_005a: ldstr "" IL_005f: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0064: callvirt "Function System.Xml.Linq.XContainer.Elements(System.Xml.Linq.XName) As System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)" IL_0069: ldstr "c" IL_006e: ldstr "" IL_0073: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0078: call "Function System.Xml.Linq.Extensions.Elements(Of System.Xml.Linq.XElement)(System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement), System.Xml.Linq.XName) As System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)" IL_007d: call "Sub M.Report(System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement))" IL_0082: call "Function M.get_P4() As System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)" IL_0087: ldstr "c" IL_008c: ldstr "" IL_0091: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0096: call "Function System.Xml.Linq.Extensions.Elements(Of System.Xml.Linq.XElement)(System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement), System.Xml.Linq.XName) As System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)" IL_009b: call "Sub M.Report(System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement))" IL_00a0: ret } ]]>) End Sub <Fact()> Public Sub DescendantAccess() Dim compilation = CompileAndVerify( <compilation> <file name="c.vb"><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Xml.Linq Imports <xmlns:p="http://roslyn/p"> Imports <xmlns:q="http://roslyn/q"> Module M Sub Main() M(<a> <c>1</> <b> <q:c>2</> <p3:c xmlns:p3="http://roslyn/p">3</> </b> <b> <c>4</> <p5:c xmlns:p5="http://roslyn/p">5</> </b> </a>) End Sub Sub M(x As XElement) Report(x...<c>) Report(x...<b>...<p:c>) End Sub Sub Report(c As IEnumerable(Of XElement)) For Each x In c Console.WriteLine("{0}", x) Next End Sub End Module ]]></file> </compilation>, references:=XmlReferences, expectedOutput:=<![CDATA[ <c>1</c> <c>4</c> <p3:c xmlns:p3="http://roslyn/p">3</p3:c> <p5:c xmlns:p5="http://roslyn/p">5</p5:c> ]]>) compilation.VerifyIL("M.M", <![CDATA[ { // Code size 73 (0x49) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldstr "c" IL_0006: ldstr "" IL_000b: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0010: callvirt "Function System.Xml.Linq.XContainer.Descendants(System.Xml.Linq.XName) As System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)" IL_0015: call "Sub M.Report(System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement))" IL_001a: ldarg.0 IL_001b: ldstr "b" IL_0020: ldstr "" IL_0025: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_002a: callvirt "Function System.Xml.Linq.XContainer.Descendants(System.Xml.Linq.XName) As System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)" IL_002f: ldstr "c" IL_0034: ldstr "http://roslyn/p" IL_0039: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_003e: call "Function System.Xml.Linq.Extensions.Descendants(Of System.Xml.Linq.XElement)(System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement), System.Xml.Linq.XName) As System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)" IL_0043: call "Sub M.Report(System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement))" IL_0048: ret } ]]>) End Sub <Fact()> Public Sub MemberAccessReceiverNotRValue() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports System.Xml.Linq Module M ReadOnly Property P As XElement Get Return Nothing End Get End Property WriteOnly Property Q As XElement Set(value As XElement) End Set End Property Sub M() Dim o As Object o = P.<x> o = P.@x o = Q.<x> o = Q.@x With P o = ...<x> .@<a> = "b" End With With Q o = ...<y> .@<c> = "d" End With End Sub End Module ]]></file> </compilation>, references:=XmlReferences) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC30524: Property 'Q' is 'WriteOnly'. o = Q.<x> ~ BC30524: Property 'Q' is 'WriteOnly'. o = Q.@x ~ BC30524: Property 'Q' is 'WriteOnly'. With Q ~ ]]></errors>) End Sub ' Should not report cascading member access errors ' if the receiver is an error type. <Fact()> Public Sub MemberAccessUnknownReceiver() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Module M Sub M() Dim x As C = Nothing Dim y As Object y = x.<y> y = x...<y> y = x.@a End Sub End Module ]]></file> </compilation>, references:=XmlReferences) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC30002: Type 'C' is not defined. Dim x As C = Nothing ~ ]]></errors>) End Sub <Fact()> Public Sub MemberAccessUntypedReceiver() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Module M Sub M() Dim o As Object o = Nothing.<x> o = Nothing.@a o = (Function() Nothing)...<x> o = (Function() Nothing).@<a> With Nothing o = .<x> End With With (Function() Nothing) .@a = "b" End With End Sub End Module ]]></file> </compilation>, references:=XmlReferences) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC31168: XML axis properties do not support late binding. o = Nothing.<x> ~~~~~~~~~~~ BC31168: XML axis properties do not support late binding. o = Nothing.@a ~~~~~~~~~~ BC36809: XML descendant elements cannot be selected from type 'Function <generated method>() As Object'. o = (Function() Nothing)...<x> ~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36808: XML attributes cannot be selected from type 'Function <generated method>() As Object'. o = (Function() Nothing).@<a> ~~~~~~~~~~~~~~~~~~~~~~~~~ BC31168: XML axis properties do not support late binding. o = .<x> ~~~~ BC36808: XML attributes cannot be selected from type 'Function <generated method>() As Object'. .@a = "b" ~~~ ]]></errors>) End Sub <Fact()> Public Sub MemberAccessImplicitReceiver() Dim compilation = CompileAndVerify( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports System Imports System.Collections.Generic Imports System.Linq Imports System.Xml.Linq Module M Function F1(x As XElement) As IEnumerable(Of XElement) With x Return .<y> End With End Function Function F2(x As XElement) As IEnumerable(Of XElement) With x Return ...<y> End With End Function Function F3(x As XElement) As Object With x Return .@a End With End Function Function F4(x As XElement) As Object With x .@<b> = .@<a> End With Return x End Function Sub Main() Console.WriteLine("{0}", F1(<x1><y/></x1>).FirstOrDefault()) Console.WriteLine("{0}", F2(<x2><y/></x2>).FirstOrDefault()) Console.WriteLine("{0}", F3(<x3 a="1"/>)) Console.WriteLine("{0}", F4(<x4 a="2"/>)) End Sub End Module ]]></file> </compilation>, references:=XmlReferences, expectedOutput:=<![CDATA[ <y /> <y /> 1 <x4 a="2" b="2" /> ]]>) End Sub <Fact()> Public Sub MemberAccessImplicitReceiverLambda() Dim compilation = CompileAndVerify( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports System Imports System.Collections Imports System.Collections.Generic Imports System.Linq Imports System.Xml.Linq Class C Implements IEnumerable(Of XElement) Private value As IEnumerable(Of XElement) = {<x a="1"><y/></x>} Public Function F1() As IEnumerable(Of XElement) With Me Return (Function() .<y>)() End With End Function Public Function F2() As IEnumerable(Of XElement) With Me Return (Function() ...<y>)() End With End Function Public Function F3() As Object With Me Return (Function() .@a)() End With End Function Public Function F4() As IEnumerable(Of XElement) With Me Dim a As Action = Sub() .@<b> = .@<a> a() End With Return Me End Function Private Function GetEnumerator() As IEnumerator(Of XElement) Implements IEnumerable(Of XElement).GetEnumerator Return value.GetEnumerator() End Function Private Function GetEnumerator1() As IEnumerator Implements IEnumerable.GetEnumerator Return Nothing End Function End Class Module M Sub Main() Dim o As New C() Console.WriteLine("{0}", o.F1().FirstOrDefault()) Console.WriteLine("{0}", o.F2().FirstOrDefault()) Console.WriteLine("{0}", o.F3()) Console.WriteLine("{0}", o.F4().FirstOrDefault()) End Sub End Module ]]></file> </compilation>, references:=XmlReferences, expectedOutput:=<![CDATA[ <y /> <y /> 1 <x a="1" b="1"> <y /> </x> ]]>) End Sub <Fact()> Public Sub MemberAccessImplicitReceiverLambdaCannotLiftMe() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports System Imports System.Collections Imports System.Collections.Generic Imports System.Xml.Linq Structure S Implements IEnumerable(Of XElement) Public Function F1() As IEnumerable(Of XElement) With Me Return (Function() .<y>)() End With End Function Public Function F2() As IEnumerable(Of XElement) With Me Return (Function() ...<y>)() End With End Function Public Function F3() As Object With Me Return (Function() .@a)() End With End Function Public Function F4() As IEnumerable(Of XElement) With Me Dim a As Action = Sub() .@<b> = .@<a> a() End With Return Me End Function Private Function GetEnumerator() As IEnumerator(Of XElement) Implements IEnumerable(Of XElement).GetEnumerator Return Nothing End Function Private Function GetEnumerator1() As IEnumerator Implements IEnumerable.GetEnumerator Return Nothing End Function End Structure ]]></file> </compilation>, references:=XmlReferences) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC36638: Instance members and 'Me' cannot be used within a lambda expression in structures. Return (Function() .<y>)() ~~~~ BC36638: Instance members and 'Me' cannot be used within a lambda expression in structures. Return (Function() ...<y>)() ~~~~~~ BC36638: Instance members and 'Me' cannot be used within a lambda expression in structures. Return (Function() .@a)() ~~~ BC36638: Instance members and 'Me' cannot be used within a lambda expression in structures. Dim a As Action = Sub() .@<b> = .@<a> ~~~~~ BC36638: Instance members and 'Me' cannot be used within a lambda expression in structures. Dim a As Action = Sub() .@<b> = .@<a> ~~~~~ ]]></errors>) End Sub <Fact()> Public Sub MemberAccessIncludeNamespaces() Dim compilation = CompileAndVerify( <compilation> <file name="c.vb"><![CDATA[ Imports <xmlns:p="http://roslyn"> Module M Sub Main() Dim x = <pa:a xmlns:pa="http://roslyn"> <pb:b xmlns:pb="http://roslyn"/> <pa:c/> <p:d/> </pa:a> Report(x.<p:b>) Report(x.<p:c>) Report(x.<p:d>) End Sub Sub Report(c As System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)) For Each x In c System.Console.WriteLine("{0}", x) Next End Sub End Module ]]></file> </compilation>, references:=XmlReferences, expectedOutput:=<![CDATA[ <pb:b xmlns:pb="http://roslyn" /> <pa:c xmlns:pa="http://roslyn" /> <pa:d xmlns:pa="http://roslyn" /> ]]>) End Sub <Fact()> Public Sub MemberAccessAssignment() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports System.Collections.Generic Imports System.Xml.Linq Module M Sub M() Dim x = <x/> x.<y> = Nothing x.<y>.<z> = Nothing x...<y> = Nothing x...<y>...<z> = Nothing N(x.<y>) N(x.<y>.<z>) N(x...<y>) N(x...<y>...<z>) End Sub Sub N(ByRef o As IEnumerable(Of XElement)) End Sub End Module ]]></file> </compilation>, references:=XmlReferences) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC30068: Expression is a value and therefore cannot be the target of an assignment. x.<y> = Nothing ~~~~~ BC30068: Expression is a value and therefore cannot be the target of an assignment. x.<y>.<z> = Nothing ~~~~~~~~~ BC30068: Expression is a value and therefore cannot be the target of an assignment. x...<y> = Nothing ~~~~~~~ BC30068: Expression is a value and therefore cannot be the target of an assignment. x...<y>...<z> = Nothing ~~~~~~~~~~~~~ ]]></errors>) End Sub <Fact()> Public Sub MemberAccessAttributeAssignment() Dim compilation = CompileAndVerify( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports <xmlns:y="http://roslyn"> Module M Sub Main() Dim x = <x a="1"><y/><y/></x> Report(x) x.@a = "2" x.<y>.@y:b = "3" N(x.@c, "4") N(x.<y>.@y:d, "5") Report(x) End Sub Sub N(ByRef x As String, y As String) x = y End Sub Sub Report(o As Object) System.Console.WriteLine("{0}", o) End Sub End Module ]]></file> </compilation>, references:=XmlReferences, expectedOutput:=<![CDATA[ <x a="1"> <y /> <y /> </x> <x a="2" c="4"> <y p2:b="3" p2:d="5" xmlns:p2="http://roslyn" /> <y /> </x> ]]>) End Sub <Fact()> Public Sub MemberAccessAttributeCompoundAssignment() Dim compilation = CompileAndVerify( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Module M Sub Main() Dim x = <x a="1"/> x.@a += "2" x.@b += "3" System.Console.WriteLine("{0}", x) End Sub End Module ]]> </file> </compilation>, references:=XmlReferences, expectedOutput:=<![CDATA[ <x a="12" b="3" /> ]]>) End Sub <Fact()> Public Sub MemberAccessAttributeAsReceiver() Dim compilation = CompileAndVerify( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Module M Sub Main() System.Console.WriteLine("{0}", <x a="b"/>[email protected]()) System.Console.WriteLine("{0}", <x><y>c</y></x>.<y>.Value) End Sub End Module ]]></file> </compilation>, references:=XmlReferences, expectedOutput:=<![CDATA[ b c ]]>) End Sub <Fact()> Public Sub MemberAccessAttributeByRefExtensionMethod() Dim compilation = CompileAndVerify( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports System.Runtime.CompilerServices Module M Sub Main() Dim x = <x a="1"/> [email protected]("2") System.Console.WriteLine("{0}", x) End Sub <Extension()> Sub M(ByRef x As String, y As String) x = y End Sub End Module ]]> </file> </compilation>, references:=Net40XmlReferences, expectedOutput:=<![CDATA[ <x a="2" /> ]]>) End Sub <Fact()> Public Sub MemberAccessAttributeAddressOf() Dim compilation = CompileAndVerify( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports System Module M Sub Main() Dim d As Func(Of String) = AddressOf <x a="b"/>[email protected] Console.WriteLine("{0}", d()) End Sub End Module ]]> </file> </compilation>, references:=Net40XmlReferences, expectedOutput:="b") End Sub ' Project-level imports should be used if file-level ' imports do not contain namespace. <Fact()> Public Sub ProjectImports() Dim options = TestOptions.ReleaseExe.WithGlobalImports(GlobalImport.Parse({"<xmlns=""default1"">", "<xmlns:p=""p1"">", "<xmlns:q=""q1"">"})) Dim compilation = CompileAndVerify( <compilation> <file name="c.vb"><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Xml.Linq Imports <xmlns:q="q2"> Class C Shared Sub Main() Dim x = <a> <b/> <p:b/> <q:b/> </a> Report(x.<b>) Report(x.<p:b>) Report(x.<q:b>) End Sub Shared Sub Report(c As IEnumerable(Of XElement)) For Each i In c Console.WriteLine(i.Name.Namespace) Next End Sub End Class ]]></file> </compilation>, references:=Net40XmlReferences, options:=options, expectedOutput:=<![CDATA[ default1 p1 q2 ]]>) compilation.VerifyIL("C.Main", <![CDATA[ { // Code size 284 (0x11c) .maxstack 4 IL_0000: ldstr "a" IL_0005: ldstr "default1" IL_000a: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_000f: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_0014: dup IL_0015: ldstr "b" IL_001a: ldstr "default1" IL_001f: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0024: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_0029: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_002e: dup IL_002f: ldstr "b" IL_0034: ldstr "p1" IL_0039: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_003e: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_0043: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_0048: dup IL_0049: ldstr "b" IL_004e: ldstr "q2" IL_0053: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0058: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_005d: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_0062: dup IL_0063: ldstr "q" IL_0068: ldstr "http://www.w3.org/2000/xmlns/" IL_006d: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0072: ldstr "q2" IL_0077: call "Function System.Xml.Linq.XNamespace.Get(String) As System.Xml.Linq.XNamespace" IL_007c: call "Function My.InternalXmlHelper.CreateNamespaceAttribute(System.Xml.Linq.XName, System.Xml.Linq.XNamespace) As System.Xml.Linq.XAttribute" IL_0081: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_0086: dup IL_0087: ldstr "p" IL_008c: ldstr "http://www.w3.org/2000/xmlns/" IL_0091: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0096: ldstr "p1" IL_009b: call "Function System.Xml.Linq.XNamespace.Get(String) As System.Xml.Linq.XNamespace" IL_00a0: call "Function My.InternalXmlHelper.CreateNamespaceAttribute(System.Xml.Linq.XName, System.Xml.Linq.XNamespace) As System.Xml.Linq.XAttribute" IL_00a5: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_00aa: dup IL_00ab: ldstr "xmlns" IL_00b0: ldstr "" IL_00b5: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_00ba: ldstr "default1" IL_00bf: call "Function System.Xml.Linq.XNamespace.Get(String) As System.Xml.Linq.XNamespace" IL_00c4: call "Function My.InternalXmlHelper.CreateNamespaceAttribute(System.Xml.Linq.XName, System.Xml.Linq.XNamespace) As System.Xml.Linq.XAttribute" IL_00c9: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_00ce: dup IL_00cf: ldstr "b" IL_00d4: ldstr "default1" IL_00d9: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_00de: callvirt "Function System.Xml.Linq.XContainer.Elements(System.Xml.Linq.XName) As System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)" IL_00e3: call "Sub C.Report(System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement))" IL_00e8: dup IL_00e9: ldstr "b" IL_00ee: ldstr "p1" IL_00f3: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_00f8: callvirt "Function System.Xml.Linq.XContainer.Elements(System.Xml.Linq.XName) As System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)" IL_00fd: call "Sub C.Report(System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement))" IL_0102: ldstr "b" IL_0107: ldstr "q2" IL_010c: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0111: callvirt "Function System.Xml.Linq.XContainer.Elements(System.Xml.Linq.XName) As System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)" IL_0116: call "Sub C.Report(System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement))" IL_011b: ret } ]]>) End Sub <Fact()> Public Sub ImplicitXmlnsAttributes() Dim options = TestOptions.ReleaseExe.WithGlobalImports(GlobalImport.Parse({"<xmlns=""http://roslyn"">", "<xmlns:p=""http://roslyn/p"">"})) Dim compilation = CompileAndVerify( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports System Imports <xmlns:P="http://roslyn/P"> Imports <xmlns:q="http://roslyn/p"> Module M Private F1 As Object = <x><p:y/></x> Private F2 As Object = <x><p:y/><P:z/></x> Private F3 As Object = <p:x><q:y/></p:x> Sub Main() Console.WriteLine("{0}", F1) Console.WriteLine("{0}", F2) Console.WriteLine("{0}", F3) End Sub End Module ]]></file> </compilation>, references:=Net40XmlReferences, options:=options, expectedOutput:=<![CDATA[ <x xmlns:p="http://roslyn/p" xmlns="http://roslyn"> <p:y /> </x> <x xmlns:P="http://roslyn/P" xmlns:p="http://roslyn/p" xmlns="http://roslyn"> <p:y /> <P:z /> </x> <p:x xmlns:q="http://roslyn/p" xmlns:p="http://roslyn/p"> <p:y /> </p:x> ]]>) End Sub <Fact()> Public Sub ImplicitXmlnsAttributes_DefaultAndEmpty() Dim compilation = CompileAndVerify( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports <xmlns="http://roslyn/default"> Imports <xmlns:p="http://roslyn/p"> Imports <xmlns:q=""> Module M Sub Main() Report(<p:x> <y/> <q:z/> </p:x>) End Sub Sub Report(o As Object) System.Console.WriteLine("{0}", o) End Sub End Module ]]></file> </compilation>, references:=Net40XmlReferences, expectedOutput:=<![CDATA[ <p:x xmlns="http://roslyn/default" xmlns:p="http://roslyn/p"> <y /> <z xmlns="" /> </p:x> ]]>) compilation.VerifyIL("M.Main", <![CDATA[ { // Code size 150 (0x96) .maxstack 4 IL_0000: ldstr "x" IL_0005: ldstr "http://roslyn/p" IL_000a: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_000f: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_0014: dup IL_0015: ldstr "y" IL_001a: ldstr "http://roslyn/default" IL_001f: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0024: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_0029: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_002e: dup IL_002f: ldstr "z" IL_0034: ldstr "" IL_0039: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_003e: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_0043: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_0048: dup IL_0049: ldstr "xmlns" IL_004e: ldstr "" IL_0053: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0058: ldstr "http://roslyn/default" IL_005d: call "Function System.Xml.Linq.XNamespace.Get(String) As System.Xml.Linq.XNamespace" IL_0062: call "Function My.InternalXmlHelper.CreateNamespaceAttribute(System.Xml.Linq.XName, System.Xml.Linq.XNamespace) As System.Xml.Linq.XAttribute" IL_0067: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_006c: dup IL_006d: ldstr "p" IL_0072: ldstr "http://www.w3.org/2000/xmlns/" IL_0077: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_007c: ldstr "http://roslyn/p" IL_0081: call "Function System.Xml.Linq.XNamespace.Get(String) As System.Xml.Linq.XNamespace" IL_0086: call "Function My.InternalXmlHelper.CreateNamespaceAttribute(System.Xml.Linq.XName, System.Xml.Linq.XNamespace) As System.Xml.Linq.XAttribute" IL_008b: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_0090: call "Sub M.Report(Object)" IL_0095: ret } ]]>) End Sub <Fact()> Public Sub ImplicitXmlnsAttributes_EmbeddedExpressions() Dim compilation = CompileAndVerify( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports System Imports <xmlns="http://roslyn/default"> Imports <xmlns:p="http://roslyn/p"> Imports <xmlns:q="http://roslyn/q"> Module M Private F0 As Object = <p:y/> Private F1 As Object = <x><%= <p:y1/> %><%= <p:y2/> %><%= <q:y3/> %></x> Private F2 As Object = <x><%= F0 %></x> Private F3 As Object = <p:x><%= <<%= <q:y/> %>/> %></p:x> Private F4 As Object = <p:x><%= (Function() <y/>)() %></p:x> Sub Main() Console.WriteLine("{0}", F1) Console.WriteLine("{0}", F2) Console.WriteLine("{0}", F3) Console.WriteLine("{0}", F4) End Sub End Module ]]></file> </compilation>, references:=Net40XmlReferences, expectedOutput:=<![CDATA[ <x xmlns="http://roslyn/default" xmlns:p="http://roslyn/p" xmlns:q="http://roslyn/q"> <p:y1 /> <p:y2 /> <q:y3 /> </x> <x xmlns="http://roslyn/default" xmlns:p="http://roslyn/p"> <p:y /> </x> <p:x xmlns:p="http://roslyn/p"> <q:y xmlns:q="http://roslyn/q" /> </p:x> <p:x xmlns:p="http://roslyn/p" xmlns="http://roslyn/default"> <y /> </p:x> ]]>) End Sub <Fact()> Public Sub ImplicitXmlnsAttributes_EmbeddedExpressions_2() Dim compilation = CompileAndVerify( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports System.Xml.Linq Imports <xmlns:p1="http://roslyn/1"> Imports <xmlns:p2="http://roslyn/2"> Module M Sub Main() ' Same xmlns merged from sibling children. Report(<a> <b> <%= F(<c> <p1:d/> </c>) %> </b> <b> <%= F(<c> <p1:d/> <p2:d/> </c>) %> </b> </a>) ' Different xmlns at sibling scopes. Report(<a> <b xmlns:p1="http://roslyn/3"> <%= F(<c> <p1:d/> <p2:d/> </c>) %> </b> <b xmlns:p2="http://roslyn/4"> <%= F(<c> <p1:d/> <p2:d/> </c>) %> </b> </a>) ' Different xmlns at nested scopes. Dev11: "Duplicate attribute" exception. Report(<a xmlns:p1="http://roslyn/3"> <b xmlns:p2="http://roslyn/4"> <%= F(<c> <p1:d/> <p2:d/> </c>) %> </b> </a>) End Sub Function F(x As XElement) As XElement Return x End Function Sub Report(x As XElement) System.Console.WriteLine("{0}", x) End Sub End Module ]]></file> </compilation>, references:=Net40XmlReferences, expectedOutput:=<![CDATA[ <a xmlns:p1="http://roslyn/1" xmlns:p2="http://roslyn/2"> <b> <c> <p1:d /> </c> </b> <b> <c> <p1:d /> <p2:d /> </c> </b> </a> <a xmlns:p2="http://roslyn/2" xmlns:p1="http://roslyn/1"> <b xmlns:p1="http://roslyn/3"> <c xmlns:p1="http://roslyn/1"> <p1:d /> <p2:d /> </c> </b> <b xmlns:p2="http://roslyn/4"> <c xmlns:p2="http://roslyn/2"> <p1:d /> <p2:d /> </c> </b> </a> <a xmlns:p1="http://roslyn/3"> <b xmlns:p2="http://roslyn/4"> <c xmlns:p2="http://roslyn/2" xmlns:p1="http://roslyn/1"> <p1:d /> <p2:d /> </c> </b> </a> ]]>) End Sub ' Embedded expression from separate file with distinct default namespaces. <Fact()> Public Sub ImplicitXmlnsAttributes_DistinctDefaultNamespaces() Dim compilation = CompileAndVerify( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports System Partial Class C Private Shared F1 As Object = <x> <%= E1() %> <%= E2() %> <%= E3() %> </x> Private Shared Function E1() As Object Return <y/> End Function Shared Sub Main() Console.WriteLine("{0}", F1) Console.WriteLine("{0}", F2) Console.WriteLine("{0}", F3) End Sub End Class ]]></file> <file name="b.vb"><![CDATA[ Option Strict On Imports <xmlns="http://roslyn/2"> Partial Class C Private Shared F2 As Object = <x> <%= E1() %> <%= E2() %> <%= E3() %> </x> Private Shared Function E2() As Object Return <y/> End Function End Class ]]></file> <file name="c.vb"><![CDATA[ Option Strict On Imports <xmlns="http://roslyn/3"> Partial Class C Private Shared F3 As Object = <x> <%= E1() %> <%= E2() %> <%= E3() %> </x> Private Shared Function E3() As Object Return <y/> End Function End Class ]]></file> </compilation>, references:=Net40XmlReferences, expectedOutput:=<![CDATA[ <x> <y /> <y xmlns="http://roslyn/2" /> <y xmlns="http://roslyn/3" /> </x> <x xmlns="http://roslyn/2"> <y xmlns="" /> <y /> <y xmlns="http://roslyn/3" /> </x> <x xmlns="http://roslyn/3"> <y xmlns="" /> <y xmlns="http://roslyn/2" /> <y /> </x> ]]>) End Sub ' Embedded expression from separate file with distinct Imports. <Fact()> Public Sub ImplicitXmlnsAttributes_DistinctImports() Dim compilation = CompileAndVerify( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports <xmlns:p="http://roslyn/p"> Imports <xmlns:q="http://roslyn/q1"> Imports <xmlns:r="http://roslyn/r"> Module M Public F As Object = <x> <y> <p:z q:a="b" r:c="d"/> <%= N.F %> </y> </x> Sub Main() System.Console.WriteLine("{0}", F) End Sub End Module ]]></file> <file name="b.vb"><![CDATA[ Option Strict On Imports <xmlns:p="http://roslyn/p"> Imports <xmlns:q="http://roslyn/q2"> Imports <xmlns:s="http://roslyn/r"> Module N Public F As Object = <p:z q:a="b" s:c="d"/> End Module ]]></file> </compilation>, references:=Net40XmlReferences, expectedOutput:=<![CDATA[ <x xmlns:r="http://roslyn/r" xmlns:q="http://roslyn/q1" xmlns:p="http://roslyn/p" xmlns:s="http://roslyn/r"> <y> <p:z q:a="b" s:c="d" /> <p:z q:a="b" s:c="d" xmlns:q="http://roslyn/q2" /> </y> </x> ]]>) End Sub ' Embedded expression other than as XElement content. ' (Dev11 does not merge namespaces in <x <%= F %>/> ' although Roslyn does.) <Fact()> Public Sub ImplicitXmlnsAttributes_EmbeddedExpressionOutsideContent() Dim compilation = CompileAndVerify( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports <xmlns:p="http://roslyn/"> Module M Private F1 As Object = <x <%= <p:y/> %>/> Private F2 As Object = <<%= <p:y/> %>/> Private F3 As Object = <?xml version="1.0"?><%= <p:y/> %> Sub Main() System.Console.WriteLine("{0}", F1) System.Console.WriteLine("{0}", F2) System.Console.WriteLine("{0}", F3) End Sub End Module ]]></file> </compilation>, references:=Net40XmlReferences, expectedOutput:=<![CDATA[ <x xmlns:p="http://roslyn/"> <p:y /> </x> <p:y xmlns:p="http://roslyn/" /> <p:y xmlns:p="http://roslyn/" /> ]]>) End Sub ' Opaque embedded expression and XML literal embedded expression ' with duplicate namespace references. (Dev11 generates code ' that throws InvalidOperationException: "Duplicate attribute".) <Fact()> Public Sub ImplicitXmlnsAttributes_EmbeddedExpressionAndEmbeddedLiteral() Dim compilation = CompileAndVerify( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports <xmlns:p="http://roslyn/p"> Imports <xmlns:q="http://roslyn/q"> Module M Private F1 As Object = <x> <%= F() %> <%= <p:z/> %> </x> Private F2 As Object = <x> <%= <p:y><%= F() %></p:y> %> </x> Function F() As Object Return <p:y q:a="b"/> End Function Sub Main() System.Console.WriteLine("{0}", F1) System.Console.WriteLine("{0}", F2) End Sub End Module ]]></file> </compilation>, references:=Net40XmlReferences, expectedOutput:=<![CDATA[ <x xmlns:q="http://roslyn/q" xmlns:p="http://roslyn/p"> <p:y q:a="b" /> <p:z /> </x> <x xmlns:p="http://roslyn/p" xmlns:q="http://roslyn/q"> <p:y> <p:y q:a="b" /> </p:y> </x> ]]>) End Sub ' InternalXmlHelper.RemoveNamespaceAttributes() modifies ' the embedded expression argument so subsequent uses of ' the expression may give different results. <WorkItem(529410, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529410")> <Fact()> Public Sub ImplicitXmlnsAttributes_SideEffects() Dim compilation = CompileAndVerify( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports <xmlns:p="http://roslyn/p"> Imports <xmlns:q="http://roslyn/q"> Module M Private F1 As Object = <q:y/> Private F2 As Object = <p:x><%= F1 %></p:x> Private F3 As Object = <p:x><%= F1 %></p:x> Sub Main() System.Console.WriteLine("{0}", F2) System.Console.WriteLine("{0}", F3) End Sub End Module ]]></file> </compilation>, references:=Net40XmlReferences, expectedOutput:=<![CDATA[ <p:x xmlns:p="http://roslyn/p" xmlns:q="http://roslyn/q"> <q:y /> </p:x> <p:x xmlns:p="http://roslyn/p"> <y xmlns="http://roslyn/q" /> </p:x> ]]>) End Sub <Fact()> Public Sub EmbeddedStringNameExpressions() Dim compilation = CompileAndVerify( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports System Imports System.Xml.Linq Module M Private F As String = "x" Private X As XElement = <<%= F %> <%= F %>="..."/> Sub Main() Console.WriteLine("{0}", X) End Sub End Module ]]></file> </compilation>, references:=Net40XmlReferences, expectedOutput:=<![CDATA[ <x x="..." /> ]]>) compilation.VerifyIL("M..cctor", <![CDATA[ { // Code size 57 (0x39) .maxstack 4 IL_0000: ldstr "x" IL_0005: stsfld "M.F As String" IL_000a: ldsfld "M.F As String" IL_000f: call "Function System.Xml.Linq.XName.op_Implicit(String) As System.Xml.Linq.XName" IL_0014: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_0019: dup IL_001a: ldsfld "M.F As String" IL_001f: call "Function System.Xml.Linq.XName.op_Implicit(String) As System.Xml.Linq.XName" IL_0024: ldstr "..." IL_0029: newobj "Sub System.Xml.Linq.XAttribute..ctor(System.Xml.Linq.XName, Object)" IL_002e: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_0033: stsfld "M.X As System.Xml.Linq.XElement" IL_0038: ret } ]]>) End Sub <Fact()> Public Sub EmbeddedXNameExpressions() Dim compilation = CompileAndVerify( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports System Imports System.Xml.Linq Module M Private F As XName = XName.Get("x", "") Private G As XName = XName.Get("y", "http://roslyn") Private H As XName = XName.Get("z", "") Private X As XElement = <<%= F %> <%= F %>="..."/> Private Y As XElement = <<%= G %> <%= G %>="..."/> Private Z As XElement = <<%= H %> <%= H %>="..."><%= H %></> Sub Main() Console.WriteLine("{0}", X) Console.WriteLine("{0}", Y) Console.WriteLine("{0}", Z) End Sub End Module ]]></file> </compilation>, references:=Net40XmlReferences, expectedOutput:=<![CDATA[ <x x="..." /> <y p1:y="..." xmlns:p1="http://roslyn" xmlns="http://roslyn" /> <z z="...">z</z> ]]>) compilation.VerifyIL("M..cctor", <![CDATA[ { // Code size 180 (0xb4) .maxstack 4 IL_0000: ldstr "x" IL_0005: ldstr "" IL_000a: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_000f: stsfld "M.F As System.Xml.Linq.XName" IL_0014: ldstr "y" IL_0019: ldstr "http://roslyn" IL_001e: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0023: stsfld "M.G As System.Xml.Linq.XName" IL_0028: ldstr "z" IL_002d: ldstr "" IL_0032: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0037: stsfld "M.H As System.Xml.Linq.XName" IL_003c: ldsfld "M.F As System.Xml.Linq.XName" IL_0041: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_0046: dup IL_0047: ldsfld "M.F As System.Xml.Linq.XName" IL_004c: ldstr "..." IL_0051: newobj "Sub System.Xml.Linq.XAttribute..ctor(System.Xml.Linq.XName, Object)" IL_0056: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_005b: stsfld "M.X As System.Xml.Linq.XElement" IL_0060: ldsfld "M.G As System.Xml.Linq.XName" IL_0065: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_006a: dup IL_006b: ldsfld "M.G As System.Xml.Linq.XName" IL_0070: ldstr "..." IL_0075: newobj "Sub System.Xml.Linq.XAttribute..ctor(System.Xml.Linq.XName, Object)" IL_007a: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_007f: stsfld "M.Y As System.Xml.Linq.XElement" IL_0084: ldsfld "M.H As System.Xml.Linq.XName" IL_0089: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_008e: dup IL_008f: ldsfld "M.H As System.Xml.Linq.XName" IL_0094: ldstr "..." IL_0099: newobj "Sub System.Xml.Linq.XAttribute..ctor(System.Xml.Linq.XName, Object)" IL_009e: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_00a3: dup IL_00a4: ldsfld "M.H As System.Xml.Linq.XName" IL_00a9: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_00ae: stsfld "M.Z As System.Xml.Linq.XElement" IL_00b3: ret } ]]>) End Sub ' Use InternalXmlHelper.CreateAttribute to generate attributes ' with embedded expression values since CreateAttribute will ' handle Nothing value. Otherwise, use New XAttribute(). <Fact()> Public Sub EmbeddedAttributeValueExpressions() Dim compilation = CompileAndVerify( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports System.Linq Imports System.Xml.Linq Module M Sub Main() Report(<x a1="b1"/>) Report(<x a2=<%= "b2" %>/>) Report(<x a3=<%= 3 %>/>) Report(<x a4=<%= Nothing %>/>) End Sub Sub Report(x As XElement) System.Console.WriteLine("[{0}] {1}", x.Attributes.Count(), x) End Sub End Module ]]></file> </compilation>, references:=Net40XmlReferences, expectedOutput:=<![CDATA[ [1] <x a1="b1" /> [1] <x a2="b2" /> [1] <x a3="3" /> [0] <x /> ]]>) compilation.VerifyIL("M.Main", <![CDATA[ { // Code size 222 (0xde) .maxstack 4 IL_0000: ldstr "x" IL_0005: ldstr "" IL_000a: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_000f: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_0014: dup IL_0015: ldstr "a1" IL_001a: ldstr "" IL_001f: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0024: ldstr "b1" IL_0029: newobj "Sub System.Xml.Linq.XAttribute..ctor(System.Xml.Linq.XName, Object)" IL_002e: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_0033: call "Sub M.Report(System.Xml.Linq.XElement)" IL_0038: ldstr "x" IL_003d: ldstr "" IL_0042: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0047: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_004c: dup IL_004d: ldstr "a2" IL_0052: ldstr "" IL_0057: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_005c: ldstr "b2" IL_0061: call "Function My.InternalXmlHelper.CreateAttribute(System.Xml.Linq.XName, Object) As System.Xml.Linq.XAttribute" IL_0066: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_006b: call "Sub M.Report(System.Xml.Linq.XElement)" IL_0070: ldstr "x" IL_0075: ldstr "" IL_007a: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_007f: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_0084: dup IL_0085: ldstr "a3" IL_008a: ldstr "" IL_008f: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0094: ldc.i4.3 IL_0095: box "Integer" IL_009a: call "Function My.InternalXmlHelper.CreateAttribute(System.Xml.Linq.XName, Object) As System.Xml.Linq.XAttribute" IL_009f: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_00a4: call "Sub M.Report(System.Xml.Linq.XElement)" IL_00a9: ldstr "x" IL_00ae: ldstr "" IL_00b3: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_00b8: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_00bd: dup IL_00be: ldstr "a4" IL_00c3: ldstr "" IL_00c8: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_00cd: ldnull IL_00ce: call "Function My.InternalXmlHelper.CreateAttribute(System.Xml.Linq.XName, Object) As System.Xml.Linq.XAttribute" IL_00d3: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_00d8: call "Sub M.Report(System.Xml.Linq.XElement)" IL_00dd: ret } ]]>) End Sub <Fact()> Public Sub EmbeddedChildExpressions() Dim compilation = CompileAndVerify( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports System Imports System.Xml.Linq Module M Property F As String = "f" Property G As XElement = <g/> Property H As XElement = <r:h xmlns:r="http://roslyn"/> Property W As XElement = <w w=<%= F %>/> Property X As XElement = <x><%= F %></x> Property Y As XElement = <y><%= G %></y> Property Z As XElement = <z><%= F %><%= G %><%= H %></z> Sub Main() Console.WriteLine("{0}", W) Console.WriteLine("{0}", X) Console.WriteLine("{0}", Y) Console.WriteLine("{0}", Z) End Sub End Module ]]></file> </compilation>, references:=Net40XmlReferences, expectedOutput:=<![CDATA[ <w w="f" /> <x>f</x> <y> <g /> </y> <z>f<g /><r:h xmlns:r="http://roslyn" /></z> ]]>) End Sub <Fact()> Public Sub EmbeddedChildExpressions_2() Dim compilation = CompileAndVerify( <compilation> <file name="c.vb"><![CDATA[ Imports System Imports System.Xml.Linq Module M Private FString = "s" Private FName As XName = XName.Get("n", "") Private FAttribute As XAttribute = New XAttribute(XName.Get("a", ""), "b") Private FElement As XElement = <e/> Private X1 As XElement = <x1 <%= FString %>/> Private X2 As XElement = <x2><%= FString %></x2> Private Y1 As XElement = <y1 <%= FName %>/> Private Y2 As XElement = <y2><%= FName %></y2> Private Z1 As XElement = <z1 <%= FAttribute %>/> Private Z2 As XElement = <z2><%= FAttribute %></z2> Private W1 As XElement = <w1 <%= FElement %>/> Private W2 As XElement = <w2><%= FElement %></w2> Sub Main() Console.WriteLine("{0}", X1) Console.WriteLine("{0}", X2) Console.WriteLine("{0}", Y1) Console.WriteLine("{0}", Y2) Console.WriteLine("{0}", Z1) Console.WriteLine("{0}", Z2) Console.WriteLine("{0}", W1) Console.WriteLine("{0}", W2) End Sub End Module ]]></file> </compilation>, references:=Net40XmlReferences, expectedOutput:=<![CDATA[ <x1>s</x1> <x2>s</x2> <y1>n</y1> <y2>n</y2> <z1 a="b" /> <z2 a="b" /> <w1> <e /> </w1> <w2> <e /> </w2> ]]>) End Sub ' XContainer.Add(ParamArray content As Object()) overload ' should be used if the expression represents an Object(). <Fact()> Public Sub EmbeddedChildCollectionExpressions() Dim compilation = CompileAndVerify( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports System Imports System.Collections.Generic Imports System.Linq Imports System.Xml.Linq Module M Private Function F() As XElement() Dim x = New XElement(1) {} x(0) = <<%= XName.Get("c1", "") %>/> x(1) = <<%= XName.Get("c2", "") %>/> Return x End Function Private Function G() As XElement(,) Dim x = New XElement(1, 1) {} x(0, 0) = <<%= XName.Get("c1", "") %>/> x(0, 1) = <<%= XName.Get("c2", "") %>/> x(1, 0) = <<%= XName.Get("c3", "") %>/> x(1, 1) = <<%= XName.Get("c4", "") %>/> Return x End Function Private Function H() As XElement()() Dim x = New XElement(1)() {} x(0) = F() x(1) = F() Return x End Function Private F0 As Object = F() Private F1 As Object() = F() Private F2 As XElement() = F() Private F3 As IEnumerable(Of Object) = F() Private F4 As IEnumerable(Of XElement) = F() Private F5 As XElement(,) = G() Private F6 As XElement()() = H() Sub Main() Report(<x0 <%= F0 %>/>) Report(<x0><%= F0 %></x0>) Report(<x1 <%= F1 %>/>) Report(<x1><%= F1 %></x1>) Report(<x2 <%= F2 %>/>) Report(<x2><%= F2 %></x2>) Report(<x3 <%= F3 %>/>) Report(<x3><%= F3 %></x3>) Report(<x4 <%= F4 %>/>) Report(<x4><%= F4 %></x4>) Report(<x5 <%= F5 %>/>) Report(<x5><%= F5 %></x5>) Report(<x6 <%= F6 %>/>) Report(<x6><%= F6 %></x6>) End Sub Sub Report(x As XElement) Console.WriteLine("{0}, #={1}", x, x.Elements.Count()) End Sub End Module ]]></file> </compilation>, references:=Net40XmlReferences, expectedOutput:=<![CDATA[ <x0> <c1 /> <c2 /> </x0>, #=2 <x0> <c1 /> <c2 /> </x0>, #=2 <x1> <c1 /> <c2 /> </x1>, #=2 <x1> <c1 /> <c2 /> </x1>, #=2 <x2> <c1 /> <c2 /> </x2>, #=2 <x2> <c1 /> <c2 /> </x2>, #=2 <x3> <c1 /> <c2 /> </x3>, #=2 <x3> <c1 /> <c2 /> </x3>, #=2 <x4> <c1 /> <c2 /> </x4>, #=2 <x4> <c1 /> <c2 /> </x4>, #=2 <x5> <c1 /> <c2 /> <c3 /> <c4 /> </x5>, #=4 <x5> <c1 /> <c2 /> <c3 /> <c4 /> </x5>, #=4 <x6> <c1 /> <c2 /> <c1 /> <c2 /> </x6>, #=4 <x6> <c1 /> <c2 /> <c1 /> <c2 /> </x6>, #=4 ]]>) compilation.VerifyIL("M.Main", <![CDATA[ { // Code size 515 (0x203) .maxstack 3 IL_0000: ldstr "x0" IL_0005: ldstr "" IL_000a: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_000f: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_0014: dup IL_0015: ldsfld "M.F0 As Object" IL_001a: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_001f: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_0024: call "Sub M.Report(System.Xml.Linq.XElement)" IL_0029: ldstr "x0" IL_002e: ldstr "" IL_0033: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0038: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_003d: dup IL_003e: ldsfld "M.F0 As Object" IL_0043: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0048: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_004d: call "Sub M.Report(System.Xml.Linq.XElement)" IL_0052: ldstr "x1" IL_0057: ldstr "" IL_005c: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0061: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_0066: dup IL_0067: ldsfld "M.F1 As Object()" IL_006c: callvirt "Sub System.Xml.Linq.XContainer.Add(ParamArray Object())" IL_0071: call "Sub M.Report(System.Xml.Linq.XElement)" IL_0076: ldstr "x1" IL_007b: ldstr "" IL_0080: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0085: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_008a: dup IL_008b: ldsfld "M.F1 As Object()" IL_0090: callvirt "Sub System.Xml.Linq.XContainer.Add(ParamArray Object())" IL_0095: call "Sub M.Report(System.Xml.Linq.XElement)" IL_009a: ldstr "x2" IL_009f: ldstr "" IL_00a4: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_00a9: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_00ae: dup IL_00af: ldsfld "M.F2 As System.Xml.Linq.XElement()" IL_00b4: callvirt "Sub System.Xml.Linq.XContainer.Add(ParamArray Object())" IL_00b9: call "Sub M.Report(System.Xml.Linq.XElement)" IL_00be: ldstr "x2" IL_00c3: ldstr "" IL_00c8: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_00cd: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_00d2: dup IL_00d3: ldsfld "M.F2 As System.Xml.Linq.XElement()" IL_00d8: callvirt "Sub System.Xml.Linq.XContainer.Add(ParamArray Object())" IL_00dd: call "Sub M.Report(System.Xml.Linq.XElement)" IL_00e2: ldstr "x3" IL_00e7: ldstr "" IL_00ec: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_00f1: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_00f6: dup IL_00f7: ldsfld "M.F3 As System.Collections.Generic.IEnumerable(Of Object)" IL_00fc: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_0101: call "Sub M.Report(System.Xml.Linq.XElement)" IL_0106: ldstr "x3" IL_010b: ldstr "" IL_0110: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0115: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_011a: dup IL_011b: ldsfld "M.F3 As System.Collections.Generic.IEnumerable(Of Object)" IL_0120: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_0125: call "Sub M.Report(System.Xml.Linq.XElement)" IL_012a: ldstr "x4" IL_012f: ldstr "" IL_0134: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0139: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_013e: dup IL_013f: ldsfld "M.F4 As System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)" IL_0144: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_0149: call "Sub M.Report(System.Xml.Linq.XElement)" IL_014e: ldstr "x4" IL_0153: ldstr "" IL_0158: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_015d: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_0162: dup IL_0163: ldsfld "M.F4 As System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)" IL_0168: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_016d: call "Sub M.Report(System.Xml.Linq.XElement)" IL_0172: ldstr "x5" IL_0177: ldstr "" IL_017c: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0181: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_0186: dup IL_0187: ldsfld "M.F5 As System.Xml.Linq.XElement(,)" IL_018c: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_0191: call "Sub M.Report(System.Xml.Linq.XElement)" IL_0196: ldstr "x5" IL_019b: ldstr "" IL_01a0: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_01a5: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_01aa: dup IL_01ab: ldsfld "M.F5 As System.Xml.Linq.XElement(,)" IL_01b0: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_01b5: call "Sub M.Report(System.Xml.Linq.XElement)" IL_01ba: ldstr "x6" IL_01bf: ldstr "" IL_01c4: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_01c9: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_01ce: dup IL_01cf: ldsfld "M.F6 As System.Xml.Linq.XElement()()" IL_01d4: callvirt "Sub System.Xml.Linq.XContainer.Add(ParamArray Object())" IL_01d9: call "Sub M.Report(System.Xml.Linq.XElement)" IL_01de: ldstr "x6" IL_01e3: ldstr "" IL_01e8: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_01ed: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_01f2: dup IL_01f3: ldsfld "M.F6 As System.Xml.Linq.XElement()()" IL_01f8: callvirt "Sub System.Xml.Linq.XContainer.Add(ParamArray Object())" IL_01fd: call "Sub M.Report(System.Xml.Linq.XElement)" IL_0202: ret } ]]>) End Sub <Fact()> Public Sub EmbeddedExpressionConversions() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports System.Xml.Linq Class A End Class Structure S End Structure Class C(Of T) Private Shared F1 As Object = Nothing Private Shared F2 As String = Nothing Private Shared F3 As XName = Nothing Private Shared F4 As XElement = Nothing Private Shared F5 As A = Nothing Private Shared F6 As S = Nothing Private Shared F7 As T = Nothing Private Shared F8 As Unknown = Nothing Shared Sub M() Dim x As XElement x = <a><%= F1 %></a> x = <a><%= F2 %></a> x = <a><%= F3 %></a> x = <a><%= F4 %></a> x = <a><%= F5 %></a> x = <a><%= F6 %></a> x = <a><%= F7 %></a> x = <a><%= F8 %></a> x = <a <%= F1 %>="b"/> x = <a <%= F2 %>="b"/> x = <a <%= F3 %>="b"/> x = <a <%= F4 %>="b"/> x = <a <%= F5 %>="b"/> x = <a <%= F6 %>="b"/> x = <a <%= F7 %>="b"/> x = <a <%= F8 %>="b"/> x = <a b=<%= F1 %>/> x = <a b=<%= F2 %>/> x = <a b=<%= F3 %>/> x = <a b=<%= F4 %>/> x = <a b=<%= F5 %>/> x = <a b=<%= F6 %>/> x = <a b=<%= F7 %>/> x = <a b=<%= F8 %>/> End Sub End Class ]]></file> </compilation>, references:=Net40XmlReferences) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC30002: Type 'Unknown' is not defined. Private Shared F8 As Unknown = Nothing ~~~~~~~ BC30512: Option Strict On disallows implicit conversions from 'Object' to 'XName'. x = <a <%= F1 %>="b"/> ~~~~~~~~~ BC30311: Value of type 'XElement' cannot be converted to 'XName'. x = <a <%= F4 %>="b"/> ~~~~~~~~~ BC30311: Value of type 'A' cannot be converted to 'XName'. x = <a <%= F5 %>="b"/> ~~~~~~~~~ BC30311: Value of type 'S' cannot be converted to 'XName'. x = <a <%= F6 %>="b"/> ~~~~~~~~~ BC30311: Value of type 'T' cannot be converted to 'XName'. x = <a <%= F7 %>="b"/> ~~~~~~~~~ ]]></errors>) End Sub ' Values of constant embedded expressions ' should be inlined in generated code. <Fact()> Public Sub EmbeddedExpressionConstants() Dim compilation = CompileAndVerify( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Module M Private Const F1 As String = "v1" Private F2 As String = "v2" Function F() As Object Return <x a0=<%= "v0" %> a1=<%= F1 %> a2=<%= F2 %>/> End Function End Module ]]></file> </compilation>, references:=Net40XmlReferences) compilation.VerifyIL("M.F", <![CDATA[ { // Code size 114 (0x72) .maxstack 4 IL_0000: ldstr "x" IL_0005: ldstr "" IL_000a: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_000f: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_0014: dup IL_0015: ldstr "a0" IL_001a: ldstr "" IL_001f: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0024: ldstr "v0" IL_0029: call "Function My.InternalXmlHelper.CreateAttribute(System.Xml.Linq.XName, Object) As System.Xml.Linq.XAttribute" IL_002e: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_0033: dup IL_0034: ldstr "a1" IL_0039: ldstr "" IL_003e: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0043: ldstr "v1" IL_0048: call "Function My.InternalXmlHelper.CreateAttribute(System.Xml.Linq.XName, Object) As System.Xml.Linq.XAttribute" IL_004d: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_0052: dup IL_0053: ldstr "a2" IL_0058: ldstr "" IL_005d: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0062: ldsfld "M.F2 As String" IL_0067: call "Function My.InternalXmlHelper.CreateAttribute(System.Xml.Linq.XName, Object) As System.Xml.Linq.XAttribute" IL_006c: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_0071: ret } ]]>) End Sub <Fact()> Public Sub EmbeddedExpressionDelegateConversion() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports System.Xml.Linq Delegate Sub D() Module M Sub M0() End Sub Sub M1() End Sub Function M2() As Object Return Nothing End Function Function M3() As Object Return Nothing End Function Private F0 As D = <%= AddressOf M0 %> Private F1 As Object = <%= AddressOf M1 %> Private F2 As XElement = <x y=<%= AddressOf M2 %>/> Private F3 As XElement = <x><%= AddressOf M3 %></x> End Module ]]></file> </compilation>, references:=Net40XmlReferences) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC31172: An embedded expression cannot be used here. Private F0 As D = <%= AddressOf M0 %> ~~~~~~~~~~~~~~~~~~~ BC30491: Expression does not produce a value. Private F0 As D = <%= AddressOf M0 %> ~~~~~~~~~~~~ BC31172: An embedded expression cannot be used here. Private F1 As Object = <%= AddressOf M1 %> ~~~~~~~~~~~~~~~~~~~ BC30491: Expression does not produce a value. Private F1 As Object = <%= AddressOf M1 %> ~~~~~~~~~~~~ BC30491: Expression does not produce a value. Private F2 As XElement = <x y=<%= AddressOf M2 %>/> ~~~~~~~~~~~~ BC30491: Expression does not produce a value. Private F3 As XElement = <x><%= AddressOf M3 %></x> ~~~~~~~~~~~~ ]]></errors>) End Sub <Fact()> Public Sub EmbeddedExpressionXElementConstructor() Dim compilation = CompileAndVerify( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports System Imports System.Xml.Linq Module M Sub Main() Report(<<%= XName.Get("x", "") %>/>) Report(<<%= XName.Get("x", "") %> a="b">c</>) Report(<<%= <x1 a1="b1">c1</x1> %> a2="b2">c2</>) End Sub Sub Report(o As XElement) Console.WriteLine("{0}", o) End Sub End Module ]]></file> </compilation>, references:=Net40XmlReferences, expectedOutput:=<![CDATA[ <x /> <x a="b">c</x> <x1 a1="b1" a2="b2">c1c2</x1> ]]>) compilation.VerifyIL("M.Main", <![CDATA[ { // Code size 207 (0xcf) .maxstack 4 IL_0000: ldstr "x" IL_0005: ldstr "" IL_000a: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_000f: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_0014: call "Sub M.Report(System.Xml.Linq.XElement)" IL_0019: ldstr "x" IL_001e: ldstr "" IL_0023: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0028: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_002d: dup IL_002e: ldstr "a" IL_0033: ldstr "" IL_0038: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_003d: ldstr "b" IL_0042: newobj "Sub System.Xml.Linq.XAttribute..ctor(System.Xml.Linq.XName, Object)" IL_0047: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_004c: dup IL_004d: ldstr "c" IL_0052: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_0057: call "Sub M.Report(System.Xml.Linq.XElement)" IL_005c: ldstr "x1" IL_0061: ldstr "" IL_0066: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_006b: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_0070: dup IL_0071: ldstr "a1" IL_0076: ldstr "" IL_007b: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0080: ldstr "b1" IL_0085: newobj "Sub System.Xml.Linq.XAttribute..ctor(System.Xml.Linq.XName, Object)" IL_008a: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_008f: dup IL_0090: ldstr "c1" IL_0095: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_009a: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XElement)" IL_009f: dup IL_00a0: ldstr "a2" IL_00a5: ldstr "" IL_00aa: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_00af: ldstr "b2" IL_00b4: newobj "Sub System.Xml.Linq.XAttribute..ctor(System.Xml.Linq.XName, Object)" IL_00b9: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_00be: dup IL_00bf: ldstr "c2" IL_00c4: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_00c9: call "Sub M.Report(System.Xml.Linq.XElement)" IL_00ce: ret } ]]>) End Sub <Fact()> Public Sub EmbeddedExpressionNoXElementConstructor() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports System.Xml.Linq Class A End Class Structure S End Structure Class C(Of T) Private Shared F1 As Object = Nothing Private Shared F2 As String = Nothing Private Shared F3 As XName = Nothing Private Shared F4 As XElement = Nothing Private Shared F5 As A = Nothing Private Shared F6 As S = Nothing Private Shared F7 As T = Nothing Private Shared F8 As Unknown = Nothing Shared Sub M() Dim x As XElement x = <<%= F1 %>/> x = <<%= F2 %>/> x = <<%= F3 %>/> x = <<%= F4 %>/> x = <<%= F5 %>/> x = <<%= F6 %>/> x = <<%= F7 %>/> x = <<%= F8 %>/> End Sub End Class ]]></file> </compilation>, references:=Net40XmlReferences) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC30002: Type 'Unknown' is not defined. Private Shared F8 As Unknown = Nothing ~~~~~~~ BC30518: Overload resolution failed because no accessible 'New' can be called with these arguments: 'Public Overloads Sub New(name As XName)': Option Strict On disallows implicit conversions from 'Object' to 'XName'. 'Public Overloads Sub New(other As XElement)': Option Strict On disallows implicit conversions from 'Object' to 'XElement'. 'Public Overloads Sub New(other As XStreamingElement)': Option Strict On disallows implicit conversions from 'Object' to 'XStreamingElement'. x = <<%= F1 %>/> ~~~~~~~~~ BC30518: Overload resolution failed because no accessible 'New' can be called with these arguments: 'Public Overloads Sub New(name As XName)': Value of type 'A' cannot be converted to 'XName'. 'Public Overloads Sub New(other As XElement)': Value of type 'A' cannot be converted to 'XElement'. 'Public Overloads Sub New(other As XStreamingElement)': Value of type 'A' cannot be converted to 'XStreamingElement'. x = <<%= F5 %>/> ~~~~~~~~~ BC30518: Overload resolution failed because no accessible 'New' can be called with these arguments: 'Public Overloads Sub New(name As XName)': Value of type 'S' cannot be converted to 'XName'. 'Public Overloads Sub New(other As XElement)': Value of type 'S' cannot be converted to 'XElement'. 'Public Overloads Sub New(other As XStreamingElement)': Value of type 'S' cannot be converted to 'XStreamingElement'. x = <<%= F6 %>/> ~~~~~~~~~ BC30518: Overload resolution failed because no accessible 'New' can be called with these arguments: 'Public Overloads Sub New(name As XName)': Value of type 'T' cannot be converted to 'XName'. 'Public Overloads Sub New(other As XElement)': Value of type 'T' cannot be converted to 'XElement'. 'Public Overloads Sub New(other As XStreamingElement)': Value of type 'T' cannot be converted to 'XStreamingElement'. x = <<%= F7 %>/> ~~~~~~~~~ ]]></errors>) End Sub ' Expressions within XmlEmbeddedExpressionSyntax should be ' bound, even if outside of an XML expression (error cases). <Fact()> Public Sub EmbeddedExpressionOutsideXmlExpression() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Class A End Class Class B End Class Module M Property P1 As A ReadOnly Property P2 As A Get Return Nothing End Get End Property WriteOnly Property P3 As A Set(value As A) End Set End Property Private F1 As B = <%= P1 %> Private F2 As B = <%= P2 %> Private F3 As B = <%= P3 %> End Module ]]></file> </compilation>, references:=Net40XmlReferences) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC30311: Value of type 'A' cannot be converted to 'B'. Private F1 As B = <%= P1 %> ~~~~~~~~~ BC31172: An embedded expression cannot be used here. Private F1 As B = <%= P1 %> ~~~~~~~~~ BC30311: Value of type 'A' cannot be converted to 'B'. Private F2 As B = <%= P2 %> ~~~~~~~~~ BC31172: An embedded expression cannot be used here. Private F2 As B = <%= P2 %> ~~~~~~~~~ BC31172: An embedded expression cannot be used here. Private F3 As B = <%= P3 %> ~~~~~~~~~ BC30524: Property 'P3' is 'WriteOnly'. Private F3 As B = <%= P3 %> ~~ ]]></errors>) End Sub ' Embedded expressions should be ignored for xmlns ' declarations, even if the expression is a string constant. <Fact()> Public Sub EmbeddedXmlnsExpressions() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Imports System.Xml.Linq Module M Private F1 As XElement = <x:y xmlns:x="http://roslyn"/> Private F2 As XElement = <x:y <%= "xmlns:x" %>="http://roslyn"/> Private F3 As XElement = <x:y <%= XName.Get("x", "http://www.w3.org/2000/xmlns/") %>="http://roslyn"/> End Module ]]></file> </compilation>, references:=Net40XmlReferences) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC31148: XML namespace prefix 'x' is not defined. Private F2 As XElement = <x:y <%= "xmlns:x" %>="http://roslyn"/> ~ BC31148: XML namespace prefix 'x' is not defined. Private F3 As XElement = <x:y <%= XName.Get("x", "http://www.w3.org/2000/xmlns/") %>="http://roslyn"/> ~ ]]></errors>) End Sub <Fact()> Public Sub EmbeddedExpressionCycle() Dim compilation = CompileAndVerify( <compilation> <file name="c.vb"><![CDATA[ Imports System Imports System.Xml.Linq Class C Private Shared F As XElement = <f><%= F %></f> Shared Sub Main() Dim G As XElement = <g><%= G %></g> Console.WriteLine("{0}", F) Console.WriteLine("{0}", G) End Sub End Class ]]></file> </compilation>, references:=Net40XmlReferences, expectedOutput:=<![CDATA[ <f /> <g /> ]]>) End Sub ' Do not evaluate embedded expressions in Imports to avoid cycles. <Fact()> Public Sub EmbeddedExpressionImportCycle() Dim options = TestOptions.ReleaseDll.WithGlobalImports(GlobalImport.Parse({"<xmlns:p=<%= <p:x/>.@y %>>"})) Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Imports <xmlns:q=<%= <q:x/>.@y %>> Module M Private F As String = <p:x q:y=""/>.@z End Module ]]></file> </compilation>, references:=Net40XmlReferences, options:=options) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC31172: Error in project-level import '<xmlns:p=<%= <p:x/>.@y %>>' at '<%= <p:x/>.@y %>' : An embedded expression cannot be used here. BC31172: An embedded expression cannot be used here. Imports <xmlns:q=<%= <q:x/>.@y %>> ~~~~~~~~~~~~~~~~ BC31148: XML namespace prefix 'p' is not defined. Private F As String = <p:x q:y=""/>.@z ~ BC31148: XML namespace prefix 'q' is not defined. Private F As String = <p:x q:y=""/>.@z ~ ]]></errors>) End Sub <Fact()> Public Sub CharacterAndEntityReferences() Dim compilation = CompileAndVerify( <compilation> <file name="c.vb"><![CDATA[ Imports <xmlns:p="&amp;&apos;&#x30;abc"> Class C Shared Sub Main() Dim x = <x xmlns:p="&amp;&apos;&#x30;abc" p:y="&amp;&apos;&gt;&lt;&quot;&#x0058;&#x59;&#x5a;"/> Dim y = <x>&amp;&apos;&gt;&lt;&quot;<y/>&#x0058;&#x59;&#x5a;</x> System.Console.WriteLine(x.@p:y) System.Console.WriteLine(y.Value) End Sub End Class ]]></file> </compilation>, references:=Net40XmlReferences, expectedOutput:=<![CDATA[ &'><"XYZ &'><"XYZ ]]>) compilation.VerifyIL("C.Main", <![CDATA[ { // Code size 193 (0xc1) .maxstack 4 .locals init (System.Xml.Linq.XElement V_0) //x IL_0000: ldstr "x" IL_0005: ldstr "" IL_000a: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_000f: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_0014: dup IL_0015: ldstr "y" IL_001a: ldstr "&'0abc" IL_001f: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0024: ldstr "&'><"XYZ" IL_0029: newobj "Sub System.Xml.Linq.XAttribute..ctor(System.Xml.Linq.XName, Object)" IL_002e: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_0033: dup IL_0034: ldstr "p" IL_0039: ldstr "http://www.w3.org/2000/xmlns/" IL_003e: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0043: ldstr "&'0abc" IL_0048: call "Function System.Xml.Linq.XNamespace.Get(String) As System.Xml.Linq.XNamespace" IL_004d: call "Function My.InternalXmlHelper.CreateNamespaceAttribute(System.Xml.Linq.XName, System.Xml.Linq.XNamespace) As System.Xml.Linq.XAttribute" IL_0052: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_0057: stloc.0 IL_0058: ldstr "x" IL_005d: ldstr "" IL_0062: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0067: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_006c: dup IL_006d: ldstr "&'><"" IL_0072: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_0077: dup IL_0078: ldstr "y" IL_007d: ldstr "" IL_0082: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0087: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_008c: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_0091: dup IL_0092: ldstr "XYZ" IL_0097: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_009c: ldloc.0 IL_009d: ldstr "y" IL_00a2: ldstr "&'0abc" IL_00a7: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_00ac: call "Function My.InternalXmlHelper.get_AttributeValue(System.Xml.Linq.XElement, System.Xml.Linq.XName) As String" IL_00b1: call "Sub System.Console.WriteLine(String)" IL_00b6: callvirt "Function System.Xml.Linq.XElement.get_Value() As String" IL_00bb: call "Sub System.Console.WriteLine(String)" IL_00c0: ret } ]]>) End Sub <Fact()> Public Sub CDATA() Dim compilation = CompileAndVerify( <compilation> <file name="c.vb"> Option Strict On Module M Sub Main() Dim o = &lt;![CDATA[value]]&gt; System.Console.WriteLine("{0}: {1}", o.GetType(), o) End Sub End Module </file> </compilation>, references:=Net40XmlReferences, expectedOutput:="System.Xml.Linq.XCData: <![CDATA[value]]>") compilation.VerifyIL("M.Main", <![CDATA[ { // Code size 29 (0x1d) .maxstack 3 .locals init (System.Xml.Linq.XCData V_0) //o IL_0000: ldstr "value" IL_0005: newobj "Sub System.Xml.Linq.XCData..ctor(String)" IL_000a: stloc.0 IL_000b: ldstr "{0}: {1}" IL_0010: ldloc.0 IL_0011: callvirt "Function Object.GetType() As System.Type" IL_0016: ldloc.0 IL_0017: call "Sub System.Console.WriteLine(String, Object, Object)" IL_001c: ret } ]]>) End Sub <Fact()> Public Sub CDATAContent() Dim compilation = CompileAndVerify( <compilation> <file name="c.vb"> Imports System Imports System.Xml.Linq Module M Sub Main() Dim x As XElement = &lt;a&gt; &lt;![CDATA[&lt;b&gt; &lt;c/&gt; &lt;/&gt;]]&gt; &lt;/a&gt; Console.WriteLine("{0}", x.Value) End Sub End Module </file> </compilation>, references:=Net40XmlReferences, expectedOutput:="<b>" & vbLf & " <c/>" & vbLf & "</>") End Sub <Fact()> Public Sub [GetXmlNamespace]() Dim compilation = CompileAndVerify( <compilation> <file name="c.vb"><![CDATA[ Imports <xmlns:F="http://roslyn/F"> Imports <xmlns:p-q="http://roslyn/p-q"> Module M Private F As Object Sub Main() Report(GetXmlNamespace(xml)) Report(GetXmlNamespace(xmlns)) Report(GetXmlNamespace()) Report(GetXmlNamespace(F)) Report(GetXmlNamespace(p-q)) End Sub Sub Report(o As Object) System.Console.WriteLine("{0}", o) End Sub End Module ]]></file> </compilation>, references:=Net40XmlReferences, expectedOutput:=<![CDATA[ http://www.w3.org/XML/1998/namespace http://www.w3.org/2000/xmlns/ http://roslyn/F http://roslyn/p-q ]]>) compilation.VerifyIL("M.Main", <![CDATA[ { // Code size 76 (0x4c) .maxstack 1 IL_0000: ldstr "http://www.w3.org/XML/1998/namespace" IL_0005: call "Function System.Xml.Linq.XNamespace.Get(String) As System.Xml.Linq.XNamespace" IL_000a: call "Sub M.Report(Object)" IL_000f: ldstr "http://www.w3.org/2000/xmlns/" IL_0014: call "Function System.Xml.Linq.XNamespace.Get(String) As System.Xml.Linq.XNamespace" IL_0019: call "Sub M.Report(Object)" IL_001e: ldstr "" IL_0023: call "Function System.Xml.Linq.XNamespace.Get(String) As System.Xml.Linq.XNamespace" IL_0028: call "Sub M.Report(Object)" IL_002d: ldstr "http://roslyn/F" IL_0032: call "Function System.Xml.Linq.XNamespace.Get(String) As System.Xml.Linq.XNamespace" IL_0037: call "Sub M.Report(Object)" IL_003c: ldstr "http://roslyn/p-q" IL_0041: call "Function System.Xml.Linq.XNamespace.Get(String) As System.Xml.Linq.XNamespace" IL_0046: call "Sub M.Report(Object)" IL_004b: ret } ]]>) End Sub ' Dev10 reports an error (BC31146: "XML name expected.") for ' leading or trailing trivia around the GetXmlNamespace ' argument. Those cases are not treated as errors in Roslyn. <Fact()> Public Sub GetXmlNamespaceWithTrivia() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Imports <xmlns:p="http://roslyn/"> Module M Private F1 = GetXmlNamespace( ) Private F2 = GetXmlNamespace(xml ) Private F3 = GetXmlNamespace( p) End Module ]]></file> </compilation>, references:=Net40XmlReferences) compilation.AssertNoErrors() End Sub <WorkItem(544261, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544261")> <Fact()> Public Sub IncompleteProjectLevelImport() Assert.Throws(Of ArgumentException)(Sub() TestOptions.ReleaseDll.WithGlobalImports(GlobalImport.Parse({"<xmlns:p=""..."""}))) Assert.Throws(Of ArgumentException)(Sub() TestOptions.ReleaseDll.WithGlobalImports(GlobalImport.Parse({"<xmlns:p=""..."">, <xmlns:q=""..."""}))) End Sub <WorkItem(544360, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544360")> <Fact()> Public Sub ExplicitDefaultXmlnsAttribute_1() Dim compilation = CompileAndVerify( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Module M Sub Main() Report(<x xmlns=" "/>) Report(<y xmlns="http://roslyn"/>) End Sub Sub Report(x As System.Xml.Linq.XElement) System.Console.WriteLine("[{0}, {1}]: {2}", x.Name.LocalName, x.Name.NamespaceName, x) End Sub End Module ]]></file> </compilation>, references:=Net40XmlReferences, expectedOutput:=<![CDATA[ [x, ]: <x xmlns=" " /> [y, http://roslyn]: <y xmlns="http://roslyn" /> ]]>) End Sub <Fact()> Public Sub ExplicitDefaultXmlnsAttribute_2() Dim compilation = CompileAndVerify( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports <xmlns="http://roslyn/1"> Module M Sub Main() Report(<x xmlns="http://roslyn/2"/>) End Sub Sub Report(x As System.Xml.Linq.XElement) System.Console.WriteLine("[{0}, {1}]: {2}", x.Name.LocalName, x.Name.NamespaceName, x) End Sub End Module ]]></file> </compilation>, references:=Net40XmlReferences, expectedOutput:=<![CDATA[ [x, http://roslyn/2]: <x xmlns="http://roslyn/2" /> ]]>) End Sub <WorkItem(544461, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544461")> <Fact()> Public Sub ValueExtensionProperty() Dim compilation = CompileAndVerify( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports System.Collections.Generic Imports System.Xml.Linq Class X Inherits XElement Public Sub New(name As XName) MyBase.New(name) End Sub End Class Structure S Implements IEnumerable(Of XElement) Public Function GetEnumerator() As IEnumerator(Of XElement) Implements IEnumerable(Of XElement).GetEnumerator Return Nothing End Function Public Function GetEnumerator1() As System.Collections.IEnumerator Implements System.Collections.IEnumerable.GetEnumerator Return Nothing End Function End Structure Interface IEnumerableOfXElement Inherits IEnumerable(Of XElement) End Interface Module M Sub M(Of T As XElement)( _1 As XElement, _2 As X, _3 As T, _4 As IEnumerable(Of XElement), _5 As IEnumerable(Of X), _6 As IEnumerable(Of T), _7 As IEnumerableOfXElement, _8 As XElement(), _9 As List(Of XElement), _10 As S) Dim o As Object o = <x/>.Value o = <x/>.<y>.Value o = _1.Value o = _2.Value o = _3.Value o = _4.Value o = _5.Value o = _6.Value o = _7.Value o = _8.Value o = _9.Value o = _10.Value End Sub End Module ]]></file> </compilation>, references:=Net40XmlReferences) compilation.VerifyIL("M.M(Of T)", <![CDATA[ { // Code size 166 (0xa6) .maxstack 3 IL_0000: ldstr "x" IL_0005: ldstr "" IL_000a: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_000f: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_0014: call "Function System.Xml.Linq.XElement.get_Value() As String" IL_0019: pop IL_001a: ldstr "x" IL_001f: ldstr "" IL_0024: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0029: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_002e: ldstr "y" IL_0033: ldstr "" IL_0038: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_003d: call "Function System.Xml.Linq.XContainer.Elements(System.Xml.Linq.XName) As System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)" IL_0042: call "Function My.InternalXmlHelper.get_Value(System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)) As String" IL_0047: pop IL_0048: ldarg.0 IL_0049: callvirt "Function System.Xml.Linq.XElement.get_Value() As String" IL_004e: pop IL_004f: ldarg.1 IL_0050: callvirt "Function System.Xml.Linq.XElement.get_Value() As String" IL_0055: pop IL_0056: ldarga.s V_2 IL_0058: constrained. "T" IL_005e: callvirt "Function System.Xml.Linq.XElement.get_Value() As String" IL_0063: pop IL_0064: ldarg.3 IL_0065: call "Function My.InternalXmlHelper.get_Value(System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)) As String" IL_006a: pop IL_006b: ldarg.s V_4 IL_006d: call "Function My.InternalXmlHelper.get_Value(System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)) As String" IL_0072: pop IL_0073: ldarg.s V_5 IL_0075: call "Function My.InternalXmlHelper.get_Value(System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)) As String" IL_007a: pop IL_007b: ldarg.s V_6 IL_007d: call "Function My.InternalXmlHelper.get_Value(System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)) As String" IL_0082: pop IL_0083: ldarg.s V_7 IL_0085: call "Function My.InternalXmlHelper.get_Value(System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)) As String" IL_008a: pop IL_008b: ldarg.s V_8 IL_008d: call "Function My.InternalXmlHelper.get_Value(System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)) As String" IL_0092: pop IL_0093: ldarg.s V_9 IL_0095: box "S" IL_009a: castclass "System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)" IL_009f: call "Function My.InternalXmlHelper.get_Value(System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)) As String" IL_00a4: pop IL_00a5: ret } ]]>) End Sub <Fact()> Public Sub ValueExtensionProperty_2() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports System Imports System.Collections.Generic Imports System.Runtime.CompilerServices Imports System.Xml.Linq Class A Inherits List(Of XElement) Public Property P As String End Class Class B Inherits A Public Property Value As String End Class Class C Inherits A Public Value As String End Class Class D Inherits A Public Property Value(o As Object) As String Get Return Nothing End Get Set(value As String) End Set End Property End Class Class E Inherits A Public Function Value() As String Return Nothing End Function End Class Class F Inherits A End Class Module M <Extension()> Public Function Value(o As F) As String Return Nothing End Function Sub M() Dim _a As New A() With {.Value = .P, .P = .Value} Dim _b As New B() With {.Value = .P, .P = .Value} Dim _c As New C() With {.Value = .P, .P = .Value} Dim _d As New D() With {.Value = .P, .P = .Value} Dim _e As New E() With {.Value = .P, .P = .Value} Dim _f As New F() With {.Value = .P, .P = .Value} _a.VALUE = Nothing _b.VALUE = Nothing _c.VALUE = Nothing _d.value = Nothing _e.value = Nothing _f.value = Nothing End Sub End Module ]]></file> </compilation>, references:=Net40XmlReferences) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC30991: Member 'Value' cannot be initialized in an object initializer expression because it is shared. Dim _a As New A() With {.Value = .P, .P = .Value} ~~~~~ BC30992: Property 'Value' cannot be initialized in an object initializer expression because it requires arguments. Dim _d As New D() With {.Value = .P, .P = .Value} ~~~~~ BC30455: Argument not specified for parameter 'o' of 'Public Property Value(o As Object) As String'. Dim _d As New D() With {.Value = .P, .P = .Value} ~~~~~ BC30990: Member 'Value' cannot be initialized in an object initializer expression because it is not a field or property. Dim _e As New E() With {.Value = .P, .P = .Value} ~~~~~ BC30990: Member 'Value' cannot be initialized in an object initializer expression because it is not a field or property. Dim _f As New F() With {.Value = .P, .P = .Value} ~~~~~ BC30455: Argument not specified for parameter 'o' of 'Public Property Value(o As Object) As String'. _d.value = Nothing ~~~~~ BC30068: Expression is a value and therefore cannot be the target of an assignment. _e.value = Nothing ~~~~~~~~ BC30068: Expression is a value and therefore cannot be the target of an assignment. _f.value = Nothing ~~~~~~~~ ]]></errors>) End Sub <Fact()> Public Sub ValueExtensionProperty_3() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports System.Collections.Generic Imports System.Xml.Linq Class C Inherits List(Of XElement) Sub M() Me.Value = F(Me.Value) MyBase.Value = F(MyBase.Value) Value = F(Value) Dim c As Char = Me.Value(0) c = Me.Value()(1) Me.Value() = Me.Value(Of Object)() End Sub Function F(o As String) As String Return Nothing End Function End Class ]]></file> </compilation>, references:=Net40XmlReferences) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC30469: Reference to a non-shared member requires an object reference. Value = F(Value) ~~~~~ BC30469: Reference to a non-shared member requires an object reference. Value = F(Value) ~~~~~ BC30456: 'Value' is not a member of 'C'. Me.Value() = Me.Value(Of Object)() ~~~~~~~~~~~~~~~~~~~ ]]></errors>) End Sub <Fact()> Public Sub ValueExtensionProperty_4() Dim compilation = CompileAndVerify( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports System Imports System.Collections.Generic Imports System.Xml.Linq Module M Sub Main() Dim x = <x> <y>content</y> <z/> </x> x.<x>.Value += "1" x.<y>.Value += "2" Add(x.<z>.Value, "3") Console.WriteLine("{0}", x) End Sub Sub Add(ByRef s As String, value As String) s += value End Sub End Module ]]></file> </compilation>, references:=Net40XmlReferences, expectedOutput:=<![CDATA[ <x> <y>content2</y> <z>3</z> </x> ]]>) End Sub ''' <summary> ''' If there is an accessible extension method named "Value", the InternalXmlHelper ''' Value extension property should be dropped, since we do not perform overload ''' resolution between methods and properties. If the extension method is inaccessible ''' however, the InternalXmlHelper property should be used. ''' </summary> <Fact()> Public Sub ValueExtensionPropertyAndExtensionMethod() ' Accessible extension method. Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Imports System.Collections.Generic Imports System.Runtime.CompilerServices Imports System.Xml.Linq Class C Sub M() Dim x = <x/>.<y> Dim o = x.Value() x.Value(o) End Sub End Class Module M <Extension()> Function Value(x As IEnumerable(Of XElement), y As Object) As Object Return Nothing End Function End Module ]]></file> </compilation>, references:=Net40XmlReferences) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC36586: Argument not specified for parameter 'y' of extension method 'Public Function Value(y As Object) As Object' defined in 'M'. Dim o = x.Value() ~~~~~ ]]></errors>) ' Inaccessible extension method. compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Imports System.Collections.Generic Imports System.Runtime.CompilerServices Imports System.Xml.Linq Class C Sub M() Dim x = <x/>.<y> Dim o = x.Value() x.Value(o) End Sub End Class Module M <Extension()> Private Function Value(x As IEnumerable(Of XElement), y As Object) As Object Return Nothing End Function End Module ]]></file> </compilation>, references:=Net40XmlReferences) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC30057: Too many arguments to 'Public Property Value As String'. x.Value(o) ~ ]]></errors>) End Sub ''' <summary> ''' Bind to InternalXmlHelper Value extension property if a member named "Value" is inaccessible. ''' Note that Dev11 ignores the InternalXmlHelper property if regular binding finds a ''' member (in this case, the inaccessible member). Therefore this is a breaking change. ''' </summary> <Fact()> Public Sub ValueExtensionPropertyAndInaccessibleMember() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Imports System.Collections Imports System.Collections.Generic Imports System.Xml.Linq Structure S Implements IEnumerable(Of XElement) Public Function GetEnumerator() As IEnumerator(Of XElement) Implements IEnumerable(Of XElement).GetEnumerator Return Nothing End Function Public Function GetEnumerator1() As IEnumerator Implements IEnumerable.GetEnumerator Return Nothing End Function Private Property Value As Object End Structure Module M Function F(o As S) ' Dev11: BC30390: 'S.Value' is not accessible in this context because it is 'Private'. Return o.Value End Function End Module ]]></file> </compilation>, references:=Net40XmlReferences) compilation.AssertNoErrors() End Sub ' The InternalXmlHelper.Value extension property should be available ' for IEnumerable(Of XElement) only. The AttributeValue extension property ' is overloaded for XElement and IEnumerable(Of XElement) but should ' only be available if the namespace is imported. <Fact()> Public Sub ValueAndAttributeValueExtensionProperties() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports System.Collections.Generic Imports System.Xml.Linq Class X Inherits XElement Public Sub New(name As XName) MyBase.New(name) End Sub End Class Interface IEnumerableOfXElement Inherits IEnumerable(Of XElement) End Interface Module M Sub M(Of T As XElement)( _1 As XObject, _2 As XElement, _3 As X, _4 As T, _5 As IEnumerable(Of XObject), _6 As IEnumerable(Of XElement), _7 As IEnumerable(Of X), _8 As IEnumerable(Of T), _9 As IEnumerableOfXElement, _10 As XElement(), _11 As List(Of XElement), _12 As IEnumerable(Of XElement)()) Dim name As XName = Nothing Dim o As Object o = <x/>.Value o = <x/>.AttributeValue(name) o = <x/>.<y>.Value o = <x/>.<y>.AttributeValue(name) o = <x/>[email protected] o = <x/>[email protected](name) o = _1.Value o = _1.AttributeValue(name) o = _2.Value o = _2.AttributeValue(name) o = _3.Value o = _3.AttributeValue(name) o = _4.Value o = _4.AttributeValue(name) o = _5.Value o = _5.AttributeValue(name) o = _6.Value o = _6.AttributeValue(name) o = _7.Value o = _7.AttributeValue(name) o = _8.Value o = _8.AttributeValue(name) o = _9.Value o = _9.AttributeValue(name) o = _10.Value o = _10.AttributeValue(name) o = _11.Value o = _11.AttributeValue(name) o = _12.Value o = _12.AttributeValue(name) End Sub End Module ]]></file> </compilation>, references:=Net40XmlReferences) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC30456: 'AttributeValue' is not a member of 'XElement'. o = <x/>.AttributeValue(name) ~~~~~~~~~~~~~~~~~~~ BC30456: 'AttributeValue' is not a member of 'IEnumerable(Of XElement)'. o = <x/>.<y>.AttributeValue(name) ~~~~~~~~~~~~~~~~~~~~~~~ BC30456: 'Value' is not a member of 'String'. o = <x/>[email protected] ~~~~~~~~~~~~~ BC30456: 'AttributeValue' is not a member of 'String'. o = <x/>[email protected](name) ~~~~~~~~~~~~~~~~~~~~~~ BC30456: 'Value' is not a member of 'XObject'. o = _1.Value ~~~~~~~~ BC30456: 'AttributeValue' is not a member of 'XObject'. o = _1.AttributeValue(name) ~~~~~~~~~~~~~~~~~ BC30456: 'AttributeValue' is not a member of 'XElement'. o = _2.AttributeValue(name) ~~~~~~~~~~~~~~~~~ BC30456: 'AttributeValue' is not a member of 'X'. o = _3.AttributeValue(name) ~~~~~~~~~~~~~~~~~ BC30456: 'AttributeValue' is not a member of 'T'. o = _4.AttributeValue(name) ~~~~~~~~~~~~~~~~~ BC30456: 'Value' is not a member of 'IEnumerable(Of XObject)'. o = _5.Value ~~~~~~~~ BC30456: 'AttributeValue' is not a member of 'IEnumerable(Of XObject)'. o = _5.AttributeValue(name) ~~~~~~~~~~~~~~~~~ BC30456: 'AttributeValue' is not a member of 'IEnumerable(Of XElement)'. o = _6.AttributeValue(name) ~~~~~~~~~~~~~~~~~ BC30456: 'AttributeValue' is not a member of 'IEnumerable(Of X)'. o = _7.AttributeValue(name) ~~~~~~~~~~~~~~~~~ BC30456: 'AttributeValue' is not a member of 'IEnumerable(Of T As XElement)'. o = _8.AttributeValue(name) ~~~~~~~~~~~~~~~~~ BC30456: 'AttributeValue' is not a member of 'IEnumerableOfXElement'. o = _9.AttributeValue(name) ~~~~~~~~~~~~~~~~~ BC30456: 'AttributeValue' is not a member of 'XElement()'. o = _10.AttributeValue(name) ~~~~~~~~~~~~~~~~~~ BC30456: 'AttributeValue' is not a member of 'List(Of XElement)'. o = _11.AttributeValue(name) ~~~~~~~~~~~~~~~~~~ BC30456: 'Value' is not a member of 'IEnumerable(Of XElement)()'. o = _12.Value ~~~~~~~~~ BC30456: 'AttributeValue' is not a member of 'IEnumerable(Of XElement)()'. o = _12.AttributeValue(name) ~~~~~~~~~~~~~~~~~~ ]]></errors>) End Sub <Fact()> Public Sub TrimElementContent() Dim compilation = CompileAndVerify( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports Microsoft.VisualBasic Imports System Imports System.Xml.Linq Module M Private F As XElement = <x> <y> <z> nested </z> </y> <y> &#x20; <z> nested </z> &#x20; </y> <y> begin <z> nested </z> end </y> <y xml:space="default"> begin <z> nested </z> end </y> <y xml:space="preserve"> begin <z> nested </z> end </y> </x> Sub Main() For Each y In F.<y> Console.Write("{0}" & Environment.NewLine, y.ToString()) Console.Write("[{0}]" & Environment.NewLine, y.Value.Replace(vbLf, Environment.NewLine)) Next End Sub End Module ]]></file> </compilation>, references:=Net40XmlReferences, expectedOutput:=<![CDATA[ <y> <z> nested </z> </y> [ nested ] <y> <z> nested </z> </y> [ nested ] <y> begin <z> nested </z> end </y> [ begin nested end ] <y xml:space="default"> begin <z> nested </z> end </y> [ begin nested end ] <y xml:space="preserve"> begin <z> nested </z> end </y> [ begin nested end ] ]]>) End Sub ''' <summary> ''' CR/LF and single CR characters should be ''' replaced by single LF characters. ''' </summary> <WorkItem(545508, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545508")> <Fact()> Public Sub NormalizeNewlinesTest() For Each eol In {vbCr, vbLf, vbCrLf} Dim sourceBuilder = New StringBuilder() sourceBuilder.AppendLine("Module M") sourceBuilder.AppendLine(" Sub Main()") sourceBuilder.AppendLine(" Report(<x>[" & eol & "|" & eol & eol & "]</>.Value)") sourceBuilder.AppendLine(" Report(<x><![CDATA[[" & eol & "|" & eol & eol & "]]]></>.Value)") sourceBuilder.AppendLine(" End Sub") sourceBuilder.AppendLine(" Sub Report(s As String)") sourceBuilder.AppendLine(" For Each c As Char in s") sourceBuilder.AppendLine(" System.Console.WriteLine(""{0}"", Microsoft.VisualBasic.AscW(c))") sourceBuilder.AppendLine(" Next") sourceBuilder.AppendLine(" End Sub") sourceBuilder.AppendLine("End Module") Dim sourceTree = VisualBasicSyntaxTree.ParseText(sourceBuilder.ToString()) Dim comp = VisualBasicCompilation.Create(Guid.NewGuid().ToString(), {sourceTree}, DefaultVbReferences.Concat(Net40XmlReferences)) CompileAndVerify(comp, expectedOutput:=<![CDATA[ 91 10 124 10 10 93 91 10 124 10 10 93 ]]>) Next End Sub <Fact()> Public Sub NormalizeAttributeValue() Const space = " " Dim strs = {space, vbCr, vbLf, vbCrLf, vbTab, "&#x20;", "&#xD;", "&#xA;", "&#x9;"} ' Empty string. NormalizeAttributeValueCore("") ' Single characters. For Each str0 In strs NormalizeAttributeValueCore(str0) NormalizeAttributeValueCore("[" & str0 & "]") Next ' Pairs of characters. For Each str1 In strs For Each str2 In strs Dim str = str1 & str2 NormalizeAttributeValueCore(str) NormalizeAttributeValueCore("[" & str & "]") Next Next End Sub Private Sub NormalizeAttributeValueCore(str As String) Dim sourceBuilder = New StringBuilder() sourceBuilder.AppendLine("Module M") sourceBuilder.AppendLine(" Sub Main()") sourceBuilder.AppendLine(" System.Console.WriteLine(""[[{0}]]"", <x a=""" & str & """/>.@a)") sourceBuilder.AppendLine(" End Sub") sourceBuilder.AppendLine("End Module") Dim sourceTree = VisualBasicSyntaxTree.ParseText(sourceBuilder.ToString()) Dim comp = VisualBasicCompilation.Create(Guid.NewGuid().ToString(), {sourceTree}, DefaultVbReferences.Concat(Net40XmlReferences)) CompileAndVerify(comp, expectedOutput:="[[" & NormalizeValue(str) & "]]") End Sub Private Function NormalizeValue(str As String) As String Const space = " " str = str.Replace(vbCrLf, space) str = str.Replace(vbCr, space) str = str.Replace(vbLf, space) str = str.Replace(vbTab, space) str = str.Replace("&#x20;", space) str = str.Replace("&#xD;", vbCr) str = str.Replace("&#xA;", vbLf) str = str.Replace("&#x9;", vbTab) Return str End Function ' Dev11 treats p:xmlns="..." as an xmlns declaration for the default ' namespace. Roslyn issues warnings for these cases and only considers ' p:xmlns="..." an xmlns declaration if 'p' maps to the default namespace. <WorkItem(544366, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544366")> <Fact()> Public Sub PrefixAndXmlnsLocalName() Dim compilation = CompileAndVerify( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports System Imports System.Xml.Linq Imports <xmlns="N0"> Imports <xmlns:p1=""> Imports <xmlns:p2="N2"> Module M Sub Main() Report(<x1 p1:a="b"/>) Report(<x2 p2:a="b"/>) Report(<y1 p1:xmlns="A1"/>) Report(<y2 p2:xmlns="A2"/>) Report(<y3 xmlns:p3="N3" p3:xmlns="A3"/>) End Sub Sub Report(x As XElement) Console.WriteLine("{0}: {1}", x.Name, x) For Each a In x.Attributes Console.WriteLine(" {0}", a.Name) Next End Sub End Module ]]></file> </compilation>, references:=Net40XmlReferences, expectedOutput:=<![CDATA[ {N0}x1: <x1 a="b" xmlns="N0" /> a xmlns {N0}x2: <x2 p2:a="b" xmlns:p2="N2" xmlns="N0" /> {N2}a {http://www.w3.org/2000/xmlns/}p2 xmlns {A1}y1: <y1 xmlns="A1" /> xmlns {N0}y2: <y2 p2:xmlns="A2" xmlns:p2="N2" xmlns="N0" /> {N2}xmlns {http://www.w3.org/2000/xmlns/}p2 xmlns {N0}y3: <y3 xmlns:p3="N3" p3:xmlns="A3" xmlns="N0" /> {http://www.w3.org/2000/xmlns/}p3 {N3}xmlns xmlns ]]>) compilation.Compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC42368: The xmlns attribute has special meaning and should not be written with a prefix. Report(<y1 p1:xmlns="A1"/>) ~~~~~~~~ BC42360: It is not recommended to have attributes named xmlns. Did you mean to write 'xmlns:p2' to define a prefix named 'p2'? Report(<y2 p2:xmlns="A2"/>) ~~~~~~~~ BC42360: It is not recommended to have attributes named xmlns. Did you mean to write 'xmlns:p3' to define a prefix named 'p3'? Report(<y3 xmlns:p3="N3" p3:xmlns="A3"/>) ~~~~~~~~ ]]></errors>) End Sub ' BC42361 is a warning only and should not prevent code gen. <Fact()> Public Sub BC42361WRN_UseValueForXmlExpression3() Dim compilation = CompileAndVerify( <compilation> <file name="c.vb"><![CDATA[ Option Strict Off Module M Sub Main() System.Console.WriteLine("{0}", If(TryCast(<x/>.<y>, String), "[Nothing]")) End Sub End Module ]]></file> </compilation>, references:=Net40XmlReferences, expectedOutput:=<![CDATA[ [Nothing] ]]>) compilation.Compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC42361: Cannot convert 'IEnumerable(Of XElement)' to 'String'. You can use the 'Value' property to get the string value of the first element of 'IEnumerable(Of XElement)'. System.Console.WriteLine("{0}", If(TryCast(<x/>.<y>, String), "[Nothing]")) ~~~~~~~~ ]]></errors>) End Sub <Fact()> Public Sub UseLocallyRedefinedImport() Dim compilation = CompileAndVerify( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports <xmlns:p="http://roslyn/"> Module M Sub Main() ' Local declaration never used. Report(<x0 xmlns:p="http://roslyn/" a="b"/>) ' Local declaration used at root. Report(<x1 xmlns:p="http://roslyn/" p:a="b"/>) ' Local declaration used beneath root. Report(<x2 xmlns:p="http://roslyn/"> <y p:a="b"/> </x2>) ' Local declaration defined and used beneath root. Report(<x3> <y xmlns:p="http://roslyn/" p:a="b"/> </x3>) ' Local declaration defined beneath root and used below. Report(<x4> <y xmlns:p="http://roslyn/"> <z p:a="b"/> </y> </x4>) ' Local declaration defined beneath root and used on sibling. Report(<x5> <y xmlns:p="http://roslyn/"/> <z p:a="b"/> </x5>) ' Local declaration re-defined at root. Report(<x6 xmlns:p="http://roslyn/other" p:a="b"/>) ' Local declaration re-defined beneath root. Report(<x7> <y xmlns:p="http://roslyn/other" p:a="b"/> </x7>) ' Local declaration defined and re-defined. Report(<x8 xmlns:p="http://roslyn/" p:a1="b1"> <y xmlns:p="http://roslyn/other" p:a2="b2"> <z xmlns:p="http://roslyn/" p:a3="b3"/> </y> </x8>) End Sub Sub Report(o As Object) System.Console.WriteLine("{0}", o) End Sub End Module ]]></file> </compilation>, references:=Net40XmlReferences, expectedOutput:=<![CDATA[ <x0 a="b" xmlns:p="http://roslyn/" /> <x1 p:a="b" xmlns:p="http://roslyn/" /> <x2 xmlns:p="http://roslyn/"> <y p:a="b" /> </x2> <x3 xmlns:p="http://roslyn/"> <y p:a="b" /> </x3> <x4 xmlns:p="http://roslyn/"> <y> <z p:a="b" /> </y> </x4> <x5 xmlns:p="http://roslyn/"> <y /> <z p:a="b" /> </x5> <x6 xmlns:p="http://roslyn/other" p:a="b" /> <x7> <y xmlns:p="http://roslyn/other" p:a="b" /> </x7> <x8 p:a1="b1" xmlns:p="http://roslyn/"> <y xmlns:p="http://roslyn/other" p:a2="b2"> <z xmlns:p="http://roslyn/" p:a3="b3" /> </y> </x8> ]]>) End Sub ' If the xmlns attribute is a re-definition of an Imports xmlns ' declaration, the attribute should be created with CreateNamespaceAttribute ' (so the attribute can be removed if the element is embedded). ' Otherwise, the attribute should be created with XAttribute .ctor. <Fact()> Public Sub ConstructingXmlnsAttributes() ' The only difference between b.vb and c.vb is that c.vb ' contains an Imports <xmlns:...> declaration that matches ' the explicit xmlns declaration within the XElement. Dim compilation = CompileAndVerify( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Partial Class C Shared Sub Main() M1() M2() End Sub Shared Sub Report(o As Object) System.Console.WriteLine("{0}", o) End Sub End Class ]]></file> <file name="b.vb"><![CDATA[ Option Strict On Partial Class C Shared Sub M1() Report(<x xmlns:p="http://roslyn/"/>) End Sub End Class ]]></file> <file name="c.vb"><![CDATA[ Option Strict On Imports <xmlns:p="http://roslyn/"> Partial Class C Shared Sub M2() Report(<x xmlns:p="http://roslyn/"/>) End Sub End Class ]]></file> </compilation>, references:=Net40XmlReferences, expectedOutput:=<![CDATA[ <x xmlns:p="http://roslyn/" /> <x xmlns:p="http://roslyn/" /> ]]>) ' If no matching Imports, use XAttribute .ctor. compilation.VerifyIL("C.M1()", <![CDATA[ { // Code size 57 (0x39) .maxstack 4 IL_0000: ldstr "x" IL_0005: ldstr "" IL_000a: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_000f: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_0014: dup IL_0015: ldstr "p" IL_001a: ldstr "http://www.w3.org/2000/xmlns/" IL_001f: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0024: ldstr "http://roslyn/" IL_0029: newobj "Sub System.Xml.Linq.XAttribute..ctor(System.Xml.Linq.XName, Object)" IL_002e: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_0033: call "Sub C.Report(Object)" IL_0038: ret } ]]>) ' If matching Imports, use CreateNamespaceAttribute. compilation.VerifyIL("C.M2()", <![CDATA[ { // Code size 62 (0x3e) .maxstack 4 IL_0000: ldstr "x" IL_0005: ldstr "" IL_000a: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_000f: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_0014: dup IL_0015: ldstr "p" IL_001a: ldstr "http://www.w3.org/2000/xmlns/" IL_001f: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0024: ldstr "http://roslyn/" IL_0029: call "Function System.Xml.Linq.XNamespace.Get(String) As System.Xml.Linq.XNamespace" IL_002e: call "Function My.InternalXmlHelper.CreateNamespaceAttribute(System.Xml.Linq.XName, System.Xml.Linq.XNamespace) As System.Xml.Linq.XAttribute" IL_0033: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_0038: call "Sub C.Report(Object)" IL_003d: ret } ]]>) End Sub <WorkItem(545345, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545345")> <Fact()> Public Sub RemoveExistingNamespaceAttribute() Dim compilation = CompileAndVerify( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports System.Xml.Linq Imports <xmlns:p="http://roslyn/p"> Partial Class C Shared Function F1() As XElement Return <p:y/> End Function Shared Sub Main() Report(<x xmlns:p="http://roslyn/p"><%= F1() %></x>) Report(<x xmlns:p="http://roslyn/q"><%= F1() %></x>) Report(<x xmlns:p="http://roslyn/q"><%= F2() %></x>) Report(<x xmlns:q="http://roslyn/q"><%= F2() %></x>) Report(<x xmlns:p="http://Roslyn/p"><%= F1() %></x>) End Sub Shared Sub Report(x As XElement) System.Console.WriteLine("{0}", x) End Sub End Class ]]></file> <file name="b.vb"><![CDATA[ Option Strict On Imports System.Xml.Linq Imports <xmlns:q="http://roslyn/q"> Partial Class C Shared Function F2() As XElement Return <q:y/> End Function End Class ]]></file> </compilation>, references:=Net40XmlReferences, expectedOutput:=<![CDATA[ <x xmlns:p="http://roslyn/p"> <p:y /> </x> <x xmlns:p="http://roslyn/q"> <p:y xmlns:p="http://roslyn/p" /> </x> <x xmlns:p="http://roslyn/q" xmlns:q="http://roslyn/q"> <q:y /> </x> <x xmlns:q="http://roslyn/q"> <q:y /> </x> <x xmlns:p="http://Roslyn/p"> <p:y xmlns:p="http://roslyn/p" /> </x> ]]>) End Sub <Fact()> Public Sub DefaultAndEmptyNamespaces_1() Dim compilation = CompileAndVerify( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports <xmlns=""> Imports <xmlns:e=""> Module M Sub Main() Report(<x e:a="1"/>) Report(<e:x a="1"/>) Report(<e:x><y/></e:x>) Report(<x><e:y/></x>) End Sub Sub Report(o As Object) System.Console.WriteLine("{0}", o) End Sub End Module ]]></file> </compilation>, references:=Net40XmlReferences, expectedOutput:=<![CDATA[ <x a="1" /> <x a="1" xmlns="" /> <x xmlns=""> <y /> </x> <x xmlns=""> <y /> </x> ]]>) End Sub <WorkItem(545401, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545401")> <Fact()> Public Sub DefaultAndEmptyNamespaces_2() Dim compilation = CompileAndVerify( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports <xmlns="default"> Imports <xmlns:e=""> Imports <xmlns:p="ns"> Module M Sub Main() Report(<x e:a="1" p:b="2"/>) Report(<e:x a="1" p:b="2"/>) Report(<p:x e:a="1" b="2"/>) Report(<e:x><y/><p:z/></e:x>) Report(<x><e:y/><p:z/></x>) Report(<p:x><e:y/><z/></p:x>) End Sub Sub Report(o As Object) System.Console.WriteLine("{0}", o) End Sub End Module ]]></file> </compilation>, references:=Net40XmlReferences, expectedOutput:=<![CDATA[ <x a="1" p:b="2" xmlns:p="ns" xmlns="default" /> <x a="1" p:b="2" xmlns:p="ns" xmlns="" /> <p:x a="1" b="2" xmlns:p="ns" /> <x xmlns:p="ns" xmlns=""> <y xmlns="default" /> <p:z /> </x> <x xmlns:p="ns" xmlns="default"> <y xmlns="" /> <p:z /> </x> <p:x xmlns="" xmlns:p="ns"> <y /> <z xmlns="default" /> </p:x> ]]>) End Sub ''' <summary> ''' Should not call RemoveNamespaceAttributes ''' on intrinsic types or enums. ''' </summary> <WorkItem(546191, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546191")> <Fact()> Public Sub RemoveNamespaceAttributes_OtherContentTypes() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"><![CDATA[ Imports System Imports <xmlns:p="http://roslyn"> Enum E A End Enum Structure S End Structure Class C(Of T) Private _1 As Object = Nothing Private _2 As Boolean = False Private _3 As Byte = 0 Private _4 As SByte = 0 Private _5 As Int16 = 0 Private _6 As UInt16 = 0 Private _7 As Int32 = 0 Private _8 As UInt32 = 0 Private _9 As Int64 = 0 Private _10 As UInt64 = 0 Private _11 As Single = 0 Private _12 As Double = 0 Private _13 As Decimal = 0 Private _14 As DateTime = Nothing Private _15 As Char = Nothing Private _16 As String = "" Private _17 As E = E.A Private _18 As Integer? = Nothing Private _19 As S = Nothing Private _20 As T = Nothing Private _21 As ValueType = E.A Private _22 As System.Enum = E.A Private _23 As Object() = Nothing Private _24 As Array = Nothing Function F1() As Object Return <x><%= _1 %></x> End Function Function F2() As Object Return <x><%= _2 %></x> End Function Function F3() As Object Return <x><%= _3 %></x> End Function Function F4() As Object Return <x><%= _4 %></x> End Function Function F5() As Object Return <x><%= _5 %></x> End Function Function F6() As Object Return <x><%= _6 %></x> End Function Function F7() As Object Return <x><%= _7 %></x> End Function Function F8() As Object Return <x><%= _8 %></x> End Function Function F9() As Object Return <x><%= _9 %></x> End Function Function F10() As Object Return <x><%= _10 %></x> End Function Function F11() As Object Return <x><%= _11 %></x> End Function Function F12() As Object Return <x><%= _12 %></x> End Function Function F13() As Object Return <x><%= _13 %></x> End Function Function F14() As Object Return <x><%= _14 %></x> End Function Function F15() As Object Return <x><%= _15 %></x> End Function Function F16() As Object Return <x><%= _16 %></x> End Function Function F17() As Object Return <x><%= _17 %></x> End Function Function F18() As Object Return <x><%= _18 %></x> End Function Function F19() As Object Return <x><%= _19 %></x> End Function Function F20() As Object Return <x><%= _20 %></x> End Function Function F21() As Object Return <x><%= _21 %></x> End Function Function F22() As Object Return <x><%= _22 %></x> End Function Function F23() As Object Return <x><%= _23 %></x> End Function Function F24() As Object Return <x><%= _24 %></x> End Function End Class ]]></file> </compilation>, references:=Net40XmlReferences) Assert.True(CallsRemoveNamespaceAttributes(verifier.VisualizeIL("C(Of T).F1()"))) Assert.False(CallsRemoveNamespaceAttributes(verifier.VisualizeIL("C(Of T).F2()"))) Assert.False(CallsRemoveNamespaceAttributes(verifier.VisualizeIL("C(Of T).F3()"))) Assert.False(CallsRemoveNamespaceAttributes(verifier.VisualizeIL("C(Of T).F4()"))) Assert.False(CallsRemoveNamespaceAttributes(verifier.VisualizeIL("C(Of T).F5()"))) Assert.False(CallsRemoveNamespaceAttributes(verifier.VisualizeIL("C(Of T).F6()"))) Assert.False(CallsRemoveNamespaceAttributes(verifier.VisualizeIL("C(Of T).F7()"))) Assert.False(CallsRemoveNamespaceAttributes(verifier.VisualizeIL("C(Of T).F8()"))) Assert.False(CallsRemoveNamespaceAttributes(verifier.VisualizeIL("C(Of T).F9()"))) Assert.False(CallsRemoveNamespaceAttributes(verifier.VisualizeIL("C(Of T).F10()"))) Assert.False(CallsRemoveNamespaceAttributes(verifier.VisualizeIL("C(Of T).F11()"))) Assert.False(CallsRemoveNamespaceAttributes(verifier.VisualizeIL("C(Of T).F12()"))) Assert.False(CallsRemoveNamespaceAttributes(verifier.VisualizeIL("C(Of T).F13()"))) Assert.False(CallsRemoveNamespaceAttributes(verifier.VisualizeIL("C(Of T).F14()"))) Assert.False(CallsRemoveNamespaceAttributes(verifier.VisualizeIL("C(Of T).F15()"))) Assert.False(CallsRemoveNamespaceAttributes(verifier.VisualizeIL("C(Of T).F16()"))) Assert.False(CallsRemoveNamespaceAttributes(verifier.VisualizeIL("C(Of T).F17()"))) Assert.True(CallsRemoveNamespaceAttributes(verifier.VisualizeIL("C(Of T).F18()"))) Assert.True(CallsRemoveNamespaceAttributes(verifier.VisualizeIL("C(Of T).F19()"))) Assert.True(CallsRemoveNamespaceAttributes(verifier.VisualizeIL("C(Of T).F20()"))) Assert.True(CallsRemoveNamespaceAttributes(verifier.VisualizeIL("C(Of T).F21()"))) Assert.True(CallsRemoveNamespaceAttributes(verifier.VisualizeIL("C(Of T).F22()"))) Assert.True(CallsRemoveNamespaceAttributes(verifier.VisualizeIL("C(Of T).F23()"))) Assert.True(CallsRemoveNamespaceAttributes(verifier.VisualizeIL("C(Of T).F24()"))) End Sub ''' <summary> ''' Should not call RemoveNamespaceAttributes ''' unless there are xmlns Imports in scope. ''' </summary> <WorkItem(546191, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546191")> <Fact()> Public Sub RemoveNamespaceAttributes_XmlnsInScope() ' No xmlns. Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"><![CDATA[ Imports System.Xml.Linq Module M Function F1() As XElement Return <x><%= F2() %></x> End Function Function F2() As XElement Return <y/> End Function End Module ]]></file> </compilation>, references:=Net40XmlReferences) Assert.False(CallsRemoveNamespaceAttributes(verifier.VisualizeIL("M.F1()"))) ' xmlns attribute. verifier = CompileAndVerify( <compilation> <file name="a.vb"><![CDATA[ Imports System.Xml.Linq Module M Function F1() As XElement Return <x xmlns:p="http://roslyn"><%= F2() %></x> End Function Function F2() As XElement Return <y/> End Function End Module ]]></file> </compilation>, references:=Net40XmlReferences) Assert.False(CallsRemoveNamespaceAttributes(verifier.VisualizeIL("M.F1()"))) ' Imports <...> in file. verifier = CompileAndVerify( <compilation> <file name="a.vb"><![CDATA[ Imports System.Xml.Linq Imports <xmlns:p="http://roslyn"> Module M Function F1() As XElement Return <x><%= F2() %></x> End Function Function F2() As XElement Return <y/> End Function End Module ]]></file> </compilation>, references:=Net40XmlReferences) Assert.True(CallsRemoveNamespaceAttributes(verifier.VisualizeIL("M.F1()"))) ' Imports <...> at project scope. Dim options = TestOptions.ReleaseDll.WithGlobalImports(GlobalImport.Parse({"<xmlns:p=""http://roslyn"">"})) verifier = CompileAndVerify( <compilation> <file name="c.vb"><![CDATA[ Imports System.Xml.Linq Module M Function F1() As XElement Return <x><%= F2() %></x> End Function Function F2() As XElement Return <y/> End Function End Module ]]></file> </compilation>, references:=Net40XmlReferences, options:=options) Assert.True(CallsRemoveNamespaceAttributes(verifier.VisualizeIL("M.F1()"))) End Sub Private Function CallsRemoveNamespaceAttributes(actualIL As String) As Boolean Return actualIL.Contains("My.InternalXmlHelper.RemoveNamespaceAttributes") End Function <WorkItem(546480, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546480")> <Fact()> Public Sub OpenCloseTag() Dim compilation = CompileAndVerify( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports System.Linq Imports System.Xml.Linq Module M Sub Main() Report(<x/>) Report(<x></>) Report(<x> </>) Report(<x> </>) Report(<x><!-- --></>) Report(<x> <!----> <!----> </>) Report(<x> <y/> </>) End Sub Sub Report(x As XElement) System.Console.WriteLine("[{0}] {1}", x.Nodes.Count(), x) End Sub End Module ]]></file> </compilation>, references:=Net40XmlReferences, expectedOutput:=<![CDATA[ [0] <x /> [0] <x></x> [0] <x></x> [0] <x></x> [1] <x> <!-- --> </x> [2] <x> <!----> <!----> </x> [1] <x> <y /> </x> ]]>) End Sub <Fact(), WorkItem(530882, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530882")> Public Sub SelectFromIEnumerableOfXElementMultitargetingNetFX35() Dim source = <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports System Imports System.Linq Imports System.Xml.Linq Module Module1 Dim stuff As XElement = <root> <output someattrib="goo1"> <value>1</value> </output> <output> <value>2</value> </output> </root> Sub Main() For Each value In stuff.<output>.<value> Console.WriteLine(value.Value) Next dim stuffArray() as XElement = {stuff, stuff} for each value in stuffArray.<output> Console.WriteLine(value.Value) next Console.WriteLine(stuff.<output>.@someattrib) End Sub End Module]]> </file> </compilation> Dim comp = CreateEmptyCompilationWithReferences( source, references:={MscorlibRef_v20, SystemRef_v20, MsvbRef, SystemXmlRef, SystemXmlLinqRef, SystemCoreRef}, options:=TestOptions.ReleaseExe.WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default)) CompileAndVerify(comp, expectedOutput:="1" & Environment.NewLine & "2" & Environment.NewLine & "1" & Environment.NewLine & "2" & Environment.NewLine & "1" & Environment.NewLine & "2" & Environment.NewLine & "goo1") End Sub <Fact(), WorkItem(530882, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530882")> Public Sub SelectFromIEnumerableOfXElementMultitargetingNetFX35_Errors() Dim source = <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports System Module Module1 Sub Main() Dim objArray() As Object = {New Object(), New Object()} For Each value In objArray.<output> Next Console.WriteLine(objArray.@someAttrib) End Sub End Module ]]></file> </compilation> Dim comp = CreateEmptyCompilationWithReferences( source, references:={MscorlibRef_v20, SystemRef_v20, MsvbRef, SystemXmlRef, SystemXmlLinqRef, SystemCoreRef}, options:=TestOptions.ReleaseExe.WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default)) VerifyDiagnostics(comp, Diagnostic(ERRID.ERR_TypeDisallowsElements, "objArray.<output>").WithArguments("Object()"), Diagnostic(ERRID.ERR_TypeDisallowsAttributes, "objArray.@someAttrib").WithArguments("Object()")) End Sub <Fact(), WorkItem(531351, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531351")> Public Sub Bug17985() Dim compilation = CompileAndVerify( <compilation> <file name="c.vb"><![CDATA[ Imports System.Xml.Linq Class scen1(Of T As XElement) Sub goo(ByVal o As T) Dim res = o.<moo> End Sub End Class ]]></file> </compilation>, references:=Net40XmlReferences, options:=TestOptions.ReleaseDll). VerifyIL("scen1(Of T).goo(T)", <![CDATA[ { // Code size 30 (0x1e) .maxstack 3 IL_0000: ldarga.s V_1 IL_0002: ldstr "moo" IL_0007: ldstr "" IL_000c: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0011: constrained. "T" IL_0017: callvirt "Function System.Xml.Linq.XContainer.Elements(System.Xml.Linq.XName) As System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)" IL_001c: pop IL_001d: ret } ]]>) End Sub <WorkItem(531445, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531445")> <WorkItem(101597, "https://devdiv.visualstudio.com/defaultcollection/DevDiv/_workitems#_a=edit&id=101597")> <Fact> Public Sub SameNamespaceDifferentPrefixes() Dim options = TestOptions.ReleaseExe.WithGlobalImports(GlobalImport.Parse({"<xmlns:r=""http://roslyn/"">", "<xmlns:s=""http://roslyn/"">"})) Dim expectedOutput As Xml.Linq.XCData Const bug101597IsFixed = False If bug101597IsFixed Then expectedOutput = <![CDATA[ <p:x xmlns:s="http://roslyn/" xmlns:r="http://roslyn/" xmlns:q="http://roslyn/" xmlns:p="http://roslyn/"> <p:y p:a="" p:b="" /> </p:x> ]]> Else expectedOutput = <![CDATA[ <q:x xmlns:p="http://roslyn/" xmlns:s="http://roslyn/" xmlns:r="http://roslyn/" xmlns:q="http://roslyn/"> <q:y q:a="" q:b="" /> </q:x> ]]> End If Dim compilation = CompileAndVerify( <compilation> <file name="a.vb"><![CDATA[ Imports <xmlns:p="http://roslyn/"> Imports <xmlns:q="http://roslyn/"> Module M Sub Main() Dim x = <p:x> <%= <q:y r:a="" s:b=""/> %> </p:x> System.Console.WriteLine("{0}", x) End Sub End Module ]]></file> </compilation>, references:=Net40XmlReferences, options:=options, expectedOutput:=expectedOutput) End Sub <WorkItem(623035, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/623035")> <Fact()> Public Sub Bug623035() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="a.vb"><![CDATA[ Friend Module Program Sub Main() Dim o2 As Object = "E" o2 = System.Xml.Linq.XName.Get("HELLO") Dim y2 = <<%= o2 %>></> System.Console.WriteLine(y2) End Sub End Module ]]></file> </compilation>, Net40XmlReferences, TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.Off)) CompileAndVerify(compilation, <![CDATA[ <HELLO></HELLO> ]]>) compilation = compilation.WithOptions(compilation.Options.WithOptionStrict(OptionStrict.Custom)) CompileAndVerify(compilation, <![CDATA[ <HELLO></HELLO> ]]>) compilation = compilation.WithOptions(compilation.Options.WithOptionStrict(OptionStrict.On)) AssertTheseDiagnostics(compilation, <expected><![CDATA[ BC30518: Overload resolution failed because no accessible 'New' can be called with these arguments: 'Public Overloads Sub New(name As XName)': Option Strict On disallows implicit conversions from 'Object' to 'XName'. 'Public Overloads Sub New(other As XElement)': Option Strict On disallows implicit conversions from 'Object' to 'XElement'. 'Public Overloads Sub New(other As XStreamingElement)': Option Strict On disallows implicit conversions from 'Object' to 'XStreamingElement'. Dim y2 = <<%= o2 %>></> ~~~~~~~~~ ]]></expected>) End Sub <WorkItem(631047, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/631047")> <Fact()> Public Sub Regress631047() CompileAndVerify( <compilation> <file name="a.vb"> <![CDATA[ Imports System Module Program Sub Main() Console.Write(<?goo                       ?>.ToString() = "<?goo                       ?>") End Sub End Module ]]> </file> </compilation>, references:=Net40XmlReferences, expectedOutput:=<![CDATA[True]]>) End Sub <WorkItem(814075, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/814075")> <Fact()> Public Sub ExpressionTreeContainingExtensionProperty() Dim compilation = CompileAndVerify( <compilation> <file name="c.vb"><![CDATA[ Imports System Imports System.Linq.Expressions Imports System.Xml.Linq Module M Sub Main() M(Function(x) x.<y>.Value) End Sub Sub M(e As Expression(Of Func(Of XElement, String))) Console.WriteLine(e) Dim c = e.Compile() Dim s = c.Invoke(<x><y>content</></>) Console.WriteLine(s) End Sub End Module ]]></file> </compilation>, references:=Net40XmlReferences, expectedOutput:=<![CDATA[ x => get_Value(x.Elements(Get("y", ""))) content ]]>) compilation.VerifyIL("M.Main", <![CDATA[ { // Code size 175 (0xaf) .maxstack 17 .locals init (System.Linq.Expressions.ParameterExpression V_0) IL_0000: ldtoken "System.Xml.Linq.XElement" IL_0005: call "Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type" IL_000a: ldstr "x" IL_000f: call "Function System.Linq.Expressions.Expression.Parameter(System.Type, String) As System.Linq.Expressions.ParameterExpression" IL_0014: stloc.0 IL_0015: ldnull IL_0016: ldtoken "Function My.InternalXmlHelper.get_Value(System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)) As String" IL_001b: call "Function System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle) As System.Reflection.MethodBase" IL_0020: castclass "System.Reflection.MethodInfo" IL_0025: ldc.i4.1 IL_0026: newarr "System.Linq.Expressions.Expression" IL_002b: dup IL_002c: ldc.i4.0 IL_002d: ldloc.0 IL_002e: ldtoken "Function System.Xml.Linq.XContainer.Elements(System.Xml.Linq.XName) As System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)" IL_0033: call "Function System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle) As System.Reflection.MethodBase" IL_0038: castclass "System.Reflection.MethodInfo" IL_003d: ldc.i4.1 IL_003e: newarr "System.Linq.Expressions.Expression" IL_0043: dup IL_0044: ldc.i4.0 IL_0045: ldnull IL_0046: ldtoken "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_004b: call "Function System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle) As System.Reflection.MethodBase" IL_0050: castclass "System.Reflection.MethodInfo" IL_0055: ldc.i4.2 IL_0056: newarr "System.Linq.Expressions.Expression" IL_005b: dup IL_005c: ldc.i4.0 IL_005d: ldstr "y" IL_0062: ldtoken "String" IL_0067: call "Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type" IL_006c: call "Function System.Linq.Expressions.Expression.Constant(Object, System.Type) As System.Linq.Expressions.ConstantExpression" IL_0071: stelem.ref IL_0072: dup IL_0073: ldc.i4.1 IL_0074: ldstr "" IL_0079: ldtoken "String" IL_007e: call "Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type" IL_0083: call "Function System.Linq.Expressions.Expression.Constant(Object, System.Type) As System.Linq.Expressions.ConstantExpression" IL_0088: stelem.ref IL_0089: call "Function System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, ParamArray System.Linq.Expressions.Expression()) As System.Linq.Expressions.MethodCallExpression" IL_008e: stelem.ref IL_008f: call "Function System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, ParamArray System.Linq.Expressions.Expression()) As System.Linq.Expressions.MethodCallExpression" IL_0094: stelem.ref IL_0095: call "Function System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, ParamArray System.Linq.Expressions.Expression()) As System.Linq.Expressions.MethodCallExpression" IL_009a: ldc.i4.1 IL_009b: newarr "System.Linq.Expressions.ParameterExpression" IL_00a0: dup IL_00a1: ldc.i4.0 IL_00a2: ldloc.0 IL_00a3: stelem.ref IL_00a4: call "Function System.Linq.Expressions.Expression.Lambda(Of System.Func(Of System.Xml.Linq.XElement, String))(System.Linq.Expressions.Expression, ParamArray System.Linq.Expressions.ParameterExpression()) As System.Linq.Expressions.Expression(Of System.Func(Of System.Xml.Linq.XElement, String))" IL_00a9: call "Sub M.M(System.Linq.Expressions.Expression(Of System.Func(Of System.Xml.Linq.XElement, String)))" IL_00ae: ret } ]]>) End Sub <WorkItem(814052, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/814052")> <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub XmlnsNamespaceTooLong() Dim identifier = New String("a"c, MetadataWriter.PdbLengthLimit) XmlnsNamespaceTooLongCore(identifier.Substring(6), tooLong:=False) XmlnsNamespaceTooLongCore(identifier, tooLong:=True) End Sub Private Sub XmlnsNamespaceTooLongCore(identifier As String, tooLong As Boolean) Dim [imports] = GlobalImport.Parse({String.Format("<xmlns:p=""{0}"">", identifier)}) Dim options = TestOptions.DebugDll.WithGlobalImports([imports]) Dim source = String.Format(<![CDATA[ Imports <xmlns="{0}"> Imports <xmlns:q="{0}"> Module M Private F As Object = <x xmlns="{0}" xmlns:r="{0}" p:a="{0}" q:b="" /> End Module ]]>.Value, identifier) Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation><file name="c.vb"><%= source %></file></compilation>, references:=Net40XmlReferences, options:=options) If Not tooLong Then compilation.AssertTheseDiagnostics(<errors/>) compilation.AssertTheseEmitDiagnostics(<errors/>) Else Dim squiggles = New String("~"c, identifier.Length) Dim errors = String.Format(<![CDATA[ BC42374: Import string '@FX:={0}' is too long for PDB. Consider shortening or compiling without /debug. Module M ~ BC42374: Import string '@FX:q={0}' is too long for PDB. Consider shortening or compiling without /debug. Module M ~ BC42374: Import string '@PX:p={0}' is too long for PDB. Consider shortening or compiling without /debug. Module M ~ ]]>.Value, identifier) compilation.AssertTheseDiagnostics(<errors/>) compilation.AssertTheseEmitDiagnostics(<errors><%= errors %></errors>) End If End Sub ''' <summary> ''' Constant embedded expression with duplicate xmlns attribute. ''' </summary> <WorkItem(863159, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/863159")> <Fact()> Public Sub XmlnsPrefixUsedInEmbeddedExpressionAndSibling_Constant() CompileAndVerify( <compilation> <file name="a.vb"><![CDATA[ Imports <xmlns:p="http://roslyn/"> Module M Sub Main() Dim x = <x> <y> <%= <p:z/> %> </y> <p:z/> </x> System.Console.WriteLine("{0}", x) End Sub End Module ]]></file> </compilation>, references:=Net40XmlReferences, expectedOutput:=<![CDATA[ <x xmlns:p="http://roslyn/"> <y> <p:z /> </y> <p:z /> </x> ]]>) End Sub ''' <summary> ''' Non-constant embedded expression with duplicate xmlns attribute. ''' </summary> <WorkItem(863159, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/863159")> <Fact()> Public Sub XmlnsPrefixUsedInEmbeddedExpressionAndSibling_NonConstant() ' Dev12 generates code that throws "InvalidOperationException: Duplicate attribute". Dim compilation = CompileAndVerify( <compilation> <file name="a.vb"><![CDATA[ Imports <xmlns:p="http://roslyn/p"> Imports <xmlns:q="http://roslyn/q"> Imports <xmlns:r="http://roslyn/r"> Class A Friend Shared Function F() As System.Xml.Linq.XElement Return <a> <p:x/> <q:y/> <r:z/> </> End Function End Class ]]></file> <file name="b.vb"><![CDATA[ Imports <xmlns:p="http://roslyn/q"> Imports <xmlns:q="http://roslyn/p"> Class B Friend Shared Function F() As System.Xml.Linq.XElement Return <b> <p:x/> <q:y/> </> End Function End Class ]]></file> <file name="c.vb"><![CDATA[ Imports System Imports <xmlns:p="http://roslyn/p"> Imports <xmlns:q="http://roslyn/q"> Class C Shared Sub Main() Console.WriteLine(<x> <y> <%= A.F() %> </> <z> <%= B.F() %> </> </>) Console.WriteLine(<x> <y> <%= A.F() %> <%= B.F() %> </> <p:z> <%= A.F() %> <%= B.F() %> </> </>) Console.WriteLine(<x> <p:y> <%= A.F() %> <%= B.F() %> </> <z> <%= A.F() %> <%= B.F() %> </> </>) Console.WriteLine(<x> <p:y> <%= A.F() %> <%= B.F() %> </> <q:z> <%= A.F() %> <%= B.F() %> </> </>) Console.WriteLine(<x> <p:y> <%= B.F() %> <%= A.F() %> </> <q:z xmlns:q="http://roslyn/q"> <%= A.F() %> <%= B.F() %> </> </>) Console.WriteLine(<x xmlns:q="http://roslyn/q"> <p:y xmlns:p="http://roslyn/p"> <%= B.F() %> <%= A.F() %> </> <z> <%= A.F() %> <%= B.F() %> </> </>) Console.WriteLine(<x> <p:y xmlns:p="http://roslyn/p"> <%= B.F() %> <%= A.F() %> </> <q:z> <%= A.F() %> <%= B.F() %> </> </>) End Sub End Class ]]></file> </compilation>, references:=Net40XmlReferences, expectedOutput:=<![CDATA[ <x xmlns:r="http://roslyn/r" xmlns:q="http://roslyn/q" xmlns:p="http://roslyn/p"> <y> <a> <p:x /> <q:y /> <r:z /> </a> </y> <z> <b xmlns:q="http://roslyn/p" xmlns:p="http://roslyn/q"> <p:x /> <q:y /> </b> </z> </x> <x xmlns:p="http://roslyn/p" xmlns:r="http://roslyn/r" xmlns:q="http://roslyn/q"> <y> <a> <p:x /> <q:y /> <r:z /> </a> <b xmlns:q="http://roslyn/p" xmlns:p="http://roslyn/q"> <p:x /> <q:y /> </b> </y> <p:z> <a> <p:x /> <q:y /> <r:z /> </a> <b xmlns:q="http://roslyn/p" xmlns:p="http://roslyn/q"> <p:x /> <q:y /> </b> </p:z> </x> <x xmlns:p="http://roslyn/p" xmlns:r="http://roslyn/r" xmlns:q="http://roslyn/q"> <p:y> <a> <p:x /> <q:y /> <r:z /> </a> <b xmlns:q="http://roslyn/p" xmlns:p="http://roslyn/q"> <p:x /> <q:y /> </b> </p:y> <z> <a> <p:x /> <q:y /> <r:z /> </a> <b xmlns:q="http://roslyn/p" xmlns:p="http://roslyn/q"> <p:x /> <q:y /> </b> </z> </x> <x xmlns:q="http://roslyn/q" xmlns:p="http://roslyn/p" xmlns:r="http://roslyn/r"> <p:y> <a> <p:x /> <q:y /> <r:z /> </a> <b xmlns:q="http://roslyn/p" xmlns:p="http://roslyn/q"> <p:x /> <q:y /> </b> </p:y> <q:z> <a> <p:x /> <q:y /> <r:z /> </a> <b xmlns:q="http://roslyn/p" xmlns:p="http://roslyn/q"> <p:x /> <q:y /> </b> </q:z> </x> <x xmlns:q="http://roslyn/q" xmlns:p="http://roslyn/p" xmlns:r="http://roslyn/r"> <p:y> <b xmlns:q="http://roslyn/p" xmlns:p="http://roslyn/q"> <p:x /> <q:y /> </b> <a> <p:x /> <q:y /> <r:z /> </a> </p:y> <q:z> <a> <p:x /> <q:y /> <r:z /> </a> <b xmlns:q="http://roslyn/p" xmlns:p="http://roslyn/q"> <p:x /> <q:y /> </b> </q:z> </x> <x xmlns:p="http://roslyn/p" xmlns:q="http://roslyn/q" xmlns:r="http://roslyn/r"> <p:y> <b xmlns:q="http://roslyn/p" xmlns:p="http://roslyn/q"> <p:x /> <q:y /> </b> <a> <p:x /> <q:y /> <r:z /> </a> </p:y> <z> <a> <p:x /> <q:y /> <r:z /> </a> <b xmlns:q="http://roslyn/p" xmlns:p="http://roslyn/q"> <p:x /> <q:y /> </b> </z> </x> <x xmlns:q="http://roslyn/q" xmlns:p="http://roslyn/p" xmlns:r="http://roslyn/r"> <p:y> <b xmlns:q="http://roslyn/p" xmlns:p="http://roslyn/q"> <p:x /> <q:y /> </b> <a> <p:x /> <q:y /> <r:z /> </a> </p:y> <q:z> <a> <p:x /> <q:y /> <r:z /> </a> <b xmlns:q="http://roslyn/p" xmlns:p="http://roslyn/q"> <p:x /> <q:y /> </b> </q:z> </x> ]]>) End Sub <WorkItem(863159, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/863159")> <Fact()> Public Sub XmlnsPrefixUsedInEmbeddedExpressionAndSibling_ExpressionTree() CompileAndVerify( <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Linq.Expressions Imports System.Xml.Linq Imports <xmlns:p="http://roslyn/p"> Module M Function F() As XElement Return <p:z/> End Function Sub Main() Dim e As Expression(Of Func(Of Object)) = Function() <x xmlns:q="http://roslyn/q"> <y> <%= F() %> </y> <p:z/> </x> Dim c = e.Compile() Console.WriteLine(c()) End Sub End Module ]]></file> </compilation>, references:=Net40XmlReferences, expectedOutput:=<![CDATA[ <x xmlns:q="http://roslyn/q" xmlns:p="http://roslyn/p"> <y> <p:z /> </y> <p:z /> </x> ]]>) End Sub ''' <summary> ''' Should not traverse into embedded expressions ''' to determine set of used Imports. ''' </summary> <Fact()> Public Sub XmlnsPrefix_UnusedExpression() CompileAndVerify( <compilation> <file name="a.vb"><![CDATA[ Imports <xmlns:p="http://roslyn/p"> Imports <xmlns:q="http://roslyn/q"> Imports <xmlns:r="http://roslyn/r"> Imports System Imports System.Xml.Linq Module M Function F(x As XElement) As XElement Console.WriteLine(x) Return <r:z/> End Function Sub Main() Dim x = <p:x> <%= F(<q:y/>) %> </p:x> Console.WriteLine(x) End Sub End Module ]]></file> </compilation>, references:=Net40XmlReferences, expectedOutput:=<![CDATA[ <q:y xmlns:q="http://roslyn/q" /> <p:x xmlns:p="http://roslyn/p" xmlns:r="http://roslyn/r"> <r:z /> </p:x> ]]>) End Sub ''' <summary> ''' My.InternalXmlHelper should be emitted into the root namespace. ''' </summary> <Fact()> Public Sub InternalXmlHelper_RootNamespace() Const source = " Imports System Imports System.Xml.Linq Class C Sub M() Dim a = <element attr='value'/>.@attr End Sub End Class " Dim tree = VisualBasicSyntaxTree.ParseText(source) Dim refBuilder = ArrayBuilder(Of MetadataReference).GetInstance() refBuilder.Add(TestMetadata.Net40.mscorlib) refBuilder.Add(TestMetadata.Net40.System) refBuilder.Add(TestMetadata.Net40.MicrosoftVisualBasic) refBuilder.AddRange(Net40XmlReferences) Dim refs = refBuilder.ToImmutableAndFree() CompileAndVerify( CreateEmptyCompilationWithReferences(tree, refs, TestOptions.DebugDll), symbolValidator:= Sub(moduleSymbol) moduleSymbol.GlobalNamespace. GetMember(Of NamespaceSymbol)("My"). GetMember(Of NamedTypeSymbol)("InternalXmlHelper") End Sub) CompileAndVerify( CreateEmptyCompilationWithReferences(tree, refs, TestOptions.DebugDll.WithRootNamespace("Root")), symbolValidator:= Sub(moduleSymbol) moduleSymbol.GlobalNamespace. GetMember(Of NamespaceSymbol)("Root"). GetMember(Of NamespaceSymbol)("My"). GetMember(Of NamedTypeSymbol)("InternalXmlHelper") End Sub) End Sub End Class End Namespace
-1
dotnet/roslyn
56,011
React to string comparison changing on .NET Core
The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
jaredpar
"2021-08-30T17:18:52Z"
"2021-08-30T20:20:04Z"
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
4d99cda6e446e77dbb302e26388c1093bd3ef569
React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
./src/Workspaces/VisualBasic/Portable/OrganizeImports/VisualBasicOrganizeImportsService.Rewriter.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.OrganizeImports Partial Friend Class VisualBasicOrganizeImportsService Private Class Rewriter Inherits VisualBasicSyntaxRewriter Private ReadOnly _placeSystemNamespaceFirst As Boolean Private ReadOnly _separateGroups As Boolean Public ReadOnly TextChanges As IList(Of TextChange) = New List(Of TextChange)() Public Sub New(placeSystemNamespaceFirst As Boolean, separateGroups As Boolean) _placeSystemNamespaceFirst = placeSystemNamespaceFirst _separateGroups = separateGroups End Sub Public Overrides Function VisitCompilationUnit(node As CompilationUnitSyntax) As SyntaxNode node = DirectCast(MyBase.VisitCompilationUnit(node), CompilationUnitSyntax) Dim organizedImports = ImportsOrganizer.Organize( node.Imports, _placeSystemNamespaceFirst, _separateGroups) Dim result = node.WithImports(organizedImports) If result IsNot node Then AddTextChange(node.Imports, organizedImports) End If Return result End Function Public Overrides Function VisitImportsStatement(node As ImportsStatementSyntax) As SyntaxNode Dim organizedImportsClauses = ImportsOrganizer.Organize(node.ImportsClauses) Dim result = node.WithImportsClauses(organizedImportsClauses) If result IsNot node Then AddTextChange(node.ImportsClauses, organizedImportsClauses) End If Return result End Function Private Sub AddTextChange(Of TSyntax As SyntaxNode)(list As SeparatedSyntaxList(Of TSyntax), organizedList As SeparatedSyntaxList(Of TSyntax)) If list.Count > 0 Then Me.TextChanges.Add(New TextChange(GetTextSpan(list), GetNewText(organizedList))) End If End Sub Private Sub AddTextChange(Of TSyntax As SyntaxNode)(list As SyntaxList(Of TSyntax), organizedList As SyntaxList(Of TSyntax)) If list.Count > 0 Then Me.TextChanges.Add(New TextChange(GetTextSpan(list), GetNewText(organizedList))) End If End Sub Private Shared Function GetNewText(Of TSyntax As SyntaxNode)(organizedList As SyntaxList(Of TSyntax)) As String Return String.Join(String.Empty, organizedList.[Select](Function(t) t.ToFullString())) End Function Private Shared Function GetNewText(Of TSyntax As SyntaxNode)(organizedList As SeparatedSyntaxList(Of TSyntax)) As String Return String.Join(String.Empty, organizedList.GetWithSeparators().[Select](Function(t) t.ToFullString())) End Function Private Shared Function GetTextSpan(Of TSyntax As SyntaxNode)(list As SyntaxList(Of TSyntax)) As TextSpan Return TextSpan.FromBounds(list.First().FullSpan.Start, list.Last().FullSpan.[End]) End Function Private Shared Function GetTextSpan(Of TSyntax As SyntaxNode)(list As SeparatedSyntaxList(Of TSyntax)) As TextSpan Return TextSpan.FromBounds(list.First().FullSpan.Start, list.Last().FullSpan.[End]) End Function End Class End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.OrganizeImports Partial Friend Class VisualBasicOrganizeImportsService Private Class Rewriter Inherits VisualBasicSyntaxRewriter Private ReadOnly _placeSystemNamespaceFirst As Boolean Private ReadOnly _separateGroups As Boolean Public ReadOnly TextChanges As IList(Of TextChange) = New List(Of TextChange)() Public Sub New(placeSystemNamespaceFirst As Boolean, separateGroups As Boolean) _placeSystemNamespaceFirst = placeSystemNamespaceFirst _separateGroups = separateGroups End Sub Public Overrides Function VisitCompilationUnit(node As CompilationUnitSyntax) As SyntaxNode node = DirectCast(MyBase.VisitCompilationUnit(node), CompilationUnitSyntax) Dim organizedImports = ImportsOrganizer.Organize( node.Imports, _placeSystemNamespaceFirst, _separateGroups) Dim result = node.WithImports(organizedImports) If result IsNot node Then AddTextChange(node.Imports, organizedImports) End If Return result End Function Public Overrides Function VisitImportsStatement(node As ImportsStatementSyntax) As SyntaxNode Dim organizedImportsClauses = ImportsOrganizer.Organize(node.ImportsClauses) Dim result = node.WithImportsClauses(organizedImportsClauses) If result IsNot node Then AddTextChange(node.ImportsClauses, organizedImportsClauses) End If Return result End Function Private Sub AddTextChange(Of TSyntax As SyntaxNode)(list As SeparatedSyntaxList(Of TSyntax), organizedList As SeparatedSyntaxList(Of TSyntax)) If list.Count > 0 Then Me.TextChanges.Add(New TextChange(GetTextSpan(list), GetNewText(organizedList))) End If End Sub Private Sub AddTextChange(Of TSyntax As SyntaxNode)(list As SyntaxList(Of TSyntax), organizedList As SyntaxList(Of TSyntax)) If list.Count > 0 Then Me.TextChanges.Add(New TextChange(GetTextSpan(list), GetNewText(organizedList))) End If End Sub Private Shared Function GetNewText(Of TSyntax As SyntaxNode)(organizedList As SyntaxList(Of TSyntax)) As String Return String.Join(String.Empty, organizedList.[Select](Function(t) t.ToFullString())) End Function Private Shared Function GetNewText(Of TSyntax As SyntaxNode)(organizedList As SeparatedSyntaxList(Of TSyntax)) As String Return String.Join(String.Empty, organizedList.GetWithSeparators().[Select](Function(t) t.ToFullString())) End Function Private Shared Function GetTextSpan(Of TSyntax As SyntaxNode)(list As SyntaxList(Of TSyntax)) As TextSpan Return TextSpan.FromBounds(list.First().FullSpan.Start, list.Last().FullSpan.[End]) End Function Private Shared Function GetTextSpan(Of TSyntax As SyntaxNode)(list As SeparatedSyntaxList(Of TSyntax)) As TextSpan Return TextSpan.FromBounds(list.First().FullSpan.Start, list.Last().FullSpan.[End]) End Function End Class End Class End Namespace
-1
dotnet/roslyn
56,011
React to string comparison changing on .NET Core
The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
jaredpar
"2021-08-30T17:18:52Z"
"2021-08-30T20:20:04Z"
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
4d99cda6e446e77dbb302e26388c1093bd3ef569
React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
./src/Workspaces/VisualBasic/Portable/CodeGeneration/VisualBasicSyntaxGenerator.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Composition Imports System.Diagnostics.CodeAnalysis Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Editing Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Simplification Imports Microsoft.CodeAnalysis.VisualBasic.LanguageServices Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGeneration <ExportLanguageService(GetType(SyntaxGenerator), LanguageNames.VisualBasic), [Shared]> Friend Class VisualBasicSyntaxGenerator Inherits SyntaxGenerator Public Shared ReadOnly Instance As SyntaxGenerator = New VisualBasicSyntaxGenerator() <ImportingConstructor> <SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Incorrectly used in production code: https://github.com/dotnet/roslyn/issues/42839")> Public Sub New() End Sub Friend Overrides ReadOnly Property ElasticCarriageReturnLineFeed As SyntaxTrivia = SyntaxFactory.ElasticCarriageReturnLineFeed Friend Overrides ReadOnly Property CarriageReturnLineFeed As SyntaxTrivia = SyntaxFactory.CarriageReturnLineFeed Friend Overrides ReadOnly Property RequiresExplicitImplementationForInterfaceMembers As Boolean = True Friend Overrides ReadOnly Property SyntaxGeneratorInternal As SyntaxGeneratorInternal = VisualBasicSyntaxGeneratorInternal.Instance Friend Overrides Function Whitespace(text As String) As SyntaxTrivia Return SyntaxFactory.Whitespace(text) End Function Friend Overrides Function SingleLineComment(text As String) As SyntaxTrivia Return SyntaxFactory.CommentTrivia("'" + text) End Function Friend Overrides Function SeparatedList(Of TElement As SyntaxNode)(list As SyntaxNodeOrTokenList) As SeparatedSyntaxList(Of TElement) Return SyntaxFactory.SeparatedList(Of TElement)(list) End Function Friend Overrides Function CreateInterpolatedStringStartToken(isVerbatim As Boolean) As SyntaxToken Return SyntaxFactory.Token(SyntaxKind.DollarSignDoubleQuoteToken) End Function Friend Overrides Function CreateInterpolatedStringEndToken() As SyntaxToken Return SyntaxFactory.Token(SyntaxKind.DoubleQuoteToken) End Function Friend Overrides Function SeparatedList(Of TElement As SyntaxNode)(nodes As IEnumerable(Of TElement), separators As IEnumerable(Of SyntaxToken)) As SeparatedSyntaxList(Of TElement) Return SyntaxFactory.SeparatedList(nodes, separators) End Function Friend Overrides Function Trivia(node As SyntaxNode) As SyntaxTrivia Dim structuredTrivia = TryCast(node, StructuredTriviaSyntax) If structuredTrivia IsNot Nothing Then Return SyntaxFactory.Trivia(structuredTrivia) End If Throw ExceptionUtilities.UnexpectedValue(node.Kind()) End Function Friend Overrides Function DocumentationCommentTrivia(nodes As IEnumerable(Of SyntaxNode), trailingTrivia As SyntaxTriviaList, lastWhitespaceTrivia As SyntaxTrivia, endOfLineString As String) As SyntaxNode Dim node = SyntaxFactory.DocumentationCommentTrivia(SyntaxFactory.List(nodes)) node = node.WithLeadingTrivia(SyntaxFactory.DocumentationCommentExteriorTrivia("''' ")). WithTrailingTrivia(node.GetTrailingTrivia()) If lastWhitespaceTrivia = Nothing Then Return node.WithTrailingTrivia(SyntaxFactory.EndOfLine(endOfLineString)) End If Return node.WithTrailingTrivia(SyntaxFactory.EndOfLine(endOfLineString), lastWhitespaceTrivia) End Function Friend Overrides Function DocumentationCommentTriviaWithUpdatedContent(trivia As SyntaxTrivia, content As IEnumerable(Of SyntaxNode)) As SyntaxNode Dim documentationCommentTrivia = TryCast(trivia.GetStructure(), DocumentationCommentTriviaSyntax) If documentationCommentTrivia IsNot Nothing Then Return SyntaxFactory.DocumentationCommentTrivia(SyntaxFactory.List(content)) End If Return Nothing End Function #Region "Expressions and Statements" Public Overrides Function AddEventHandler([event] As SyntaxNode, handler As SyntaxNode) As SyntaxNode Return SyntaxFactory.AddHandlerStatement(CType([event], ExpressionSyntax), CType(handler, ExpressionSyntax)) End Function Public Overrides Function RemoveEventHandler([event] As SyntaxNode, handler As SyntaxNode) As SyntaxNode Return SyntaxFactory.RemoveHandlerStatement(CType([event], ExpressionSyntax), CType(handler, ExpressionSyntax)) End Function Public Overrides Function AwaitExpression(expression As SyntaxNode) As SyntaxNode Return SyntaxFactory.AwaitExpression(DirectCast(expression, ExpressionSyntax)) End Function Public Overrides Function NameOfExpression(expression As SyntaxNode) As SyntaxNode Return SyntaxFactory.NameOfExpression(DirectCast(expression, ExpressionSyntax)) End Function Public Overrides Function TupleExpression(arguments As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.TupleExpression(SyntaxFactory.SeparatedList(arguments.Select(AddressOf AsSimpleArgument))) End Function Private Shared Function Parenthesize(expression As SyntaxNode, Optional addSimplifierAnnotation As Boolean = True) As ParenthesizedExpressionSyntax Return VisualBasicSyntaxGeneratorInternal.Parenthesize(expression, addSimplifierAnnotation) End Function Public Overrides Function AddExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.AddExpression(Parenthesize(left), Parenthesize(right)) End Function Public Overloads Overrides Function Argument(name As String, refKind As RefKind, expression As SyntaxNode) As SyntaxNode If name Is Nothing Then Return SyntaxFactory.SimpleArgument(DirectCast(expression, ExpressionSyntax)) Else Return SyntaxFactory.SimpleArgument(SyntaxFactory.NameColonEquals(name.ToIdentifierName()), DirectCast(expression, ExpressionSyntax)) End If End Function Public Overrides Function TryCastExpression(expression As SyntaxNode, type As SyntaxNode) As SyntaxNode Return SyntaxFactory.TryCastExpression(DirectCast(expression, ExpressionSyntax), DirectCast(type, TypeSyntax)) End Function Public Overrides Function AssignmentStatement(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.SimpleAssignmentStatement( DirectCast(left, ExpressionSyntax), SyntaxFactory.Token(SyntaxKind.EqualsToken), DirectCast(right, ExpressionSyntax)) End Function Public Overrides Function BaseExpression() As SyntaxNode Return SyntaxFactory.MyBaseExpression() End Function Public Overrides Function BitwiseAndExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.AndExpression(Parenthesize(left), Parenthesize(right)) End Function Public Overrides Function BitwiseOrExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.OrExpression(Parenthesize(left), Parenthesize(right)) End Function Public Overrides Function CastExpression(type As SyntaxNode, expression As SyntaxNode) As SyntaxNode Return SyntaxFactory.DirectCastExpression(DirectCast(expression, ExpressionSyntax), DirectCast(type, TypeSyntax)).WithAdditionalAnnotations(Simplifier.Annotation) End Function Public Overrides Function ConvertExpression(type As SyntaxNode, expression As SyntaxNode) As SyntaxNode Return SyntaxFactory.CTypeExpression(DirectCast(expression, ExpressionSyntax), DirectCast(type, TypeSyntax)).WithAdditionalAnnotations(Simplifier.Annotation) End Function Public Overrides Function ConditionalExpression(condition As SyntaxNode, whenTrue As SyntaxNode, whenFalse As SyntaxNode) As SyntaxNode Return SyntaxFactory.TernaryConditionalExpression( DirectCast(condition, ExpressionSyntax), DirectCast(whenTrue, ExpressionSyntax), DirectCast(whenFalse, ExpressionSyntax)) End Function Public Overrides Function LiteralExpression(value As Object) As SyntaxNode Return ExpressionGenerator.GenerateNonEnumValueExpression(Nothing, value, canUseFieldReference:=True) End Function Public Overrides Function TypedConstantExpression(value As TypedConstant) As SyntaxNode Return ExpressionGenerator.GenerateExpression(value) End Function Friend Overrides Function NumericLiteralToken(text As String, value As ULong) As SyntaxToken Return SyntaxFactory.Literal(text, value) End Function Public Overrides Function DefaultExpression(type As ITypeSymbol) As SyntaxNode Return SyntaxFactory.NothingLiteralExpression(SyntaxFactory.Token(SyntaxKind.NothingKeyword)) End Function Public Overrides Function DefaultExpression(type As SyntaxNode) As SyntaxNode Return SyntaxFactory.NothingLiteralExpression(SyntaxFactory.Token(SyntaxKind.NothingKeyword)) End Function Public Overloads Overrides Function ElementAccessExpression(expression As SyntaxNode, arguments As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.InvocationExpression(ParenthesizeLeft(expression), CreateArgumentList(arguments)) End Function Public Overrides Function ExpressionStatement(expression As SyntaxNode) As SyntaxNode If TypeOf expression Is StatementSyntax Then Return expression End If Return SyntaxFactory.ExpressionStatement(DirectCast(expression, ExpressionSyntax)) End Function Public Overloads Overrides Function GenericName(identifier As String, typeArguments As IEnumerable(Of SyntaxNode)) As SyntaxNode Return GenericName(identifier.ToIdentifierToken(), typeArguments) End Function Friend Overrides Function GenericName(identifier As SyntaxToken, typeArguments As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.GenericName( identifier, SyntaxFactory.TypeArgumentList( SyntaxFactory.SeparatedList(typeArguments.Cast(Of TypeSyntax)()))).WithAdditionalAnnotations(Simplifier.Annotation) End Function Public Overrides Function IdentifierName(identifier As String) As SyntaxNode Return identifier.ToIdentifierName() End Function Public Overrides Function IfStatement(condition As SyntaxNode, trueStatements As IEnumerable(Of SyntaxNode), Optional falseStatements As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Dim ifStmt = SyntaxFactory.IfStatement(SyntaxFactory.Token(SyntaxKind.IfKeyword), DirectCast(condition, ExpressionSyntax), SyntaxFactory.Token(SyntaxKind.ThenKeyword)) If falseStatements Is Nothing Then Return SyntaxFactory.MultiLineIfBlock( ifStmt, GetStatementList(trueStatements), Nothing, Nothing ) End If ' convert nested if-blocks into else-if parts Dim statements = falseStatements.ToList() If statements.Count = 1 AndAlso TypeOf statements(0) Is MultiLineIfBlockSyntax Then Dim mifBlock = DirectCast(statements(0), MultiLineIfBlockSyntax) ' insert block's if-part onto head of elseIf-parts Dim elseIfBlocks = mifBlock.ElseIfBlocks.Insert(0, SyntaxFactory.ElseIfBlock( SyntaxFactory.ElseIfStatement(SyntaxFactory.Token(SyntaxKind.ElseIfKeyword), mifBlock.IfStatement.Condition, SyntaxFactory.Token(SyntaxKind.ThenKeyword)), mifBlock.Statements) ) Return SyntaxFactory.MultiLineIfBlock( ifStmt, GetStatementList(trueStatements), elseIfBlocks, mifBlock.ElseBlock ) End If Return SyntaxFactory.MultiLineIfBlock( ifStmt, GetStatementList(trueStatements), Nothing, SyntaxFactory.ElseBlock(GetStatementList(falseStatements)) ) End Function Private Function GetStatementList(nodes As IEnumerable(Of SyntaxNode)) As SyntaxList(Of StatementSyntax) If nodes Is Nothing Then Return Nothing Else Return SyntaxFactory.List(nodes.Select(AddressOf AsStatement)) End If End Function Private Function AsStatement(node As SyntaxNode) As StatementSyntax Dim expr = TryCast(node, ExpressionSyntax) If expr IsNot Nothing Then Return SyntaxFactory.ExpressionStatement(expr) Else Return DirectCast(node, StatementSyntax) End If End Function Public Overloads Overrides Function InvocationExpression(expression As SyntaxNode, arguments As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.InvocationExpression(ParenthesizeLeft(expression), CreateArgumentList(arguments)) End Function Public Overrides Function IsTypeExpression(expression As SyntaxNode, type As SyntaxNode) As SyntaxNode Return SyntaxFactory.TypeOfIsExpression(Parenthesize(expression), DirectCast(type, TypeSyntax)) End Function Public Overrides Function TypeOfExpression(type As SyntaxNode) As SyntaxNode Return SyntaxFactory.GetTypeExpression(DirectCast(type, TypeSyntax)) End Function Public Overrides Function LogicalAndExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.AndAlsoExpression(Parenthesize(left), Parenthesize(right)) End Function Public Overrides Function LogicalNotExpression(expression As SyntaxNode) As SyntaxNode Return SyntaxFactory.NotExpression(Parenthesize(expression)) End Function Public Overrides Function LogicalOrExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.OrElseExpression(Parenthesize(left), Parenthesize(right)) End Function Friend Overrides Function MemberAccessExpressionWorker(expression As SyntaxNode, simpleName As SyntaxNode) As SyntaxNode Return SyntaxFactory.SimpleMemberAccessExpression( If(expression IsNot Nothing, ParenthesizeLeft(expression), Nothing), SyntaxFactory.Token(SyntaxKind.DotToken), DirectCast(simpleName, SimpleNameSyntax)) End Function Public Overrides Function ConditionalAccessExpression(expression As SyntaxNode, whenNotNull As SyntaxNode) As SyntaxNode Return SyntaxGeneratorInternal.ConditionalAccessExpression(expression, whenNotNull) End Function Public Overrides Function MemberBindingExpression(name As SyntaxNode) As SyntaxNode Return SyntaxGeneratorInternal.MemberBindingExpression(name) End Function Public Overrides Function ElementBindingExpression(arguments As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.InvocationExpression(expression:=Nothing, SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList(arguments))) End Function ' parenthesize the left-side of a dot or target of an invocation if not unnecessary Private Shared Function ParenthesizeLeft(expression As SyntaxNode) As ExpressionSyntax Dim expressionSyntax = DirectCast(expression, ExpressionSyntax) If TypeOf expressionSyntax Is TypeSyntax _ OrElse expressionSyntax.IsMeMyBaseOrMyClass() _ OrElse expressionSyntax.IsKind(SyntaxKind.ParenthesizedExpression) _ OrElse expressionSyntax.IsKind(SyntaxKind.InvocationExpression) _ OrElse expressionSyntax.IsKind(SyntaxKind.SimpleMemberAccessExpression) Then Return expressionSyntax Else Return expressionSyntax.Parenthesize() End If End Function Public Overrides Function MultiplyExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.MultiplyExpression(Parenthesize(left), Parenthesize(right)) End Function Public Overrides Function NegateExpression(expression As SyntaxNode) As SyntaxNode Return SyntaxFactory.UnaryMinusExpression(Parenthesize(expression)) End Function Private Shared Function AsExpressionList(expressions As IEnumerable(Of SyntaxNode)) As SeparatedSyntaxList(Of ExpressionSyntax) Return SyntaxFactory.SeparatedList(Of ExpressionSyntax)(expressions.OfType(Of ExpressionSyntax)()) End Function Public Overrides Function ArrayCreationExpression(elementType As SyntaxNode, size As SyntaxNode) As SyntaxNode Dim sizes = SyntaxFactory.ArgumentList(SyntaxFactory.SingletonSeparatedList(AsArgument(size))) Dim initializer = SyntaxFactory.CollectionInitializer() Return SyntaxFactory.ArrayCreationExpression(Nothing, DirectCast(elementType, TypeSyntax), sizes, initializer) End Function Public Overrides Function ArrayCreationExpression(elementType As SyntaxNode, elements As IEnumerable(Of SyntaxNode)) As SyntaxNode Dim sizes = SyntaxFactory.ArgumentList() Dim initializer = SyntaxFactory.CollectionInitializer(AsExpressionList(elements)) Return SyntaxFactory.ArrayCreationExpression(Nothing, DirectCast(elementType, TypeSyntax), sizes, initializer) End Function Public Overloads Overrides Function ObjectCreationExpression(typeName As SyntaxNode, arguments As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.ObjectCreationExpression( attributeLists:=Nothing, DirectCast(typeName, TypeSyntax), CreateArgumentList(arguments), initializer:=Nothing) End Function Friend Overrides Function ObjectCreationExpression(typeName As SyntaxNode, openParen As SyntaxToken, arguments As SeparatedSyntaxList(Of SyntaxNode), closeParen As SyntaxToken) As SyntaxNode Return SyntaxFactory.ObjectCreationExpression( attributeLists:=Nothing, DirectCast(typeName, TypeSyntax), SyntaxFactory.ArgumentList(openParen, arguments, closeParen), initializer:=Nothing) End Function Public Overrides Function QualifiedName(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.QualifiedName(DirectCast(left, NameSyntax), DirectCast(right, SimpleNameSyntax)) End Function Friend Overrides Function GlobalAliasedName(name As SyntaxNode) As SyntaxNode Return QualifiedName(SyntaxFactory.GlobalName(), name) End Function Public Overrides Function ReferenceEqualsExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.IsExpression(Parenthesize(left), Parenthesize(right)) End Function Public Overrides Function ReferenceNotEqualsExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.IsNotExpression(Parenthesize(left), Parenthesize(right)) End Function Public Overrides Function ReturnStatement(Optional expressionOpt As SyntaxNode = Nothing) As SyntaxNode Return SyntaxFactory.ReturnStatement(DirectCast(expressionOpt, ExpressionSyntax)) End Function Public Overrides Function ThisExpression() As SyntaxNode Return SyntaxFactory.MeExpression() End Function Public Overrides Function ThrowStatement(Optional expressionOpt As SyntaxNode = Nothing) As SyntaxNode Return SyntaxFactory.ThrowStatement(DirectCast(expressionOpt, ExpressionSyntax)) End Function Public Overrides Function ThrowExpression(expression As SyntaxNode) As SyntaxNode Throw New NotSupportedException("ThrowExpressions are not supported in Visual Basic") End Function Friend Overrides Function SupportsThrowExpression() As Boolean Return False End Function Public Overrides Function NameExpression(namespaceOrTypeSymbol As INamespaceOrTypeSymbol) As SyntaxNode Return namespaceOrTypeSymbol.GenerateTypeSyntax() End Function Public Overrides Function TypeExpression(typeSymbol As ITypeSymbol) As SyntaxNode Return typeSymbol.GenerateTypeSyntax() End Function Public Overrides Function TypeExpression(specialType As SpecialType) As SyntaxNode Select Case specialType Case SpecialType.System_Boolean Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.BooleanKeyword)) Case SpecialType.System_Byte Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.ByteKeyword)) Case SpecialType.System_Char Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.CharKeyword)) Case SpecialType.System_Decimal Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.DecimalKeyword)) Case SpecialType.System_Double Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.DoubleKeyword)) Case SpecialType.System_Int16 Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.ShortKeyword)) Case SpecialType.System_Int32 Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.IntegerKeyword)) Case SpecialType.System_Int64 Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.LongKeyword)) Case SpecialType.System_Object Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.ObjectKeyword)) Case SpecialType.System_SByte Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.SByteKeyword)) Case SpecialType.System_Single Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.SingleKeyword)) Case SpecialType.System_String Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.StringKeyword)) Case SpecialType.System_UInt16 Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.UShortKeyword)) Case SpecialType.System_UInt32 Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.UIntegerKeyword)) Case SpecialType.System_UInt64 Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.ULongKeyword)) Case SpecialType.System_DateTime Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.DateKeyword)) Case Else Throw New NotSupportedException("Unsupported SpecialType") End Select End Function Public Overloads Overrides Function UsingStatement(type As SyntaxNode, identifier As String, expression As SyntaxNode, statements As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.UsingBlock( SyntaxFactory.UsingStatement( expression:=Nothing, variables:=SyntaxFactory.SingletonSeparatedList(VisualBasicSyntaxGeneratorInternal.VariableDeclarator(type, identifier.ToModifiedIdentifier, expression))), GetStatementList(statements)) End Function Public Overloads Overrides Function UsingStatement(expression As SyntaxNode, statements As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.UsingBlock( SyntaxFactory.UsingStatement( expression:=DirectCast(expression, ExpressionSyntax), variables:=Nothing), GetStatementList(statements)) End Function Public Overrides Function LockStatement(expression As SyntaxNode, statements As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.SyncLockBlock( SyntaxFactory.SyncLockStatement( expression:=DirectCast(expression, ExpressionSyntax)), GetStatementList(statements)) End Function Public Overrides Function ValueEqualsExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.EqualsExpression(Parenthesize(left), Parenthesize(right)) End Function Public Overrides Function ValueNotEqualsExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.NotEqualsExpression(Parenthesize(left), Parenthesize(right)) End Function Private Function CreateArgumentList(arguments As IEnumerable(Of SyntaxNode)) As ArgumentListSyntax Return SyntaxFactory.ArgumentList(CreateArguments(arguments)) End Function Private Function CreateArguments(arguments As IEnumerable(Of SyntaxNode)) As SeparatedSyntaxList(Of ArgumentSyntax) Return SyntaxFactory.SeparatedList(arguments.Select(AddressOf AsArgument)) End Function Private Function AsArgument(argOrExpression As SyntaxNode) As ArgumentSyntax Return If(TryCast(argOrExpression, ArgumentSyntax), SyntaxFactory.SimpleArgument(DirectCast(argOrExpression, ExpressionSyntax))) End Function Private Function AsSimpleArgument(argOrExpression As SyntaxNode) As SimpleArgumentSyntax Return If(TryCast(argOrExpression, SimpleArgumentSyntax), SyntaxFactory.SimpleArgument(DirectCast(argOrExpression, ExpressionSyntax))) End Function Public Overloads Overrides Function LocalDeclarationStatement(type As SyntaxNode, identifier As String, Optional initializer As SyntaxNode = Nothing, Optional isConst As Boolean = False) As SyntaxNode Return LocalDeclarationStatement(type, identifier.ToIdentifierToken, initializer, isConst) End Function Public Overloads Overrides Function SwitchStatement(expression As SyntaxNode, caseClauses As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.SelectBlock( SyntaxFactory.SelectStatement(DirectCast(expression, ExpressionSyntax)), SyntaxFactory.List(caseClauses.Cast(Of CaseBlockSyntax))) End Function Public Overloads Overrides Function SwitchSection(expressions As IEnumerable(Of SyntaxNode), statements As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.CaseBlock( SyntaxFactory.CaseStatement(GetCaseClauses(expressions)), GetStatementList(statements)) End Function Friend Overrides Function SwitchSectionFromLabels(labels As IEnumerable(Of SyntaxNode), statements As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.CaseBlock( SyntaxFactory.CaseStatement(SyntaxFactory.SeparatedList(labels.Cast(Of CaseClauseSyntax))), GetStatementList(statements)) End Function Public Overrides Function DefaultSwitchSection(statements As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.CaseElseBlock( SyntaxFactory.CaseElseStatement(SyntaxFactory.ElseCaseClause()), GetStatementList(statements)) End Function Private Shared Function GetCaseClauses(expressions As IEnumerable(Of SyntaxNode)) As SeparatedSyntaxList(Of CaseClauseSyntax) Dim cases = SyntaxFactory.SeparatedList(Of CaseClauseSyntax) If expressions IsNot Nothing Then cases = cases.AddRange(expressions.Select(Function(e) SyntaxFactory.SimpleCaseClause(DirectCast(e, ExpressionSyntax)))) End If Return cases End Function Public Overrides Function ExitSwitchStatement() As SyntaxNode Return SyntaxFactory.ExitSelectStatement() End Function Public Overloads Overrides Function ValueReturningLambdaExpression(parameters As IEnumerable(Of SyntaxNode), expression As SyntaxNode) As SyntaxNode Return SyntaxFactory.SingleLineFunctionLambdaExpression( SyntaxFactory.FunctionLambdaHeader().WithParameterList(GetParameterList(parameters)), DirectCast(expression, ExpressionSyntax)) End Function Public Overrides Function VoidReturningLambdaExpression(lambdaParameters As IEnumerable(Of SyntaxNode), expression As SyntaxNode) As SyntaxNode Return SyntaxFactory.SingleLineSubLambdaExpression( SyntaxFactory.SubLambdaHeader().WithParameterList(GetParameterList(lambdaParameters)), AsStatement(expression)) End Function Public Overloads Overrides Function ValueReturningLambdaExpression(lambdaParameters As IEnumerable(Of SyntaxNode), statements As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.MultiLineFunctionLambdaExpression( SyntaxFactory.FunctionLambdaHeader().WithParameterList(GetParameterList(lambdaParameters)), GetStatementList(statements), SyntaxFactory.EndFunctionStatement()) End Function Public Overrides Function VoidReturningLambdaExpression(lambdaParameters As IEnumerable(Of SyntaxNode), statements As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.MultiLineSubLambdaExpression( SyntaxFactory.SubLambdaHeader().WithParameterList(GetParameterList(lambdaParameters)), GetStatementList(statements), SyntaxFactory.EndSubStatement()) End Function Public Overrides Function LambdaParameter(identifier As String, Optional type As SyntaxNode = Nothing) As SyntaxNode Return ParameterDeclaration(identifier, type) End Function Public Overrides Function ArrayTypeExpression(type As SyntaxNode) As SyntaxNode Dim arrayType = TryCast(type, ArrayTypeSyntax) If arrayType IsNot Nothing Then Return arrayType.WithRankSpecifiers(arrayType.RankSpecifiers.Add(SyntaxFactory.ArrayRankSpecifier())) Else Return SyntaxFactory.ArrayType(DirectCast(type, TypeSyntax), SyntaxFactory.SingletonList(SyntaxFactory.ArrayRankSpecifier())) End If End Function Public Overrides Function NullableTypeExpression(type As SyntaxNode) As SyntaxNode Dim nullableType = TryCast(type, NullableTypeSyntax) If nullableType IsNot Nothing Then Return nullableType Else Return SyntaxFactory.NullableType(DirectCast(type, TypeSyntax)) End If End Function Friend Overrides Function CreateTupleType(elements As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.TupleType(SyntaxFactory.SeparatedList(elements.Cast(Of TupleElementSyntax)())) End Function Public Overrides Function TupleElementExpression(type As SyntaxNode, Optional name As String = Nothing) As SyntaxNode If name Is Nothing Then Return SyntaxFactory.TypedTupleElement(DirectCast(type, TypeSyntax)) Else Return SyntaxFactory.NamedTupleElement(name.ToIdentifierToken(), SyntaxFactory.SimpleAsClause(DirectCast(type, TypeSyntax))) End If End Function Public Overrides Function WithTypeArguments(name As SyntaxNode, typeArguments As IEnumerable(Of SyntaxNode)) As SyntaxNode If name.IsKind(SyntaxKind.IdentifierName) OrElse name.IsKind(SyntaxKind.GenericName) Then Dim sname = DirectCast(name, SimpleNameSyntax) Return SyntaxFactory.GenericName(sname.Identifier, SyntaxFactory.TypeArgumentList(SyntaxFactory.SeparatedList(typeArguments.Cast(Of TypeSyntax)()))) ElseIf name.IsKind(SyntaxKind.QualifiedName) Then Dim qname = DirectCast(name, QualifiedNameSyntax) Return SyntaxFactory.QualifiedName(qname.Left, DirectCast(WithTypeArguments(qname.Right, typeArguments), SimpleNameSyntax)) ElseIf name.IsKind(SyntaxKind.SimpleMemberAccessExpression) Then Dim sma = DirectCast(name, MemberAccessExpressionSyntax) Return SyntaxFactory.MemberAccessExpression(name.Kind(), sma.Expression, sma.OperatorToken, DirectCast(WithTypeArguments(sma.Name, typeArguments), SimpleNameSyntax)) Else Throw New NotSupportedException() End If End Function Public Overrides Function SubtractExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.SubtractExpression(Parenthesize(left), Parenthesize(right)) End Function Public Overrides Function DivideExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.DivideExpression(Parenthesize(left), Parenthesize(right)) End Function Public Overrides Function ModuloExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.ModuloExpression(Parenthesize(left), Parenthesize(right)) End Function Public Overrides Function BitwiseNotExpression(operand As SyntaxNode) As SyntaxNode Return SyntaxFactory.NotExpression(Parenthesize(operand)) End Function Public Overrides Function CoalesceExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.BinaryConditionalExpression(DirectCast(left, ExpressionSyntax), DirectCast(right, ExpressionSyntax)) End Function Public Overrides Function LessThanExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.LessThanExpression(Parenthesize(left), Parenthesize(right)) End Function Public Overrides Function LessThanOrEqualExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.LessThanOrEqualExpression(Parenthesize(left), Parenthesize(right)) End Function Public Overrides Function GreaterThanExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.GreaterThanExpression(Parenthesize(left), Parenthesize(right)) End Function Public Overrides Function GreaterThanOrEqualExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.GreaterThanOrEqualExpression(Parenthesize(left), Parenthesize(right)) End Function Public Overrides Function TryCatchStatement(tryStatements As IEnumerable(Of SyntaxNode), catchClauses As IEnumerable(Of SyntaxNode), Optional finallyStatements As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Return SyntaxFactory.TryBlock( GetStatementList(tryStatements), If(catchClauses IsNot Nothing, SyntaxFactory.List(catchClauses.Cast(Of CatchBlockSyntax)()), Nothing), If(finallyStatements IsNot Nothing, SyntaxFactory.FinallyBlock(GetStatementList(finallyStatements)), Nothing) ) End Function Public Overrides Function CatchClause(type As SyntaxNode, identifier As String, statements As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.CatchBlock( SyntaxFactory.CatchStatement( SyntaxFactory.IdentifierName(identifier), SyntaxFactory.SimpleAsClause(DirectCast(type, TypeSyntax)), whenClause:=Nothing ), GetStatementList(statements) ) End Function Public Overrides Function WhileStatement(condition As SyntaxNode, statements As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.WhileBlock( SyntaxFactory.WhileStatement(DirectCast(condition, ExpressionSyntax)), GetStatementList(statements)) End Function Friend Overrides Function ScopeBlock(statements As IEnumerable(Of SyntaxNode)) As SyntaxNode Throw New NotSupportedException() End Function Friend Overrides Function ParseExpression(stringToParse As String) As SyntaxNode Return SyntaxFactory.ParseExpression(stringToParse) End Function #End Region #Region "Declarations" Private Shared ReadOnly s_fieldModifiers As DeclarationModifiers = DeclarationModifiers.Const Or DeclarationModifiers.[New] Or DeclarationModifiers.ReadOnly Or DeclarationModifiers.Static Or DeclarationModifiers.WithEvents Private Shared ReadOnly s_methodModifiers As DeclarationModifiers = DeclarationModifiers.Abstract Or DeclarationModifiers.Async Or DeclarationModifiers.[New] Or DeclarationModifiers.Override Or DeclarationModifiers.Partial Or DeclarationModifiers.Sealed Or DeclarationModifiers.Static Or DeclarationModifiers.Virtual Private Shared ReadOnly s_constructorModifiers As DeclarationModifiers = DeclarationModifiers.Static Private Shared ReadOnly s_propertyModifiers As DeclarationModifiers = DeclarationModifiers.Abstract Or DeclarationModifiers.[New] Or DeclarationModifiers.Override Or DeclarationModifiers.ReadOnly Or DeclarationModifiers.WriteOnly Or DeclarationModifiers.Sealed Or DeclarationModifiers.Static Or DeclarationModifiers.Virtual Private Shared ReadOnly s_indexerModifiers As DeclarationModifiers = DeclarationModifiers.Abstract Or DeclarationModifiers.[New] Or DeclarationModifiers.Override Or DeclarationModifiers.ReadOnly Or DeclarationModifiers.WriteOnly Or DeclarationModifiers.Sealed Or DeclarationModifiers.Static Or DeclarationModifiers.Virtual Private Shared ReadOnly s_classModifiers As DeclarationModifiers = DeclarationModifiers.Abstract Or DeclarationModifiers.[New] Or DeclarationModifiers.Partial Or DeclarationModifiers.Sealed Or DeclarationModifiers.Static Private Shared ReadOnly s_structModifiers As DeclarationModifiers = DeclarationModifiers.[New] Or DeclarationModifiers.Partial Private Shared ReadOnly s_interfaceModifiers As DeclarationModifiers = DeclarationModifiers.[New] Or DeclarationModifiers.Partial Private Shared ReadOnly s_accessorModifiers As DeclarationModifiers = DeclarationModifiers.Abstract Or DeclarationModifiers.[New] Or DeclarationModifiers.Override Or DeclarationModifiers.Virtual Private Shared Function GetAllowedModifiers(kind As SyntaxKind) As DeclarationModifiers Select Case kind Case SyntaxKind.ClassBlock, SyntaxKind.ClassStatement Return s_classModifiers Case SyntaxKind.EnumBlock, SyntaxKind.EnumStatement Return DeclarationModifiers.[New] Case SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement Return DeclarationModifiers.[New] Case SyntaxKind.InterfaceBlock, SyntaxKind.InterfaceStatement Return s_interfaceModifiers Case SyntaxKind.StructureBlock, SyntaxKind.StructureStatement Return s_structModifiers Case SyntaxKind.FunctionBlock, SyntaxKind.FunctionStatement, SyntaxKind.SubBlock, SyntaxKind.SubStatement, SyntaxKind.OperatorBlock, SyntaxKind.OperatorStatement Return s_methodModifiers Case SyntaxKind.ConstructorBlock, SyntaxKind.SubNewStatement Return s_constructorModifiers Case SyntaxKind.FieldDeclaration Return s_fieldModifiers Case SyntaxKind.PropertyBlock, SyntaxKind.PropertyStatement Return s_propertyModifiers Case SyntaxKind.EventBlock, SyntaxKind.EventStatement Return s_propertyModifiers Case SyntaxKind.GetAccessorBlock, SyntaxKind.GetAccessorStatement, SyntaxKind.SetAccessorBlock, SyntaxKind.SetAccessorStatement, SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.AddHandlerAccessorStatement, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorStatement, SyntaxKind.RaiseEventAccessorBlock, SyntaxKind.RaiseEventAccessorStatement Return s_accessorModifiers Case SyntaxKind.EnumMemberDeclaration Case SyntaxKind.Parameter Case SyntaxKind.LocalDeclarationStatement Case Else Return DeclarationModifiers.None End Select End Function Public Overrides Function FieldDeclaration(name As String, type As SyntaxNode, Optional accessibility As Accessibility = Nothing, Optional modifiers As DeclarationModifiers = Nothing, Optional initializer As SyntaxNode = Nothing) As SyntaxNode Return SyntaxFactory.FieldDeclaration( attributeLists:=Nothing, modifiers:=GetModifierList(accessibility, modifiers And s_fieldModifiers, declaration:=Nothing, DeclarationKind.Field), declarators:=SyntaxFactory.SingletonSeparatedList(VisualBasicSyntaxGeneratorInternal.VariableDeclarator(type, name.ToModifiedIdentifier, initializer))) End Function Public Overrides Function MethodDeclaration( identifier As String, Optional parameters As IEnumerable(Of SyntaxNode) = Nothing, Optional typeParameters As IEnumerable(Of String) = Nothing, Optional returnType As SyntaxNode = Nothing, Optional accessibility As Accessibility = Nothing, Optional modifiers As DeclarationModifiers = Nothing, Optional statements As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Dim statement = SyntaxFactory.MethodStatement( kind:=If(returnType Is Nothing, SyntaxKind.SubStatement, SyntaxKind.FunctionStatement), attributeLists:=Nothing, modifiers:=GetModifierList(accessibility, modifiers And s_methodModifiers, declaration:=Nothing, DeclarationKind.Method), subOrFunctionKeyword:=If(returnType Is Nothing, SyntaxFactory.Token(SyntaxKind.SubKeyword), SyntaxFactory.Token(SyntaxKind.FunctionKeyword)), identifier:=identifier.ToIdentifierToken(), typeParameterList:=GetTypeParameters(typeParameters), parameterList:=GetParameterList(parameters), asClause:=If(returnType IsNot Nothing, SyntaxFactory.SimpleAsClause(DirectCast(returnType, TypeSyntax)), Nothing), handlesClause:=Nothing, implementsClause:=Nothing) If modifiers.IsAbstract Then Return statement Else Return SyntaxFactory.MethodBlock( kind:=If(returnType Is Nothing, SyntaxKind.SubBlock, SyntaxKind.FunctionBlock), subOrFunctionStatement:=statement, statements:=GetStatementList(statements), endSubOrFunctionStatement:=If(returnType Is Nothing, SyntaxFactory.EndSubStatement(), SyntaxFactory.EndFunctionStatement())) End If End Function Public Overrides Function OperatorDeclaration(kind As OperatorKind, Optional parameters As IEnumerable(Of SyntaxNode) = Nothing, Optional returnType As SyntaxNode = Nothing, Optional accessibility As Accessibility = Accessibility.NotApplicable, Optional modifiers As DeclarationModifiers = Nothing, Optional statements As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Dim statement As OperatorStatementSyntax Dim asClause = If(returnType IsNot Nothing, SyntaxFactory.SimpleAsClause(DirectCast(returnType, TypeSyntax)), Nothing) Dim parameterList = GetParameterList(parameters) Dim operatorToken = SyntaxFactory.Token(GetTokenKind(kind)) Dim modifierList As SyntaxTokenList = GetModifierList(accessibility, modifiers And s_methodModifiers, declaration:=Nothing, DeclarationKind.Operator) If kind = OperatorKind.ImplicitConversion OrElse kind = OperatorKind.ExplicitConversion Then modifierList = modifierList.Add(SyntaxFactory.Token( If(kind = OperatorKind.ImplicitConversion, SyntaxKind.WideningKeyword, SyntaxKind.NarrowingKeyword))) statement = SyntaxFactory.OperatorStatement( attributeLists:=Nothing, modifiers:=modifierList, operatorToken:=operatorToken, parameterList:=parameterList, asClause:=asClause) Else statement = SyntaxFactory.OperatorStatement( attributeLists:=Nothing, modifiers:=modifierList, operatorToken:=operatorToken, parameterList:=parameterList, asClause:=asClause) End If If modifiers.IsAbstract Then Return statement Else Return SyntaxFactory.OperatorBlock( operatorStatement:=statement, statements:=GetStatementList(statements), endOperatorStatement:=SyntaxFactory.EndOperatorStatement()) End If End Function Private Shared Function GetTokenKind(kind As OperatorKind) As SyntaxKind Select Case kind Case OperatorKind.ImplicitConversion, OperatorKind.ExplicitConversion Return SyntaxKind.CTypeKeyword Case OperatorKind.Addition Return SyntaxKind.PlusToken Case OperatorKind.BitwiseAnd Return SyntaxKind.AndKeyword Case OperatorKind.BitwiseOr Return SyntaxKind.OrKeyword Case OperatorKind.Division Return SyntaxKind.SlashToken Case OperatorKind.Equality Return SyntaxKind.EqualsToken Case OperatorKind.ExclusiveOr Return SyntaxKind.XorKeyword Case OperatorKind.False Return SyntaxKind.IsFalseKeyword Case OperatorKind.GreaterThan Return SyntaxKind.GreaterThanToken Case OperatorKind.GreaterThanOrEqual Return SyntaxKind.GreaterThanEqualsToken Case OperatorKind.Inequality Return SyntaxKind.LessThanGreaterThanToken Case OperatorKind.LeftShift Return SyntaxKind.LessThanLessThanToken Case OperatorKind.LessThan Return SyntaxKind.LessThanToken Case OperatorKind.LessThanOrEqual Return SyntaxKind.LessThanEqualsToken Case OperatorKind.LogicalNot Return SyntaxKind.NotKeyword Case OperatorKind.Modulus Return SyntaxKind.ModKeyword Case OperatorKind.Multiply Return SyntaxKind.AsteriskToken Case OperatorKind.RightShift Return SyntaxKind.GreaterThanGreaterThanToken Case OperatorKind.Subtraction Return SyntaxKind.MinusToken Case OperatorKind.True Return SyntaxKind.IsTrueKeyword Case OperatorKind.UnaryNegation Return SyntaxKind.MinusToken Case OperatorKind.UnaryPlus Return SyntaxKind.PlusToken Case Else Throw New ArgumentException($"Operator {kind} cannot be generated in Visual Basic.") End Select End Function Private Shared Function GetParameterList(parameters As IEnumerable(Of SyntaxNode)) As ParameterListSyntax Return If(parameters IsNot Nothing, SyntaxFactory.ParameterList(SyntaxFactory.SeparatedList(parameters.Cast(Of ParameterSyntax)())), SyntaxFactory.ParameterList()) End Function Public Overrides Function ParameterDeclaration(name As String, Optional type As SyntaxNode = Nothing, Optional initializer As SyntaxNode = Nothing, Optional refKind As RefKind = Nothing) As SyntaxNode Return SyntaxFactory.Parameter( attributeLists:=Nothing, modifiers:=GetParameterModifiers(refKind, initializer), identifier:=name.ToModifiedIdentifier(), asClause:=If(type IsNot Nothing, SyntaxFactory.SimpleAsClause(DirectCast(type, TypeSyntax)), Nothing), [default]:=If(initializer IsNot Nothing, SyntaxFactory.EqualsValue(DirectCast(initializer, ExpressionSyntax)), Nothing)) End Function Private Shared Function GetParameterModifiers(refKind As RefKind, initializer As SyntaxNode) As SyntaxTokenList Dim tokens As SyntaxTokenList = Nothing If initializer IsNot Nothing Then tokens = tokens.Add(SyntaxFactory.Token(SyntaxKind.OptionalKeyword)) End If If refKind <> RefKind.None Then tokens = tokens.Add(SyntaxFactory.Token(SyntaxKind.ByRefKeyword)) End If Return tokens End Function Public Overrides Function GetAccessorDeclaration(Optional accessibility As Accessibility = Accessibility.NotApplicable, Optional statements As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Return SyntaxFactory.GetAccessorBlock( SyntaxFactory.GetAccessorStatement().WithModifiers(GetModifierList(accessibility, DeclarationModifiers.None, declaration:=Nothing, DeclarationKind.Property)), GetStatementList(statements)) End Function Public Overrides Function SetAccessorDeclaration(Optional accessibility As Accessibility = Accessibility.NotApplicable, Optional statements As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Return SyntaxFactory.SetAccessorBlock( SyntaxFactory.SetAccessorStatement().WithModifiers(GetModifierList(accessibility, DeclarationModifiers.None, declaration:=Nothing, DeclarationKind.Property)), GetStatementList(statements)) End Function Public Overrides Function WithAccessorDeclarations(declaration As SyntaxNode, accessorDeclarations As IEnumerable(Of SyntaxNode)) As SyntaxNode Dim propertyBlock = GetPropertyBlock(declaration) If propertyBlock Is Nothing Then Return declaration End If propertyBlock = propertyBlock.WithAccessors( SyntaxFactory.List(accessorDeclarations.OfType(Of AccessorBlockSyntax))) Dim hasGetAccessor = propertyBlock.Accessors.Any(SyntaxKind.GetAccessorBlock) Dim hasSetAccessor = propertyBlock.Accessors.Any(SyntaxKind.SetAccessorBlock) If hasGetAccessor AndAlso Not hasSetAccessor Then propertyBlock = DirectCast(WithModifiers(propertyBlock, GetModifiers(propertyBlock) Or DeclarationModifiers.ReadOnly), PropertyBlockSyntax) ElseIf Not hasGetAccessor AndAlso hasSetAccessor Then propertyBlock = DirectCast(WithModifiers(propertyBlock, GetModifiers(propertyBlock) Or DeclarationModifiers.WriteOnly), PropertyBlockSyntax) ElseIf hasGetAccessor AndAlso hasSetAccessor Then propertyBlock = DirectCast(WithModifiers(propertyBlock, GetModifiers(propertyBlock).WithIsReadOnly(False).WithIsWriteOnly(False)), PropertyBlockSyntax) End If Return If(propertyBlock.Accessors.Count = 0, propertyBlock.PropertyStatement, DirectCast(propertyBlock, SyntaxNode)) End Function Private Shared Function GetPropertyBlock(declaration As SyntaxNode) As PropertyBlockSyntax Dim propertyBlock = TryCast(declaration, PropertyBlockSyntax) If propertyBlock IsNot Nothing Then Return propertyBlock End If Dim propertyStatement = TryCast(declaration, PropertyStatementSyntax) If propertyStatement IsNot Nothing Then Return SyntaxFactory.PropertyBlock(propertyStatement, SyntaxFactory.List(Of AccessorBlockSyntax)) End If Return Nothing End Function Public Overrides Function PropertyDeclaration( identifier As String, type As SyntaxNode, Optional accessibility As Accessibility = Nothing, Optional modifiers As DeclarationModifiers = Nothing, Optional getAccessorStatements As IEnumerable(Of SyntaxNode) = Nothing, Optional setAccessorStatements As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Dim asClause = SyntaxFactory.SimpleAsClause(DirectCast(type, TypeSyntax)) Dim statement = SyntaxFactory.PropertyStatement( attributeLists:=Nothing, modifiers:=GetModifierList(accessibility, modifiers And s_propertyModifiers, declaration:=Nothing, DeclarationKind.Property), identifier:=identifier.ToIdentifierToken(), parameterList:=Nothing, asClause:=asClause, initializer:=Nothing, implementsClause:=Nothing) If modifiers.IsAbstract Then Return statement Else Dim accessors = New List(Of AccessorBlockSyntax) If Not modifiers.IsWriteOnly Then accessors.Add(CreateGetAccessorBlock(getAccessorStatements)) End If If Not modifiers.IsReadOnly Then accessors.Add(CreateSetAccessorBlock(type, setAccessorStatements)) End If Return SyntaxFactory.PropertyBlock( propertyStatement:=statement, accessors:=SyntaxFactory.List(accessors), endPropertyStatement:=SyntaxFactory.EndPropertyStatement()) End If End Function Public Overrides Function IndexerDeclaration( parameters As IEnumerable(Of SyntaxNode), type As SyntaxNode, Optional accessibility As Accessibility = Nothing, Optional modifiers As DeclarationModifiers = Nothing, Optional getAccessorStatements As IEnumerable(Of SyntaxNode) = Nothing, Optional setAccessorStatements As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Dim asClause = SyntaxFactory.SimpleAsClause(DirectCast(type, TypeSyntax)) Dim statement = SyntaxFactory.PropertyStatement( attributeLists:=Nothing, modifiers:=GetModifierList(accessibility, modifiers And s_indexerModifiers, declaration:=Nothing, DeclarationKind.Indexer, isDefault:=True), identifier:=SyntaxFactory.Identifier("Item"), parameterList:=SyntaxFactory.ParameterList(SyntaxFactory.SeparatedList(parameters.Cast(Of ParameterSyntax))), asClause:=asClause, initializer:=Nothing, implementsClause:=Nothing) If modifiers.IsAbstract Then Return statement Else Dim accessors = New List(Of AccessorBlockSyntax) If Not modifiers.IsWriteOnly Then accessors.Add(CreateGetAccessorBlock(getAccessorStatements)) End If If Not modifiers.IsReadOnly Then accessors.Add(CreateSetAccessorBlock(type, setAccessorStatements)) End If Return SyntaxFactory.PropertyBlock( propertyStatement:=statement, accessors:=SyntaxFactory.List(accessors), endPropertyStatement:=SyntaxFactory.EndPropertyStatement()) End If End Function Private Function AccessorBlock(kind As SyntaxKind, statements As IEnumerable(Of SyntaxNode), type As SyntaxNode) As AccessorBlockSyntax Select Case kind Case SyntaxKind.GetAccessorBlock Return CreateGetAccessorBlock(statements) Case SyntaxKind.SetAccessorBlock Return CreateSetAccessorBlock(type, statements) Case SyntaxKind.AddHandlerAccessorBlock Return CreateAddHandlerAccessorBlock(type, statements) Case SyntaxKind.RemoveHandlerAccessorBlock Return CreateRemoveHandlerAccessorBlock(type, statements) Case Else Return Nothing End Select End Function Private Function CreateGetAccessorBlock(statements As IEnumerable(Of SyntaxNode)) As AccessorBlockSyntax Return SyntaxFactory.AccessorBlock( SyntaxKind.GetAccessorBlock, SyntaxFactory.AccessorStatement(SyntaxKind.GetAccessorStatement, SyntaxFactory.Token(SyntaxKind.GetKeyword)), GetStatementList(statements), SyntaxFactory.EndGetStatement()) End Function Private Function CreateSetAccessorBlock(type As SyntaxNode, statements As IEnumerable(Of SyntaxNode)) As AccessorBlockSyntax Dim asClause = SyntaxFactory.SimpleAsClause(DirectCast(type, TypeSyntax)) Dim valueParameter = SyntaxFactory.Parameter( attributeLists:=Nothing, modifiers:=Nothing, identifier:=SyntaxFactory.ModifiedIdentifier("value"), asClause:=asClause, [default]:=Nothing) Return SyntaxFactory.AccessorBlock( SyntaxKind.SetAccessorBlock, SyntaxFactory.AccessorStatement( kind:=SyntaxKind.SetAccessorStatement, attributeLists:=Nothing, modifiers:=Nothing, accessorKeyword:=SyntaxFactory.Token(SyntaxKind.SetKeyword), parameterList:=SyntaxFactory.ParameterList(SyntaxFactory.SingletonSeparatedList(valueParameter))), GetStatementList(statements), SyntaxFactory.EndSetStatement()) End Function Private Function CreateAddHandlerAccessorBlock(delegateType As SyntaxNode, statements As IEnumerable(Of SyntaxNode)) As AccessorBlockSyntax Dim asClause = SyntaxFactory.SimpleAsClause(DirectCast(delegateType, TypeSyntax)) Dim valueParameter = SyntaxFactory.Parameter( attributeLists:=Nothing, modifiers:=Nothing, identifier:=SyntaxFactory.ModifiedIdentifier("value"), asClause:=asClause, [default]:=Nothing) Return SyntaxFactory.AccessorBlock( SyntaxKind.AddHandlerAccessorBlock, SyntaxFactory.AccessorStatement( kind:=SyntaxKind.AddHandlerAccessorStatement, attributeLists:=Nothing, modifiers:=Nothing, accessorKeyword:=SyntaxFactory.Token(SyntaxKind.AddHandlerKeyword), parameterList:=SyntaxFactory.ParameterList(SyntaxFactory.SingletonSeparatedList(valueParameter))), GetStatementList(statements), SyntaxFactory.EndAddHandlerStatement()) End Function Private Function CreateRemoveHandlerAccessorBlock(delegateType As SyntaxNode, statements As IEnumerable(Of SyntaxNode)) As AccessorBlockSyntax Dim asClause = SyntaxFactory.SimpleAsClause(DirectCast(delegateType, TypeSyntax)) Dim valueParameter = SyntaxFactory.Parameter( attributeLists:=Nothing, modifiers:=Nothing, identifier:=SyntaxFactory.ModifiedIdentifier("value"), asClause:=asClause, [default]:=Nothing) Return SyntaxFactory.AccessorBlock( SyntaxKind.RemoveHandlerAccessorBlock, SyntaxFactory.AccessorStatement( kind:=SyntaxKind.RemoveHandlerAccessorStatement, attributeLists:=Nothing, modifiers:=Nothing, accessorKeyword:=SyntaxFactory.Token(SyntaxKind.RemoveHandlerKeyword), parameterList:=SyntaxFactory.ParameterList(SyntaxFactory.SingletonSeparatedList(valueParameter))), GetStatementList(statements), SyntaxFactory.EndRemoveHandlerStatement()) End Function Private Function CreateRaiseEventAccessorBlock(parameters As IEnumerable(Of SyntaxNode), statements As IEnumerable(Of SyntaxNode)) As AccessorBlockSyntax Dim parameterList = GetParameterList(parameters) Return SyntaxFactory.AccessorBlock( SyntaxKind.RaiseEventAccessorBlock, SyntaxFactory.AccessorStatement( kind:=SyntaxKind.RaiseEventAccessorStatement, attributeLists:=Nothing, modifiers:=Nothing, accessorKeyword:=SyntaxFactory.Token(SyntaxKind.RaiseEventKeyword), parameterList:=parameterList), GetStatementList(statements), SyntaxFactory.EndRaiseEventStatement()) End Function Public Overrides Function AsPublicInterfaceImplementation(declaration As SyntaxNode, interfaceTypeName As SyntaxNode, interfaceMemberName As String) As SyntaxNode Return Isolate(declaration, Function(decl) AsPublicInterfaceImplementationInternal(decl, interfaceTypeName, interfaceMemberName)) End Function Private Function AsPublicInterfaceImplementationInternal(declaration As SyntaxNode, interfaceTypeName As SyntaxNode, interfaceMemberName As String) As SyntaxNode Dim type = DirectCast(interfaceTypeName, NameSyntax) declaration = WithBody(declaration, allowDefault:=True) declaration = WithAccessibility(declaration, Accessibility.Public) Dim memberName = If(interfaceMemberName IsNot Nothing, interfaceMemberName, GetInterfaceMemberName(declaration)) declaration = WithName(declaration, memberName) declaration = WithImplementsClause(declaration, SyntaxFactory.ImplementsClause(SyntaxFactory.QualifiedName(type, SyntaxFactory.IdentifierName(memberName)))) Return declaration End Function Public Overrides Function AsPrivateInterfaceImplementation(declaration As SyntaxNode, interfaceTypeName As SyntaxNode, interfaceMemberName As String) As SyntaxNode Return Isolate(declaration, Function(decl) AsPrivateInterfaceImplementationInternal(decl, interfaceTypeName, interfaceMemberName)) End Function Private Function AsPrivateInterfaceImplementationInternal(declaration As SyntaxNode, interfaceTypeName As SyntaxNode, interfaceMemberName As String) As SyntaxNode Dim type = DirectCast(interfaceTypeName, NameSyntax) declaration = WithBody(declaration, allowDefault:=False) declaration = WithAccessibility(declaration, Accessibility.Private) Dim memberName = If(interfaceMemberName IsNot Nothing, interfaceMemberName, GetInterfaceMemberName(declaration)) declaration = WithName(declaration, GetNameAsIdentifier(interfaceTypeName) & "_" & memberName) declaration = WithImplementsClause(declaration, SyntaxFactory.ImplementsClause(SyntaxFactory.QualifiedName(type, SyntaxFactory.IdentifierName(memberName)))) Return declaration End Function Private Function GetInterfaceMemberName(declaration As SyntaxNode) As String Dim clause = GetImplementsClause(declaration) If clause IsNot Nothing Then Dim qname = clause.InterfaceMembers.FirstOrDefault(Function(n) n.Right IsNot Nothing) If qname IsNot Nothing Then Return qname.Right.ToString() End If End If Return GetName(declaration) End Function Private Shared Function GetImplementsClause(declaration As SyntaxNode) As ImplementsClauseSyntax Select Case declaration.Kind Case SyntaxKind.SubBlock, SyntaxKind.FunctionBlock Return DirectCast(declaration, MethodBlockSyntax).SubOrFunctionStatement.ImplementsClause Case SyntaxKind.SubStatement, SyntaxKind.FunctionStatement Return DirectCast(declaration, MethodStatementSyntax).ImplementsClause Case SyntaxKind.PropertyBlock Return DirectCast(declaration, PropertyBlockSyntax).PropertyStatement.ImplementsClause Case SyntaxKind.PropertyStatement Return DirectCast(declaration, PropertyStatementSyntax).ImplementsClause Case Else Return Nothing End Select End Function Private Shared Function WithImplementsClause(declaration As SyntaxNode, clause As ImplementsClauseSyntax) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.SubBlock, SyntaxKind.FunctionBlock Dim mb = DirectCast(declaration, MethodBlockSyntax) Return mb.WithSubOrFunctionStatement(mb.SubOrFunctionStatement.WithImplementsClause(clause)) Case SyntaxKind.SubStatement, SyntaxKind.FunctionStatement Return DirectCast(declaration, MethodStatementSyntax).WithImplementsClause(clause) Case SyntaxKind.PropertyBlock Dim pb = DirectCast(declaration, PropertyBlockSyntax) Return pb.WithPropertyStatement(pb.PropertyStatement.WithImplementsClause(clause)) Case SyntaxKind.PropertyStatement Return DirectCast(declaration, PropertyStatementSyntax).WithImplementsClause(clause) Case Else Return declaration End Select End Function Private Function GetNameAsIdentifier(type As SyntaxNode) As String Dim name = TryCast(type, IdentifierNameSyntax) If name IsNot Nothing Then Return name.Identifier.ValueText End If Dim gname = TryCast(type, GenericNameSyntax) If gname IsNot Nothing Then Return gname.Identifier.ValueText & "_" & gname.TypeArgumentList.Arguments.Select(Function(t) GetNameAsIdentifier(t)).Aggregate(Function(a, b) a & "_" & b) End If Dim qname = TryCast(type, QualifiedNameSyntax) If qname IsNot Nothing Then Return GetNameAsIdentifier(qname.Right) End If Return "[" & type.ToString() & "]" End Function Private Function WithBody(declaration As SyntaxNode, allowDefault As Boolean) As SyntaxNode declaration = Me.WithModifiersInternal(declaration, Me.GetModifiers(declaration) - DeclarationModifiers.Abstract) Dim method = TryCast(declaration, MethodStatementSyntax) If method IsNot Nothing Then Return SyntaxFactory.MethodBlock( kind:=If(method.IsKind(SyntaxKind.FunctionStatement), SyntaxKind.FunctionBlock, SyntaxKind.SubBlock), subOrFunctionStatement:=method, endSubOrFunctionStatement:=If(method.IsKind(SyntaxKind.FunctionStatement), SyntaxFactory.EndFunctionStatement(), SyntaxFactory.EndSubStatement())) End If Dim prop = TryCast(declaration, PropertyStatementSyntax) If prop IsNot Nothing Then prop = prop.WithModifiers(WithIsDefault(prop.Modifiers, GetIsDefault(prop.Modifiers) And allowDefault, declaration)) Dim accessors = New List(Of AccessorBlockSyntax) accessors.Add(CreateGetAccessorBlock(Nothing)) If (Not prop.Modifiers.Any(SyntaxKind.ReadOnlyKeyword)) Then accessors.Add(CreateSetAccessorBlock(prop.AsClause.Type, Nothing)) End If Return SyntaxFactory.PropertyBlock( propertyStatement:=prop, accessors:=SyntaxFactory.List(accessors), endPropertyStatement:=SyntaxFactory.EndPropertyStatement()) End If Return declaration End Function Private Function GetIsDefault(modifierList As SyntaxTokenList) As Boolean Dim access As Accessibility Dim modifiers As DeclarationModifiers Dim isDefault As Boolean SyntaxFacts.GetAccessibilityAndModifiers(modifierList, access, modifiers, isDefault) Return isDefault End Function Private Function WithIsDefault(modifierList As SyntaxTokenList, isDefault As Boolean, declaration As SyntaxNode) As SyntaxTokenList Dim access As Accessibility Dim modifiers As DeclarationModifiers Dim currentIsDefault As Boolean SyntaxFacts.GetAccessibilityAndModifiers(modifierList, access, modifiers, currentIsDefault) If currentIsDefault <> isDefault Then Return GetModifierList(access, modifiers, declaration, GetDeclarationKind(declaration), isDefault) Else Return modifierList End If End Function Public Overrides Function ConstructorDeclaration( Optional name As String = Nothing, Optional parameters As IEnumerable(Of SyntaxNode) = Nothing, Optional accessibility As Accessibility = Nothing, Optional modifiers As DeclarationModifiers = Nothing, Optional baseConstructorArguments As IEnumerable(Of SyntaxNode) = Nothing, Optional statements As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Dim stats = GetStatementList(statements) If (baseConstructorArguments IsNot Nothing) Then Dim baseCall = DirectCast(Me.ExpressionStatement(Me.InvocationExpression(Me.MemberAccessExpression(Me.BaseExpression(), SyntaxFactory.IdentifierName("New")), baseConstructorArguments)), StatementSyntax) stats = stats.Insert(0, baseCall) End If Return SyntaxFactory.ConstructorBlock( subNewStatement:=SyntaxFactory.SubNewStatement( attributeLists:=Nothing, modifiers:=GetModifierList(accessibility, modifiers And s_constructorModifiers, declaration:=Nothing, DeclarationKind.Constructor), parameterList:=If(parameters IsNot Nothing, SyntaxFactory.ParameterList(SyntaxFactory.SeparatedList(parameters.Cast(Of ParameterSyntax)())), SyntaxFactory.ParameterList())), statements:=stats) End Function Public Overrides Function ClassDeclaration( name As String, Optional typeParameters As IEnumerable(Of String) = Nothing, Optional accessibility As Accessibility = Nothing, Optional modifiers As DeclarationModifiers = Nothing, Optional baseType As SyntaxNode = Nothing, Optional interfaceTypes As IEnumerable(Of SyntaxNode) = Nothing, Optional members As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Dim itypes = If(interfaceTypes IsNot Nothing, interfaceTypes.Cast(Of TypeSyntax), Nothing) If itypes IsNot Nothing AndAlso itypes.Count = 0 Then itypes = Nothing End If Return SyntaxFactory.ClassBlock( classStatement:=SyntaxFactory.ClassStatement( attributeLists:=Nothing, modifiers:=GetModifierList(accessibility, modifiers And s_classModifiers, declaration:=Nothing, DeclarationKind.Class), identifier:=name.ToIdentifierToken(), typeParameterList:=GetTypeParameters(typeParameters)), [inherits]:=If(baseType IsNot Nothing, SyntaxFactory.SingletonList(SyntaxFactory.InheritsStatement(DirectCast(baseType, TypeSyntax))), Nothing), [implements]:=If(itypes IsNot Nothing, SyntaxFactory.SingletonList(SyntaxFactory.ImplementsStatement(SyntaxFactory.SeparatedList(itypes))), Nothing), members:=AsClassMembers(members)) End Function Private Function AsClassMembers(nodes As IEnumerable(Of SyntaxNode)) As SyntaxList(Of StatementSyntax) If nodes IsNot Nothing Then Return SyntaxFactory.List(nodes.Select(AddressOf AsClassMember).Where(Function(n) n IsNot Nothing)) Else Return Nothing End If End Function Private Function AsClassMember(node As SyntaxNode) As StatementSyntax Return TryCast(AsIsolatedDeclaration(node), StatementSyntax) End Function Public Overrides Function StructDeclaration( name As String, Optional typeParameters As IEnumerable(Of String) = Nothing, Optional accessibility As Accessibility = Nothing, Optional modifiers As DeclarationModifiers = Nothing, Optional interfaceTypes As IEnumerable(Of SyntaxNode) = Nothing, Optional members As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Dim itypes = If(interfaceTypes IsNot Nothing, interfaceTypes.Cast(Of TypeSyntax), Nothing) If itypes IsNot Nothing AndAlso itypes.Count = 0 Then itypes = Nothing End If Return SyntaxFactory.StructureBlock( structureStatement:=SyntaxFactory.StructureStatement( attributeLists:=Nothing, modifiers:=GetModifierList(accessibility, modifiers And s_structModifiers, declaration:=Nothing, DeclarationKind.Struct), identifier:=name.ToIdentifierToken(), typeParameterList:=GetTypeParameters(typeParameters)), [inherits]:=Nothing, [implements]:=If(itypes IsNot Nothing, SyntaxFactory.SingletonList(SyntaxFactory.ImplementsStatement(SyntaxFactory.SeparatedList(itypes))), Nothing), members:=If(members IsNot Nothing, SyntaxFactory.List(members.Cast(Of StatementSyntax)()), Nothing)) End Function Public Overrides Function InterfaceDeclaration( name As String, Optional typeParameters As IEnumerable(Of String) = Nothing, Optional accessibility As Accessibility = Nothing, Optional interfaceTypes As IEnumerable(Of SyntaxNode) = Nothing, Optional members As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Dim itypes = If(interfaceTypes IsNot Nothing, interfaceTypes.Cast(Of TypeSyntax), Nothing) If itypes IsNot Nothing AndAlso itypes.Count = 0 Then itypes = Nothing End If Return SyntaxFactory.InterfaceBlock( interfaceStatement:=SyntaxFactory.InterfaceStatement( attributeLists:=Nothing, modifiers:=GetModifierList(accessibility, DeclarationModifiers.None, declaration:=Nothing, DeclarationKind.Interface), identifier:=name.ToIdentifierToken(), typeParameterList:=GetTypeParameters(typeParameters)), [inherits]:=If(itypes IsNot Nothing, SyntaxFactory.SingletonList(SyntaxFactory.InheritsStatement(SyntaxFactory.SeparatedList(itypes))), Nothing), [implements]:=Nothing, members:=AsInterfaceMembers(members)) End Function Private Function AsInterfaceMembers(nodes As IEnumerable(Of SyntaxNode)) As SyntaxList(Of StatementSyntax) If nodes IsNot Nothing Then Return SyntaxFactory.List(nodes.Select(AddressOf AsInterfaceMember).Where(Function(n) n IsNot Nothing)) Else Return Nothing End If End Function Friend Overrides Function AsInterfaceMember(node As SyntaxNode) As SyntaxNode If node IsNot Nothing Then Select Case node.Kind Case SyntaxKind.FunctionBlock, SyntaxKind.SubBlock Return AsInterfaceMember(DirectCast(node, MethodBlockSyntax).BlockStatement) Case SyntaxKind.FunctionStatement, SyntaxKind.SubStatement Return Isolate(node, Function(d) DirectCast(d, MethodStatementSyntax).WithModifiers(Nothing)) Case SyntaxKind.PropertyBlock Return AsInterfaceMember(DirectCast(node, PropertyBlockSyntax).PropertyStatement) Case SyntaxKind.PropertyStatement Return Isolate( node, Function(d) Dim propertyStatement = DirectCast(d, PropertyStatementSyntax) Dim mods = SyntaxFactory.TokenList(propertyStatement.Modifiers.Where(Function(tk) tk.IsKind(SyntaxKind.ReadOnlyKeyword) Or tk.IsKind(SyntaxKind.DefaultKeyword))) Return propertyStatement.WithModifiers(mods) End Function) Case SyntaxKind.EventBlock Return AsInterfaceMember(DirectCast(node, EventBlockSyntax).EventStatement) Case SyntaxKind.EventStatement Return Isolate(node, Function(d) DirectCast(d, EventStatementSyntax).WithModifiers(Nothing).WithCustomKeyword(Nothing)) End Select End If Return Nothing End Function Public Overrides Function EnumDeclaration( name As String, Optional accessibility As Accessibility = Nothing, Optional modifiers As DeclarationModifiers = Nothing, Optional members As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Return EnumDeclaration(name, Nothing, accessibility, modifiers, members) End Function Friend Overrides Function EnumDeclaration(name As String, underlyingType As SyntaxNode, Optional accessibility As Accessibility = Accessibility.NotApplicable, Optional modifiers As DeclarationModifiers = Nothing, Optional members As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Dim underlyingTypeClause = If(underlyingType Is Nothing, Nothing, SyntaxFactory.SimpleAsClause(DirectCast(underlyingType, TypeSyntax))) Return SyntaxFactory.EnumBlock( enumStatement:=SyntaxFactory.EnumStatement( attributeLists:=Nothing, modifiers:=GetModifierList(accessibility, modifiers And GetAllowedModifiers(SyntaxKind.EnumStatement), declaration:=Nothing, DeclarationKind.Enum), identifier:=name.ToIdentifierToken(), underlyingType:=underlyingTypeClause), members:=AsEnumMembers(members)) End Function Public Overrides Function EnumMember(name As String, Optional expression As SyntaxNode = Nothing) As SyntaxNode Return SyntaxFactory.EnumMemberDeclaration( attributeLists:=Nothing, identifier:=name.ToIdentifierToken(), initializer:=If(expression IsNot Nothing, SyntaxFactory.EqualsValue(DirectCast(expression, ExpressionSyntax)), Nothing)) End Function Private Function AsEnumMembers(nodes As IEnumerable(Of SyntaxNode)) As SyntaxList(Of StatementSyntax) If nodes IsNot Nothing Then Return SyntaxFactory.List(nodes.Select(AddressOf AsEnumMember).Where(Function(n) n IsNot Nothing)) Else Return Nothing End If End Function Private Function AsEnumMember(node As SyntaxNode) As StatementSyntax Select Case node.Kind Case SyntaxKind.IdentifierName Dim id = DirectCast(node, IdentifierNameSyntax) Return DirectCast(EnumMember(id.Identifier.ValueText), EnumMemberDeclarationSyntax) Case SyntaxKind.FieldDeclaration Dim fd = DirectCast(node, FieldDeclarationSyntax) If fd.Declarators.Count = 1 Then Dim vd = fd.Declarators(0) If vd.Initializer IsNot Nothing AndAlso vd.Names.Count = 1 Then Return DirectCast(EnumMember(vd.Names(0).Identifier.ValueText, vd.Initializer.Value), EnumMemberDeclarationSyntax) End If End If End Select Return TryCast(node, EnumMemberDeclarationSyntax) End Function Public Overrides Function DelegateDeclaration( name As String, Optional parameters As IEnumerable(Of SyntaxNode) = Nothing, Optional typeParameters As IEnumerable(Of String) = Nothing, Optional returnType As SyntaxNode = Nothing, Optional accessibility As Accessibility = Accessibility.NotApplicable, Optional modifiers As DeclarationModifiers = Nothing) As SyntaxNode Dim kind = If(returnType Is Nothing, SyntaxKind.DelegateSubStatement, SyntaxKind.DelegateFunctionStatement) Return SyntaxFactory.DelegateStatement( kind:=kind, attributeLists:=Nothing, modifiers:=GetModifierList(accessibility, modifiers And GetAllowedModifiers(kind), declaration:=Nothing, DeclarationKind.Delegate), subOrFunctionKeyword:=If(kind = SyntaxKind.DelegateSubStatement, SyntaxFactory.Token(SyntaxKind.SubKeyword), SyntaxFactory.Token(SyntaxKind.FunctionKeyword)), identifier:=name.ToIdentifierToken(), typeParameterList:=GetTypeParameters(typeParameters), parameterList:=GetParameterList(parameters), asClause:=If(kind = SyntaxKind.DelegateFunctionStatement, SyntaxFactory.SimpleAsClause(DirectCast(returnType, TypeSyntax)), Nothing)) End Function Public Overrides Function CompilationUnit(declarations As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.CompilationUnit().WithImports(AsImports(declarations)).WithMembers(AsNamespaceMembers(declarations)) End Function Private Function AsImports(declarations As IEnumerable(Of SyntaxNode)) As SyntaxList(Of ImportsStatementSyntax) Return If(declarations Is Nothing, Nothing, SyntaxFactory.List(declarations.Select(AddressOf AsNamespaceImport).OfType(Of ImportsStatementSyntax)())) End Function Private Function AsNamespaceImport(node As SyntaxNode) As SyntaxNode Dim name = TryCast(node, NameSyntax) If name IsNot Nothing Then Return Me.NamespaceImportDeclaration(name) End If Return TryCast(node, ImportsStatementSyntax) End Function Private Shared Function AsNamespaceMembers(declarations As IEnumerable(Of SyntaxNode)) As SyntaxList(Of StatementSyntax) Return If(declarations Is Nothing, Nothing, SyntaxFactory.List(declarations.OfType(Of StatementSyntax)().Where(Function(s) Not TypeOf s Is ImportsStatementSyntax))) End Function Public Overrides Function NamespaceImportDeclaration(name As SyntaxNode) As SyntaxNode Return SyntaxFactory.ImportsStatement(SyntaxFactory.SingletonSeparatedList(Of ImportsClauseSyntax)(SyntaxFactory.SimpleImportsClause(DirectCast(name, NameSyntax)))) End Function Public Overrides Function AliasImportDeclaration(aliasIdentifierName As String, name As SyntaxNode) As SyntaxNode If TypeOf name Is NameSyntax Then Return SyntaxFactory.ImportsStatement(SyntaxFactory.SeparatedList(Of ImportsClauseSyntax).Add( SyntaxFactory.SimpleImportsClause( SyntaxFactory.ImportAliasClause(aliasIdentifierName), CType(name, NameSyntax)))) End If Throw New ArgumentException("name is not a NameSyntax.", NameOf(name)) End Function Public Overrides Function NamespaceDeclaration(name As SyntaxNode, nestedDeclarations As IEnumerable(Of SyntaxNode)) As SyntaxNode Dim imps As IEnumerable(Of StatementSyntax) = AsImports(nestedDeclarations) Dim members As IEnumerable(Of StatementSyntax) = AsNamespaceMembers(nestedDeclarations) ' put imports at start Dim statements = imps.Concat(members) Return SyntaxFactory.NamespaceBlock( SyntaxFactory.NamespaceStatement(DirectCast(name, NameSyntax)), members:=SyntaxFactory.List(statements)) End Function Public Overrides Function Attribute(name As SyntaxNode, Optional attributeArguments As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Dim attr = SyntaxFactory.Attribute( target:=Nothing, name:=DirectCast(name, TypeSyntax), argumentList:=AsArgumentList(attributeArguments)) Return AsAttributeList(attr) End Function Private Function AsArgumentList(arguments As IEnumerable(Of SyntaxNode)) As ArgumentListSyntax If arguments IsNot Nothing Then Return SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList(arguments.Select(AddressOf AsArgument))) Else Return Nothing End If End Function Public Overrides Function AttributeArgument(name As String, expression As SyntaxNode) As SyntaxNode Return Argument(name, RefKind.None, expression) End Function Public Overrides Function ClearTrivia(Of TNode As SyntaxNode)(node As TNode) As TNode If node IsNot Nothing Then Return node.WithLeadingTrivia(SyntaxFactory.ElasticMarker).WithTrailingTrivia(SyntaxFactory.ElasticMarker) Else Return Nothing End If End Function Private Function AsAttributeLists(attributes As IEnumerable(Of SyntaxNode)) As SyntaxList(Of AttributeListSyntax) If attributes IsNot Nothing Then Return SyntaxFactory.List(attributes.Select(AddressOf AsAttributeList)) Else Return Nothing End If End Function Private Function AsAttributeList(node As SyntaxNode) As AttributeListSyntax Dim attr = TryCast(node, AttributeSyntax) If attr IsNot Nothing Then Return SyntaxFactory.AttributeList(SyntaxFactory.SingletonSeparatedList(WithNoTarget(attr))) Else Return WithNoTargets(DirectCast(node, AttributeListSyntax)) End If End Function Private Overloads Function WithNoTargets(attrs As AttributeListSyntax) As AttributeListSyntax If (attrs.Attributes.Any(Function(a) a.Target IsNot Nothing)) Then Return attrs.WithAttributes(SyntaxFactory.SeparatedList(attrs.Attributes.Select(AddressOf WithAssemblyTarget))) Else Return attrs End If End Function Private Shared Function WithNoTarget(attr As AttributeSyntax) As AttributeSyntax Return attr.WithTarget(Nothing) End Function Friend Overrides Function GetTypeInheritance(declaration As SyntaxNode) As ImmutableArray(Of SyntaxNode) Dim typeDecl = TryCast(declaration, TypeBlockSyntax) If typeDecl Is Nothing Then Return ImmutableArray(Of SyntaxNode).Empty End If Dim builder = ArrayBuilder(Of SyntaxNode).GetInstance() builder.AddRange(typeDecl.Inherits) builder.AddRange(typeDecl.Implements) Return builder.ToImmutableAndFree() End Function Public Overrides Function GetAttributes(declaration As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Return Me.Flatten(declaration.GetAttributeLists()) End Function Public Overrides Function InsertAttributes(declaration As SyntaxNode, index As Integer, attributes As IEnumerable(Of SyntaxNode)) As SyntaxNode Return Isolate(declaration, Function(d) InsertAttributesInternal(d, index, attributes)) End Function Private Function InsertAttributesInternal(declaration As SyntaxNode, index As Integer, attributes As IEnumerable(Of SyntaxNode)) As SyntaxNode Dim newAttributes = AsAttributeLists(attributes) Dim existingAttributes = Me.GetAttributes(declaration) If index >= 0 AndAlso index < existingAttributes.Count Then Return Me.InsertNodesBefore(declaration, existingAttributes(index), newAttributes) ElseIf existingAttributes.Count > 0 Then Return Me.InsertNodesAfter(declaration, existingAttributes(existingAttributes.Count - 1), newAttributes) Else Dim lists = GetAttributeLists(declaration) Return Me.WithAttributeLists(declaration, lists.AddRange(AsAttributeLists(attributes))) End If End Function Private Shared Function HasAssemblyTarget(attr As AttributeSyntax) As Boolean Return attr.Target IsNot Nothing AndAlso attr.Target.AttributeModifier.IsKind(SyntaxKind.AssemblyKeyword) End Function Private Overloads Function WithAssemblyTargets(attrs As AttributeListSyntax) As AttributeListSyntax If attrs.Attributes.Any(Function(a) Not HasAssemblyTarget(a)) Then Return attrs.WithAttributes(SyntaxFactory.SeparatedList(attrs.Attributes.Select(AddressOf WithAssemblyTarget))) Else Return attrs End If End Function Private Overloads Function WithAssemblyTarget(attr As AttributeSyntax) As AttributeSyntax If Not HasAssemblyTarget(attr) Then Return attr.WithTarget(SyntaxFactory.AttributeTarget(SyntaxFactory.Token(SyntaxKind.AssemblyKeyword))) Else Return attr End If End Function Public Overrides Function GetReturnAttributes(declaration As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Return Me.Flatten(GetReturnAttributeLists(declaration)) End Function Public Overrides Function InsertReturnAttributes(declaration As SyntaxNode, index As Integer, attributes As IEnumerable(Of SyntaxNode)) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.FunctionBlock, SyntaxKind.FunctionStatement, SyntaxKind.DelegateFunctionStatement Return Isolate(declaration, Function(d) InsertReturnAttributesInternal(d, index, attributes)) Case Else Return declaration End Select End Function Private Function InsertReturnAttributesInternal(declaration As SyntaxNode, index As Integer, attributes As IEnumerable(Of SyntaxNode)) As SyntaxNode Dim newAttributes = AsAttributeLists(attributes) Dim existingReturnAttributes = Me.GetReturnAttributes(declaration) If index >= 0 AndAlso index < existingReturnAttributes.Count Then Return Me.InsertNodesBefore(declaration, existingReturnAttributes(index), newAttributes) ElseIf existingReturnAttributes.Count > 0 Then Return Me.InsertNodesAfter(declaration, existingReturnAttributes(existingReturnAttributes.Count - 1), newAttributes) Else Dim lists = GetReturnAttributeLists(declaration) Dim newLists = lists.AddRange(newAttributes) Return Me.WithReturnAttributeLists(declaration, newLists) End If End Function Private Shared Function GetReturnAttributeLists(declaration As SyntaxNode) As SyntaxList(Of AttributeListSyntax) Dim asClause = GetAsClause(declaration) If asClause IsNot Nothing Then Select Case declaration.Kind() Case SyntaxKind.FunctionBlock, SyntaxKind.FunctionStatement, SyntaxKind.DelegateFunctionStatement Return asClause.Attributes End Select End If Return Nothing End Function Private Function WithReturnAttributeLists(declaration As SyntaxNode, lists As IEnumerable(Of AttributeListSyntax)) As SyntaxNode If declaration Is Nothing Then Return Nothing End If Select Case declaration.Kind() Case SyntaxKind.FunctionBlock Dim fb = DirectCast(declaration, MethodBlockSyntax) Dim asClause = DirectCast(WithReturnAttributeLists(GetAsClause(declaration), lists), SimpleAsClauseSyntax) Return fb.WithSubOrFunctionStatement(fb.SubOrFunctionStatement.WithAsClause(asClause)) Case SyntaxKind.FunctionStatement Dim ms = DirectCast(declaration, MethodStatementSyntax) Dim asClause = DirectCast(WithReturnAttributeLists(GetAsClause(declaration), lists), SimpleAsClauseSyntax) Return ms.WithAsClause(asClause) Case SyntaxKind.DelegateFunctionStatement Dim df = DirectCast(declaration, DelegateStatementSyntax) Dim asClause = DirectCast(WithReturnAttributeLists(GetAsClause(declaration), lists), SimpleAsClauseSyntax) Return df.WithAsClause(asClause) Case SyntaxKind.SimpleAsClause Return DirectCast(declaration, SimpleAsClauseSyntax).WithAttributeLists(SyntaxFactory.List(lists)) Case Else Return Nothing End Select End Function Private Function WithAttributeLists(node As SyntaxNode, lists As IEnumerable(Of AttributeListSyntax)) As SyntaxNode Dim arg = SyntaxFactory.List(lists) Select Case node.Kind Case SyntaxKind.CompilationUnit 'convert to assembly target arg = SyntaxFactory.List(lists.Select(Function(lst) Me.WithAssemblyTargets(lst))) ' add as single attributes statement Return DirectCast(node, CompilationUnitSyntax).WithAttributes(SyntaxFactory.SingletonList(SyntaxFactory.AttributesStatement(arg))) Case SyntaxKind.ClassBlock Return DirectCast(node, ClassBlockSyntax).WithClassStatement(DirectCast(node, ClassBlockSyntax).ClassStatement.WithAttributeLists(arg)) Case SyntaxKind.ClassStatement Return DirectCast(node, ClassStatementSyntax).WithAttributeLists(arg) Case SyntaxKind.StructureBlock Return DirectCast(node, StructureBlockSyntax).WithStructureStatement(DirectCast(node, StructureBlockSyntax).StructureStatement.WithAttributeLists(arg)) Case SyntaxKind.StructureStatement Return DirectCast(node, StructureStatementSyntax).WithAttributeLists(arg) Case SyntaxKind.InterfaceBlock Return DirectCast(node, InterfaceBlockSyntax).WithInterfaceStatement(DirectCast(node, InterfaceBlockSyntax).InterfaceStatement.WithAttributeLists(arg)) Case SyntaxKind.InterfaceStatement Return DirectCast(node, InterfaceStatementSyntax).WithAttributeLists(arg) Case SyntaxKind.EnumBlock Return DirectCast(node, EnumBlockSyntax).WithEnumStatement(DirectCast(node, EnumBlockSyntax).EnumStatement.WithAttributeLists(arg)) Case SyntaxKind.EnumStatement Return DirectCast(node, EnumStatementSyntax).WithAttributeLists(arg) Case SyntaxKind.EnumMemberDeclaration Return DirectCast(node, EnumMemberDeclarationSyntax).WithAttributeLists(arg) Case SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement Return DirectCast(node, DelegateStatementSyntax).WithAttributeLists(arg) Case SyntaxKind.FieldDeclaration Return DirectCast(node, FieldDeclarationSyntax).WithAttributeLists(arg) Case SyntaxKind.FunctionBlock, SyntaxKind.SubBlock Return DirectCast(node, MethodBlockSyntax).WithSubOrFunctionStatement(DirectCast(node, MethodBlockSyntax).SubOrFunctionStatement.WithAttributeLists(arg)) Case SyntaxKind.FunctionStatement, SyntaxKind.SubStatement Return DirectCast(node, MethodStatementSyntax).WithAttributeLists(arg) Case SyntaxKind.ConstructorBlock Return DirectCast(node, ConstructorBlockSyntax).WithSubNewStatement(DirectCast(node, ConstructorBlockSyntax).SubNewStatement.WithAttributeLists(arg)) Case SyntaxKind.SubNewStatement Return DirectCast(node, SubNewStatementSyntax).WithAttributeLists(arg) Case SyntaxKind.Parameter Return DirectCast(node, ParameterSyntax).WithAttributeLists(arg) Case SyntaxKind.PropertyBlock Return DirectCast(node, PropertyBlockSyntax).WithPropertyStatement(DirectCast(node, PropertyBlockSyntax).PropertyStatement.WithAttributeLists(arg)) Case SyntaxKind.PropertyStatement Return DirectCast(node, PropertyStatementSyntax).WithAttributeLists(arg) Case SyntaxKind.OperatorBlock Return DirectCast(node, OperatorBlockSyntax).WithOperatorStatement(DirectCast(node, OperatorBlockSyntax).OperatorStatement.WithAttributeLists(arg)) Case SyntaxKind.OperatorStatement Return DirectCast(node, OperatorStatementSyntax).WithAttributeLists(arg) Case SyntaxKind.EventBlock Return DirectCast(node, EventBlockSyntax).WithEventStatement(DirectCast(node, EventBlockSyntax).EventStatement.WithAttributeLists(arg)) Case SyntaxKind.EventStatement Return DirectCast(node, EventStatementSyntax).WithAttributeLists(arg) Case SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock, SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RaiseEventAccessorBlock Return DirectCast(node, AccessorBlockSyntax).WithAccessorStatement(DirectCast(node, AccessorBlockSyntax).AccessorStatement.WithAttributeLists(arg)) Case SyntaxKind.GetAccessorStatement, SyntaxKind.SetAccessorStatement, SyntaxKind.AddHandlerAccessorStatement, SyntaxKind.RemoveHandlerAccessorStatement, SyntaxKind.RaiseEventAccessorStatement Return DirectCast(node, AccessorStatementSyntax).WithAttributeLists(arg) Case Else Return node End Select End Function Public Overrides Function GetDeclarationKind(declaration As SyntaxNode) As DeclarationKind Return SyntaxFacts.GetDeclarationKind(declaration) End Function Private Shared Function GetDeclarationCount(node As SyntaxNode) As Integer Return VisualBasicSyntaxFacts.GetDeclarationCount(node) End Function Private Shared Function IsChildOf(node As SyntaxNode, kind As SyntaxKind) As Boolean Return VisualBasicSyntaxFacts.IsChildOf(node, kind) End Function Private Shared Function IsChildOfVariableDeclaration(node As SyntaxNode) As Boolean Return VisualBasicSyntaxFacts.IsChildOfVariableDeclaration(node) End Function Private Function Isolate(declaration As SyntaxNode, editor As Func(Of SyntaxNode, SyntaxNode)) As SyntaxNode Dim isolated = AsIsolatedDeclaration(declaration) Return PreserveTrivia(isolated, editor) End Function Private Function GetFullDeclaration(declaration As SyntaxNode) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.ModifiedIdentifier If IsChildOf(declaration, SyntaxKind.VariableDeclarator) Then Return GetFullDeclaration(declaration.Parent) End If Case SyntaxKind.VariableDeclarator If IsChildOfVariableDeclaration(declaration) Then Return declaration.Parent End If Case SyntaxKind.Attribute If declaration.Parent IsNot Nothing Then Return declaration.Parent End If Case SyntaxKind.SimpleImportsClause, SyntaxKind.XmlNamespaceImportsClause If declaration.Parent IsNot Nothing Then Return declaration.Parent End If End Select Return declaration End Function Private Function AsIsolatedDeclaration(declaration As SyntaxNode) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.ModifiedIdentifier Dim full = GetFullDeclaration(declaration) If full IsNot declaration Then Return WithSingleVariable(full, DirectCast(declaration, ModifiedIdentifierSyntax)) End If Case SyntaxKind.Attribute Dim list = TryCast(declaration.Parent, AttributeListSyntax) If list IsNot Nothing Then Return list.WithAttributes(SyntaxFactory.SingletonSeparatedList(DirectCast(declaration, AttributeSyntax))) End If Case SyntaxKind.SimpleImportsClause, SyntaxKind.XmlNamespaceImportsClause Dim stmt = TryCast(declaration.Parent, ImportsStatementSyntax) If stmt IsNot Nothing Then Return stmt.WithImportsClauses(SyntaxFactory.SingletonSeparatedList(DirectCast(declaration, ImportsClauseSyntax))) End If End Select Return declaration End Function Private Shared Function WithSingleVariable(declaration As SyntaxNode, variable As ModifiedIdentifierSyntax) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.FieldDeclaration Dim fd = DirectCast(declaration, FieldDeclarationSyntax) Return ReplaceWithTrivia(declaration, fd.Declarators(0), fd.Declarators(0).WithNames(SyntaxFactory.SingletonSeparatedList(variable))) Case SyntaxKind.LocalDeclarationStatement Dim ld = DirectCast(declaration, LocalDeclarationStatementSyntax) Return ReplaceWithTrivia(declaration, ld.Declarators(0), ld.Declarators(0).WithNames(SyntaxFactory.SingletonSeparatedList(variable))) Case SyntaxKind.VariableDeclarator Dim vd = DirectCast(declaration, VariableDeclaratorSyntax) Return vd.WithNames(SyntaxFactory.SingletonSeparatedList(variable)) Case Else Return declaration End Select End Function Public Overrides Function GetName(declaration As SyntaxNode) As String Select Case declaration.Kind Case SyntaxKind.ClassBlock Return DirectCast(declaration, ClassBlockSyntax).BlockStatement.Identifier.ValueText Case SyntaxKind.StructureBlock Return DirectCast(declaration, StructureBlockSyntax).BlockStatement.Identifier.ValueText Case SyntaxKind.InterfaceBlock Return DirectCast(declaration, InterfaceBlockSyntax).BlockStatement.Identifier.ValueText Case SyntaxKind.EnumBlock Return DirectCast(declaration, EnumBlockSyntax).EnumStatement.Identifier.ValueText Case SyntaxKind.EnumMemberDeclaration Return DirectCast(declaration, EnumMemberDeclarationSyntax).Identifier.ValueText Case SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement Return DirectCast(declaration, DelegateStatementSyntax).Identifier.ValueText Case SyntaxKind.FunctionBlock, SyntaxKind.SubBlock Return DirectCast(declaration, MethodBlockSyntax).SubOrFunctionStatement.Identifier.ValueText Case SyntaxKind.FunctionStatement, SyntaxKind.SubStatement Return DirectCast(declaration, MethodStatementSyntax).Identifier.ValueText Case SyntaxKind.PropertyBlock Return DirectCast(declaration, PropertyBlockSyntax).PropertyStatement.Identifier.ValueText Case SyntaxKind.PropertyStatement Return DirectCast(declaration, PropertyStatementSyntax).Identifier.ValueText Case SyntaxKind.EventBlock Return DirectCast(declaration, EventBlockSyntax).EventStatement.Identifier.ValueText Case SyntaxKind.EventStatement Return DirectCast(declaration, EventStatementSyntax).Identifier.ValueText Case SyntaxKind.EventStatement Return DirectCast(declaration, EventStatementSyntax).Identifier.ValueText Case SyntaxKind.Parameter Return DirectCast(declaration, ParameterSyntax).Identifier.Identifier.ValueText Case SyntaxKind.NamespaceBlock Return DirectCast(declaration, NamespaceBlockSyntax).NamespaceStatement.Name.ToString() Case SyntaxKind.FieldDeclaration Dim fd = DirectCast(declaration, FieldDeclarationSyntax) If GetDeclarationCount(fd) = 1 Then Return fd.Declarators(0).Names(0).Identifier.ValueText End If Case SyntaxKind.LocalDeclarationStatement Dim ld = DirectCast(declaration, LocalDeclarationStatementSyntax) If GetDeclarationCount(ld) = 1 Then Return ld.Declarators(0).Names(0).Identifier.ValueText End If Case SyntaxKind.VariableDeclarator Dim vd = DirectCast(declaration, VariableDeclaratorSyntax) If vd.Names.Count = 1 Then Return vd.Names(0).Identifier.ValueText End If Case SyntaxKind.ModifiedIdentifier Return DirectCast(declaration, ModifiedIdentifierSyntax).Identifier.ValueText Case SyntaxKind.Attribute Return DirectCast(declaration, AttributeSyntax).Name.ToString() Case SyntaxKind.AttributeList Dim list = DirectCast(declaration, AttributeListSyntax) If list.Attributes.Count = 1 Then Return list.Attributes(0).Name.ToString() End If Case SyntaxKind.ImportsStatement Dim stmt = DirectCast(declaration, ImportsStatementSyntax) If stmt.ImportsClauses.Count = 1 Then Return GetName(stmt.ImportsClauses(0)) End If Case SyntaxKind.SimpleImportsClause Return DirectCast(declaration, SimpleImportsClauseSyntax).Name.ToString() End Select Return String.Empty End Function Public Overrides Function WithName(declaration As SyntaxNode, name As String) As SyntaxNode Return Isolate(declaration, Function(d) WithNameInternal(d, name)) End Function Private Function WithNameInternal(declaration As SyntaxNode, name As String) As SyntaxNode Dim id = name.ToIdentifierToken() Select Case declaration.Kind Case SyntaxKind.ClassBlock Return ReplaceWithTrivia(declaration, DirectCast(declaration, ClassBlockSyntax).BlockStatement.Identifier, id) Case SyntaxKind.StructureBlock Return ReplaceWithTrivia(declaration, DirectCast(declaration, StructureBlockSyntax).BlockStatement.Identifier, id) Case SyntaxKind.InterfaceBlock Return ReplaceWithTrivia(declaration, DirectCast(declaration, InterfaceBlockSyntax).BlockStatement.Identifier, id) Case SyntaxKind.EnumBlock Return ReplaceWithTrivia(declaration, DirectCast(declaration, EnumBlockSyntax).EnumStatement.Identifier, id) Case SyntaxKind.EnumMemberDeclaration Return ReplaceWithTrivia(declaration, DirectCast(declaration, EnumMemberDeclarationSyntax).Identifier, id) Case SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement Return ReplaceWithTrivia(declaration, DirectCast(declaration, DelegateStatementSyntax).Identifier, id) Case SyntaxKind.FunctionBlock, SyntaxKind.SubBlock Return ReplaceWithTrivia(declaration, DirectCast(declaration, MethodBlockSyntax).SubOrFunctionStatement.Identifier, id) Case SyntaxKind.FunctionStatement, SyntaxKind.SubStatement Return ReplaceWithTrivia(declaration, DirectCast(declaration, MethodStatementSyntax).Identifier, id) Case SyntaxKind.PropertyBlock Return ReplaceWithTrivia(declaration, DirectCast(declaration, PropertyBlockSyntax).PropertyStatement.Identifier, id) Case SyntaxKind.PropertyStatement Return ReplaceWithTrivia(declaration, DirectCast(declaration, PropertyStatementSyntax).Identifier, id) Case SyntaxKind.EventBlock Return ReplaceWithTrivia(declaration, DirectCast(declaration, EventBlockSyntax).EventStatement.Identifier, id) Case SyntaxKind.EventStatement Return ReplaceWithTrivia(declaration, DirectCast(declaration, EventStatementSyntax).Identifier, id) Case SyntaxKind.EventStatement Return ReplaceWithTrivia(declaration, DirectCast(declaration, EventStatementSyntax).Identifier, id) Case SyntaxKind.Parameter Return ReplaceWithTrivia(declaration, DirectCast(declaration, ParameterSyntax).Identifier.Identifier, id) Case SyntaxKind.NamespaceBlock Return ReplaceWithTrivia(declaration, DirectCast(declaration, NamespaceBlockSyntax).NamespaceStatement.Name, Me.DottedName(name)) Case SyntaxKind.LocalDeclarationStatement Dim ld = DirectCast(declaration, LocalDeclarationStatementSyntax) If ld.Declarators.Count = 1 AndAlso ld.Declarators(0).Names.Count = 1 Then Return ReplaceWithTrivia(declaration, ld.Declarators(0).Names(0).Identifier, id) End If Case SyntaxKind.FieldDeclaration Dim fd = DirectCast(declaration, FieldDeclarationSyntax) If fd.Declarators.Count = 1 AndAlso fd.Declarators(0).Names.Count = 1 Then Return ReplaceWithTrivia(declaration, fd.Declarators(0).Names(0).Identifier, id) End If Case SyntaxKind.Attribute Return ReplaceWithTrivia(declaration, DirectCast(declaration, AttributeSyntax).Name, Me.DottedName(name)) Case SyntaxKind.AttributeList Dim al = DirectCast(declaration, AttributeListSyntax) If al.Attributes.Count = 1 Then Return ReplaceWithTrivia(declaration, al.Attributes(0).Name, Me.DottedName(name)) End If Case SyntaxKind.ImportsStatement Dim stmt = DirectCast(declaration, ImportsStatementSyntax) If stmt.ImportsClauses.Count = 1 Then Dim clause = stmt.ImportsClauses(0) Select Case clause.Kind Case SyntaxKind.SimpleImportsClause Return ReplaceWithTrivia(declaration, DirectCast(clause, SimpleImportsClauseSyntax).Name, Me.DottedName(name)) End Select End If End Select Return declaration End Function Public Overrides Function [GetType](declaration As SyntaxNode) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.ModifiedIdentifier Dim vd = TryCast(declaration.Parent, VariableDeclaratorSyntax) If vd IsNot Nothing Then Return [GetType](vd) End If Case Else Dim asClause = GetAsClause(declaration) If asClause IsNot Nothing Then Return asClause.Type End If End Select Return Nothing End Function Public Overrides Function WithType(declaration As SyntaxNode, type As SyntaxNode) As SyntaxNode Return Isolate(declaration, Function(d) WithTypeInternal(d, type)) End Function Private Function WithTypeInternal(declaration As SyntaxNode, type As SyntaxNode) As SyntaxNode If type Is Nothing Then declaration = AsSub(declaration) Else declaration = AsFunction(declaration) End If Dim asClause = GetAsClause(declaration) If asClause IsNot Nothing Then If type IsNot Nothing Then Select Case asClause.Kind Case SyntaxKind.SimpleAsClause asClause = DirectCast(asClause, SimpleAsClauseSyntax).WithType(DirectCast(type, TypeSyntax)) Case SyntaxKind.AsNewClause Dim asNew = DirectCast(asClause, AsNewClauseSyntax) Select Case asNew.NewExpression.Kind Case SyntaxKind.ObjectCreationExpression asClause = asNew.WithNewExpression(DirectCast(asNew.NewExpression, ObjectCreationExpressionSyntax).WithType(DirectCast(type, TypeSyntax))) Case SyntaxKind.ArrayCreationExpression asClause = asNew.WithNewExpression(DirectCast(asNew.NewExpression, ArrayCreationExpressionSyntax).WithType(DirectCast(type, TypeSyntax))) End Select End Select Else asClause = Nothing End If ElseIf type IsNot Nothing Then asClause = SyntaxFactory.SimpleAsClause(DirectCast(type, TypeSyntax)) End If Return WithAsClause(declaration, asClause) End Function Private Shared Function GetAsClause(declaration As SyntaxNode) As AsClauseSyntax Select Case declaration.Kind Case SyntaxKind.DelegateFunctionStatement Return DirectCast(declaration, DelegateStatementSyntax).AsClause Case SyntaxKind.FunctionBlock Return DirectCast(declaration, MethodBlockSyntax).SubOrFunctionStatement.AsClause Case SyntaxKind.FunctionStatement Return DirectCast(declaration, MethodStatementSyntax).AsClause Case SyntaxKind.PropertyBlock Return DirectCast(declaration, PropertyBlockSyntax).PropertyStatement.AsClause Case SyntaxKind.PropertyStatement Return DirectCast(declaration, PropertyStatementSyntax).AsClause Case SyntaxKind.EventBlock Return DirectCast(declaration, EventBlockSyntax).EventStatement.AsClause Case SyntaxKind.EventStatement Return DirectCast(declaration, EventStatementSyntax).AsClause Case SyntaxKind.Parameter Return DirectCast(declaration, ParameterSyntax).AsClause Case SyntaxKind.FieldDeclaration Dim fd = DirectCast(declaration, FieldDeclarationSyntax) If fd.Declarators.Count = 1 Then Return fd.Declarators(0).AsClause End If Case SyntaxKind.LocalDeclarationStatement Dim ld = DirectCast(declaration, LocalDeclarationStatementSyntax) If ld.Declarators.Count = 1 Then Return ld.Declarators(0).AsClause End If Case SyntaxKind.VariableDeclarator Return DirectCast(declaration, VariableDeclaratorSyntax).AsClause Case SyntaxKind.ModifiedIdentifier Dim vd = TryCast(declaration.Parent, VariableDeclaratorSyntax) If vd IsNot Nothing Then Return vd.AsClause End If End Select Return Nothing End Function Private Shared Function WithAsClause(declaration As SyntaxNode, asClause As AsClauseSyntax) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.DelegateFunctionStatement Return DirectCast(declaration, DelegateStatementSyntax).WithAsClause(DirectCast(asClause, SimpleAsClauseSyntax)) Case SyntaxKind.FieldDeclaration Dim fd = DirectCast(declaration, FieldDeclarationSyntax) If fd.Declarators.Count = 1 Then Return ReplaceWithTrivia(declaration, fd.Declarators(0), fd.Declarators(0).WithAsClause(asClause)) End If Case SyntaxKind.FunctionBlock Return DirectCast(declaration, MethodBlockSyntax).WithSubOrFunctionStatement(DirectCast(declaration, MethodBlockSyntax).SubOrFunctionStatement.WithAsClause(DirectCast(asClause, SimpleAsClauseSyntax))) Case SyntaxKind.FunctionStatement Return DirectCast(declaration, MethodStatementSyntax).WithAsClause(DirectCast(asClause, SimpleAsClauseSyntax)) Case SyntaxKind.PropertyBlock Return DirectCast(declaration, PropertyBlockSyntax).WithPropertyStatement(DirectCast(declaration, PropertyBlockSyntax).PropertyStatement.WithAsClause(asClause)) Case SyntaxKind.PropertyStatement Return DirectCast(declaration, PropertyStatementSyntax).WithAsClause(asClause) Case SyntaxKind.EventBlock Return DirectCast(declaration, EventBlockSyntax).WithEventStatement(DirectCast(declaration, EventBlockSyntax).EventStatement.WithAsClause(DirectCast(asClause, SimpleAsClauseSyntax))) Case SyntaxKind.EventStatement Return DirectCast(declaration, EventStatementSyntax).WithAsClause(DirectCast(asClause, SimpleAsClauseSyntax)) Case SyntaxKind.Parameter Return DirectCast(declaration, ParameterSyntax).WithAsClause(DirectCast(asClause, SimpleAsClauseSyntax)) Case SyntaxKind.LocalDeclarationStatement Dim ld = DirectCast(declaration, LocalDeclarationStatementSyntax) If ld.Declarators.Count = 1 Then Return ReplaceWithTrivia(declaration, ld.Declarators(0), ld.Declarators(0).WithAsClause(asClause)) End If Case SyntaxKind.VariableDeclarator Return DirectCast(declaration, VariableDeclaratorSyntax).WithAsClause(asClause) End Select Return declaration End Function Private Function AsFunction(declaration As SyntaxNode) As SyntaxNode Return Isolate(declaration, AddressOf AsFunctionInternal) End Function Private Function AsFunctionInternal(declaration As SyntaxNode) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.SubBlock Dim sb = DirectCast(declaration, MethodBlockSyntax) Return SyntaxFactory.MethodBlock( SyntaxKind.FunctionBlock, DirectCast(AsFunction(sb.BlockStatement), MethodStatementSyntax), sb.Statements, SyntaxFactory.EndBlockStatement( SyntaxKind.EndFunctionStatement, sb.EndBlockStatement.EndKeyword, SyntaxFactory.Token(sb.EndBlockStatement.BlockKeyword.LeadingTrivia, SyntaxKind.FunctionKeyword, sb.EndBlockStatement.BlockKeyword.TrailingTrivia) )) Case SyntaxKind.SubStatement Dim ss = DirectCast(declaration, MethodStatementSyntax) Return SyntaxFactory.MethodStatement( SyntaxKind.FunctionStatement, ss.AttributeLists, ss.Modifiers, SyntaxFactory.Token(ss.DeclarationKeyword.LeadingTrivia, SyntaxKind.FunctionKeyword, ss.DeclarationKeyword.TrailingTrivia), ss.Identifier, ss.TypeParameterList, ss.ParameterList, SyntaxFactory.SimpleAsClause(SyntaxFactory.IdentifierName("Object")), ss.HandlesClause, ss.ImplementsClause) Case SyntaxKind.DelegateSubStatement Dim ds = DirectCast(declaration, DelegateStatementSyntax) Return SyntaxFactory.DelegateStatement( SyntaxKind.DelegateFunctionStatement, ds.AttributeLists, ds.Modifiers, SyntaxFactory.Token(ds.DeclarationKeyword.LeadingTrivia, SyntaxKind.FunctionKeyword, ds.DeclarationKeyword.TrailingTrivia), ds.Identifier, ds.TypeParameterList, ds.ParameterList, SyntaxFactory.SimpleAsClause(SyntaxFactory.IdentifierName("Object"))) Case SyntaxKind.MultiLineSubLambdaExpression Dim ml = DirectCast(declaration, MultiLineLambdaExpressionSyntax) Return SyntaxFactory.MultiLineLambdaExpression( SyntaxKind.MultiLineFunctionLambdaExpression, DirectCast(AsFunction(ml.SubOrFunctionHeader), LambdaHeaderSyntax), ml.Statements, SyntaxFactory.EndBlockStatement( SyntaxKind.EndFunctionStatement, ml.EndSubOrFunctionStatement.EndKeyword, SyntaxFactory.Token(ml.EndSubOrFunctionStatement.BlockKeyword.LeadingTrivia, SyntaxKind.FunctionKeyword, ml.EndSubOrFunctionStatement.BlockKeyword.TrailingTrivia) )) Case SyntaxKind.SingleLineSubLambdaExpression Dim sl = DirectCast(declaration, SingleLineLambdaExpressionSyntax) Return SyntaxFactory.SingleLineLambdaExpression( SyntaxKind.SingleLineFunctionLambdaExpression, DirectCast(AsFunction(sl.SubOrFunctionHeader), LambdaHeaderSyntax), sl.Body) Case SyntaxKind.SubLambdaHeader Dim lh = DirectCast(declaration, LambdaHeaderSyntax) Return SyntaxFactory.LambdaHeader( SyntaxKind.FunctionLambdaHeader, lh.AttributeLists, lh.Modifiers, SyntaxFactory.Token(lh.DeclarationKeyword.LeadingTrivia, SyntaxKind.FunctionKeyword, lh.DeclarationKeyword.TrailingTrivia), lh.ParameterList, asClause:=Nothing) Case SyntaxKind.DeclareSubStatement Dim ds = DirectCast(declaration, DeclareStatementSyntax) Return SyntaxFactory.DeclareStatement( SyntaxKind.DeclareFunctionStatement, ds.AttributeLists, ds.Modifiers, ds.CharsetKeyword, SyntaxFactory.Token(ds.DeclarationKeyword.LeadingTrivia, SyntaxKind.FunctionKeyword, ds.DeclarationKeyword.TrailingTrivia), ds.Identifier, ds.LibraryName, ds.AliasName, ds.ParameterList, SyntaxFactory.SimpleAsClause(SyntaxFactory.IdentifierName("Object"))) Case Else Return declaration End Select End Function Private Function AsSub(declaration As SyntaxNode) As SyntaxNode Return Isolate(declaration, AddressOf AsSubInternal) End Function Private Function AsSubInternal(declaration As SyntaxNode) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.FunctionBlock Dim mb = DirectCast(declaration, MethodBlockSyntax) Return SyntaxFactory.MethodBlock( SyntaxKind.SubBlock, DirectCast(AsSub(mb.BlockStatement), MethodStatementSyntax), mb.Statements, SyntaxFactory.EndBlockStatement( SyntaxKind.EndSubStatement, mb.EndBlockStatement.EndKeyword, SyntaxFactory.Token(mb.EndBlockStatement.BlockKeyword.LeadingTrivia, SyntaxKind.SubKeyword, mb.EndBlockStatement.BlockKeyword.TrailingTrivia) )) Case SyntaxKind.FunctionStatement Dim ms = DirectCast(declaration, MethodStatementSyntax) Return SyntaxFactory.MethodStatement( SyntaxKind.SubStatement, ms.AttributeLists, ms.Modifiers, SyntaxFactory.Token(ms.DeclarationKeyword.LeadingTrivia, SyntaxKind.SubKeyword, ms.DeclarationKeyword.TrailingTrivia), ms.Identifier, ms.TypeParameterList, ms.ParameterList, asClause:=Nothing, handlesClause:=ms.HandlesClause, implementsClause:=ms.ImplementsClause) Case SyntaxKind.DelegateFunctionStatement Dim ds = DirectCast(declaration, DelegateStatementSyntax) Return SyntaxFactory.DelegateStatement( SyntaxKind.DelegateSubStatement, ds.AttributeLists, ds.Modifiers, SyntaxFactory.Token(ds.DeclarationKeyword.LeadingTrivia, SyntaxKind.SubKeyword, ds.DeclarationKeyword.TrailingTrivia), ds.Identifier, ds.TypeParameterList, ds.ParameterList, asClause:=Nothing) Case SyntaxKind.MultiLineFunctionLambdaExpression Dim ml = DirectCast(declaration, MultiLineLambdaExpressionSyntax) Return SyntaxFactory.MultiLineLambdaExpression( SyntaxKind.MultiLineSubLambdaExpression, DirectCast(AsSub(ml.SubOrFunctionHeader), LambdaHeaderSyntax), ml.Statements, SyntaxFactory.EndBlockStatement( SyntaxKind.EndSubStatement, ml.EndSubOrFunctionStatement.EndKeyword, SyntaxFactory.Token(ml.EndSubOrFunctionStatement.BlockKeyword.LeadingTrivia, SyntaxKind.SubKeyword, ml.EndSubOrFunctionStatement.BlockKeyword.TrailingTrivia) )) Case SyntaxKind.SingleLineFunctionLambdaExpression Dim sl = DirectCast(declaration, SingleLineLambdaExpressionSyntax) Return SyntaxFactory.SingleLineLambdaExpression( SyntaxKind.SingleLineSubLambdaExpression, DirectCast(AsSub(sl.SubOrFunctionHeader), LambdaHeaderSyntax), sl.Body) Case SyntaxKind.FunctionLambdaHeader Dim lh = DirectCast(declaration, LambdaHeaderSyntax) Return SyntaxFactory.LambdaHeader( SyntaxKind.SubLambdaHeader, lh.AttributeLists, lh.Modifiers, SyntaxFactory.Token(lh.DeclarationKeyword.LeadingTrivia, SyntaxKind.SubKeyword, lh.DeclarationKeyword.TrailingTrivia), lh.ParameterList, asClause:=Nothing) Case SyntaxKind.DeclareFunctionStatement Dim ds = DirectCast(declaration, DeclareStatementSyntax) Return SyntaxFactory.DeclareStatement( SyntaxKind.DeclareSubStatement, ds.AttributeLists, ds.Modifiers, ds.CharsetKeyword, SyntaxFactory.Token(ds.DeclarationKeyword.LeadingTrivia, SyntaxKind.SubKeyword, ds.DeclarationKeyword.TrailingTrivia), ds.Identifier, ds.LibraryName, ds.AliasName, ds.ParameterList, asClause:=Nothing) Case Else Return declaration End Select End Function Public Overrides Function GetModifiers(declaration As SyntaxNode) As DeclarationModifiers Dim tokens = SyntaxFacts.GetModifierTokens(declaration) Dim acc As Accessibility Dim mods As DeclarationModifiers Dim isDefault As Boolean SyntaxFacts.GetAccessibilityAndModifiers(tokens, acc, mods, isDefault) Return mods End Function Public Overrides Function WithModifiers(declaration As SyntaxNode, modifiers As DeclarationModifiers) As SyntaxNode Return Isolate(declaration, Function(d) Me.WithModifiersInternal(d, modifiers)) End Function Private Function WithModifiersInternal(declaration As SyntaxNode, modifiers As DeclarationModifiers) As SyntaxNode Dim tokens = SyntaxFacts.GetModifierTokens(declaration) Dim acc As Accessibility Dim currentMods As DeclarationModifiers Dim isDefault As Boolean SyntaxFacts.GetAccessibilityAndModifiers(tokens, acc, currentMods, isDefault) If currentMods <> modifiers Then Dim newTokens = GetModifierList(acc, modifiers And GetAllowedModifiers(declaration.Kind), declaration, GetDeclarationKind(declaration), isDefault) Return WithModifierTokens(declaration, Merge(tokens, newTokens)) Else Return declaration End If End Function Private Function WithModifierTokens(declaration As SyntaxNode, tokens As SyntaxTokenList) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.ClassBlock Return DirectCast(declaration, ClassBlockSyntax).WithClassStatement(DirectCast(declaration, ClassBlockSyntax).ClassStatement.WithModifiers(tokens)) Case SyntaxKind.ClassStatement Return DirectCast(declaration, ClassStatementSyntax).WithModifiers(tokens) Case SyntaxKind.StructureBlock Return DirectCast(declaration, StructureBlockSyntax).WithStructureStatement(DirectCast(declaration, StructureBlockSyntax).StructureStatement.WithModifiers(tokens)) Case SyntaxKind.StructureStatement Return DirectCast(declaration, StructureStatementSyntax).WithModifiers(tokens) Case SyntaxKind.InterfaceBlock Return DirectCast(declaration, InterfaceBlockSyntax).WithInterfaceStatement(DirectCast(declaration, InterfaceBlockSyntax).InterfaceStatement.WithModifiers(tokens)) Case SyntaxKind.InterfaceStatement Return DirectCast(declaration, InterfaceStatementSyntax).WithModifiers(tokens) Case SyntaxKind.EnumBlock Return DirectCast(declaration, EnumBlockSyntax).WithEnumStatement(DirectCast(declaration, EnumBlockSyntax).EnumStatement.WithModifiers(tokens)) Case SyntaxKind.EnumStatement Return DirectCast(declaration, EnumStatementSyntax).WithModifiers(tokens) Case SyntaxKind.ModuleBlock Return DirectCast(declaration, ModuleBlockSyntax).WithModuleStatement(DirectCast(declaration, ModuleBlockSyntax).ModuleStatement.WithModifiers(tokens)) Case SyntaxKind.ModuleStatement Return DirectCast(declaration, ModuleStatementSyntax).WithModifiers(tokens) Case SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement Return DirectCast(declaration, DelegateStatementSyntax).WithModifiers(tokens) Case SyntaxKind.FieldDeclaration Return DirectCast(declaration, FieldDeclarationSyntax).WithModifiers(tokens) Case SyntaxKind.FunctionBlock, SyntaxKind.SubBlock Return DirectCast(declaration, MethodBlockSyntax).WithSubOrFunctionStatement(DirectCast(declaration, MethodBlockSyntax).SubOrFunctionStatement.WithModifiers(tokens)) Case SyntaxKind.ConstructorBlock Return DirectCast(declaration, ConstructorBlockSyntax).WithSubNewStatement(DirectCast(declaration, ConstructorBlockSyntax).SubNewStatement.WithModifiers(tokens)) Case SyntaxKind.FunctionStatement, SyntaxKind.SubStatement Return DirectCast(declaration, MethodStatementSyntax).WithModifiers(tokens) Case SyntaxKind.SubNewStatement Return DirectCast(declaration, SubNewStatementSyntax).WithModifiers(tokens) Case SyntaxKind.PropertyBlock Return DirectCast(declaration, PropertyBlockSyntax).WithPropertyStatement(DirectCast(declaration, PropertyBlockSyntax).PropertyStatement.WithModifiers(tokens)) Case SyntaxKind.PropertyStatement Return DirectCast(declaration, PropertyStatementSyntax).WithModifiers(tokens) Case SyntaxKind.OperatorBlock Return DirectCast(declaration, OperatorBlockSyntax).WithOperatorStatement(DirectCast(declaration, OperatorBlockSyntax).OperatorStatement.WithModifiers(tokens)) Case SyntaxKind.OperatorStatement Return DirectCast(declaration, OperatorStatementSyntax).WithModifiers(tokens) Case SyntaxKind.EventBlock Return DirectCast(declaration, EventBlockSyntax).WithEventStatement(DirectCast(declaration, EventBlockSyntax).EventStatement.WithModifiers(tokens)) Case SyntaxKind.EventStatement Return DirectCast(declaration, EventStatementSyntax).WithModifiers(tokens) Case SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock, SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RaiseEventAccessorBlock Return DirectCast(declaration, AccessorBlockSyntax).WithAccessorStatement( DirectCast(Me.WithModifierTokens(DirectCast(declaration, AccessorBlockSyntax).AccessorStatement, tokens), AccessorStatementSyntax)) Case SyntaxKind.GetAccessorStatement, SyntaxKind.SetAccessorStatement, SyntaxKind.AddHandlerAccessorStatement, SyntaxKind.RemoveHandlerAccessorStatement, SyntaxKind.RaiseEventAccessorStatement Return DirectCast(declaration, AccessorStatementSyntax).WithModifiers(tokens) Case Else Return declaration End Select End Function Public Overrides Function GetAccessibility(declaration As SyntaxNode) As Accessibility Return SyntaxFacts.GetAccessibility(declaration) End Function Public Overrides Function WithAccessibility(declaration As SyntaxNode, accessibility As Accessibility) As SyntaxNode If Not SyntaxFacts.CanHaveAccessibility(declaration) AndAlso accessibility <> Accessibility.NotApplicable Then Return declaration End If Return Isolate(declaration, Function(d) Me.WithAccessibilityInternal(d, accessibility)) End Function Private Function WithAccessibilityInternal(declaration As SyntaxNode, accessibility As Accessibility) As SyntaxNode If Not SyntaxFacts.CanHaveAccessibility(declaration) Then Return declaration End If Dim tokens = SyntaxFacts.GetModifierTokens(declaration) Dim currentAcc As Accessibility Dim mods As DeclarationModifiers Dim isDefault As Boolean SyntaxFacts.GetAccessibilityAndModifiers(tokens, currentAcc, mods, isDefault) If currentAcc = accessibility Then Return declaration End If Dim newTokens = GetModifierList(accessibility, mods, declaration, GetDeclarationKind(declaration), isDefault) 'GetDeclarationKind returns None for Field if the count is > 1 'To handle multiple declarations on a field if the Accessibility is NotApplicable, we need to add the Dim If declaration.Kind = SyntaxKind.FieldDeclaration AndAlso accessibility = Accessibility.NotApplicable AndAlso newTokens.Count = 0 Then ' Add the Dim newTokens = newTokens.Add(SyntaxFactory.Token(SyntaxKind.DimKeyword)) End If Return WithModifierTokens(declaration, Merge(tokens, newTokens)) End Function Private Shared Function GetModifierList(accessibility As Accessibility, modifiers As DeclarationModifiers, declaration As SyntaxNode, kind As DeclarationKind, Optional isDefault As Boolean = False) As SyntaxTokenList Dim _list = SyntaxFactory.TokenList() ' While partial must always be last in C#, its preferred position in VB is to be first, ' even before accessibility modifiers. This order is enforced by line commit. If modifiers.IsPartial Then _list = _list.Add(SyntaxFactory.Token(SyntaxKind.PartialKeyword)) End If If isDefault Then _list = _list.Add(SyntaxFactory.Token(SyntaxKind.DefaultKeyword)) End If Select Case (accessibility) Case Accessibility.Internal _list = _list.Add(SyntaxFactory.Token(SyntaxKind.FriendKeyword)) Case Accessibility.Public _list = _list.Add(SyntaxFactory.Token(SyntaxKind.PublicKeyword)) Case Accessibility.Private _list = _list.Add(SyntaxFactory.Token(SyntaxKind.PrivateKeyword)) Case Accessibility.Protected _list = _list.Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword)) Case Accessibility.ProtectedOrInternal _list = _list.Add(SyntaxFactory.Token(SyntaxKind.FriendKeyword)).Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword)) Case Accessibility.ProtectedAndInternal _list = _list.Add(SyntaxFactory.Token(SyntaxKind.PrivateKeyword)).Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword)) Case Accessibility.NotApplicable Case Else Throw New NotSupportedException(String.Format("Accessibility '{0}' not supported.", accessibility)) End Select Dim isClass = kind = DeclarationKind.Class OrElse declaration.IsKind(SyntaxKind.ClassStatement) If modifiers.IsAbstract Then If isClass Then _list = _list.Add(SyntaxFactory.Token(SyntaxKind.MustInheritKeyword)) Else _list = _list.Add(SyntaxFactory.Token(SyntaxKind.MustOverrideKeyword)) End If End If If modifiers.IsNew Then _list = _list.Add(SyntaxFactory.Token(SyntaxKind.ShadowsKeyword)) End If If modifiers.IsSealed Then If isClass Then _list = _list.Add(SyntaxFactory.Token(SyntaxKind.NotInheritableKeyword)) Else _list = _list.Add(SyntaxFactory.Token(SyntaxKind.NotOverridableKeyword)) End If End If If modifiers.IsOverride Then _list = _list.Add(SyntaxFactory.Token(SyntaxKind.OverridesKeyword)) End If If modifiers.IsVirtual Then _list = _list.Add(SyntaxFactory.Token(SyntaxKind.OverridableKeyword)) End If If modifiers.IsStatic Then _list = _list.Add(SyntaxFactory.Token(SyntaxKind.SharedKeyword)) End If If modifiers.IsAsync Then _list = _list.Add(SyntaxFactory.Token(SyntaxKind.AsyncKeyword)) End If If modifiers.IsConst Then _list = _list.Add(SyntaxFactory.Token(SyntaxKind.ConstKeyword)) End If If modifiers.IsReadOnly Then _list = _list.Add(SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword)) End If If modifiers.IsWriteOnly Then _list = _list.Add(SyntaxFactory.Token(SyntaxKind.WriteOnlyKeyword)) End If If modifiers.IsUnsafe Then Throw New NotSupportedException("Unsupported modifier") ''''_list = _list.Add(SyntaxFactory.Token(SyntaxKind.UnsafeKeyword)) End If If modifiers.IsWithEvents Then _list = _list.Add(SyntaxFactory.Token(SyntaxKind.WithEventsKeyword)) End If If (kind = DeclarationKind.Field AndAlso _list.Count = 0) Then _list = _list.Add(SyntaxFactory.Token(SyntaxKind.DimKeyword)) End If Return _list End Function Private Shared Function GetTypeParameters(typeParameterNames As IEnumerable(Of String)) As TypeParameterListSyntax If typeParameterNames Is Nothing Then Return Nothing End If Dim typeParameterList = SyntaxFactory.TypeParameterList(SyntaxFactory.SeparatedList(typeParameterNames.Select(Function(name) SyntaxFactory.TypeParameter(name)))) If typeParameterList.Parameters.Count = 0 Then typeParameterList = Nothing End If Return typeParameterList End Function Public Overrides Function WithTypeParameters(declaration As SyntaxNode, typeParameterNames As IEnumerable(Of String)) As SyntaxNode Dim typeParameterList = GetTypeParameters(typeParameterNames) Return ReplaceTypeParameterList(declaration, Function(old) typeParameterList) End Function Private Shared Function ReplaceTypeParameterList(declaration As SyntaxNode, replacer As Func(Of TypeParameterListSyntax, TypeParameterListSyntax)) As SyntaxNode Dim method = TryCast(declaration, MethodStatementSyntax) If method IsNot Nothing Then Return method.WithTypeParameterList(replacer(method.TypeParameterList)) End If Dim methodBlock = TryCast(declaration, MethodBlockSyntax) If methodBlock IsNot Nothing Then Return methodBlock.WithSubOrFunctionStatement(methodBlock.SubOrFunctionStatement.WithTypeParameterList(replacer(methodBlock.SubOrFunctionStatement.TypeParameterList))) End If Dim classBlock = TryCast(declaration, ClassBlockSyntax) If classBlock IsNot Nothing Then Return classBlock.WithClassStatement(classBlock.ClassStatement.WithTypeParameterList(replacer(classBlock.ClassStatement.TypeParameterList))) End If Dim structureBlock = TryCast(declaration, StructureBlockSyntax) If structureBlock IsNot Nothing Then Return structureBlock.WithStructureStatement(structureBlock.StructureStatement.WithTypeParameterList(replacer(structureBlock.StructureStatement.TypeParameterList))) End If Dim interfaceBlock = TryCast(declaration, InterfaceBlockSyntax) If interfaceBlock IsNot Nothing Then Return interfaceBlock.WithInterfaceStatement(interfaceBlock.InterfaceStatement.WithTypeParameterList(replacer(interfaceBlock.InterfaceStatement.TypeParameterList))) End If Return declaration End Function Friend Overrides Function WithExplicitInterfaceImplementations(declaration As SyntaxNode, explicitInterfaceImplementations As ImmutableArray(Of ISymbol)) As SyntaxNode If TypeOf declaration Is MethodStatementSyntax Then Dim methodStatement = DirectCast(declaration, MethodStatementSyntax) Dim interfaceMembers = explicitInterfaceImplementations.Select(AddressOf GenerateInterfaceMember) Return methodStatement.WithImplementsClause( SyntaxFactory.ImplementsClause(SyntaxFactory.SeparatedList(interfaceMembers))) ElseIf TypeOf declaration Is MethodBlockSyntax Then Dim methodBlock = DirectCast(declaration, MethodBlockSyntax) Return methodBlock.WithSubOrFunctionStatement( DirectCast(WithExplicitInterfaceImplementations(methodBlock.SubOrFunctionStatement, explicitInterfaceImplementations), MethodStatementSyntax)) Else Debug.Fail("Unhandled kind to add explicit implementations for: " & declaration.Kind()) End If Return declaration End Function Private Function GenerateInterfaceMember(method As ISymbol) As QualifiedNameSyntax Dim interfaceName = method.ContainingType.GenerateTypeSyntax() Return SyntaxFactory.QualifiedName( DirectCast(interfaceName, NameSyntax), SyntaxFactory.IdentifierName(method.Name)) End Function Public Overrides Function WithTypeConstraint(declaration As SyntaxNode, typeParameterName As String, kinds As SpecialTypeConstraintKind, Optional types As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Dim constraints = SyntaxFactory.SeparatedList(Of ConstraintSyntax) If types IsNot Nothing Then constraints = constraints.AddRange(types.Select(Function(t) SyntaxFactory.TypeConstraint(DirectCast(t, TypeSyntax)))) End If If (kinds And SpecialTypeConstraintKind.Constructor) <> 0 Then constraints = constraints.Add(SyntaxFactory.NewConstraint(SyntaxFactory.Token(SyntaxKind.NewKeyword))) End If Dim isReferenceType = (kinds And SpecialTypeConstraintKind.ReferenceType) <> 0 Dim isValueType = (kinds And SpecialTypeConstraintKind.ValueType) <> 0 If isReferenceType Then constraints = constraints.Insert(0, SyntaxFactory.ClassConstraint(SyntaxFactory.Token(SyntaxKind.ClassKeyword))) ElseIf isValueType Then constraints = constraints.Insert(0, SyntaxFactory.StructureConstraint(SyntaxFactory.Token(SyntaxKind.StructureKeyword))) End If Dim clause As TypeParameterConstraintClauseSyntax = Nothing If constraints.Count = 1 Then clause = SyntaxFactory.TypeParameterSingleConstraintClause(constraints(0)) ElseIf constraints.Count > 1 Then clause = SyntaxFactory.TypeParameterMultipleConstraintClause(constraints) End If Return ReplaceTypeParameterList(declaration, Function(old) WithTypeParameterConstraints(old, typeParameterName, clause)) End Function Private Shared Function WithTypeParameterConstraints(typeParameterList As TypeParameterListSyntax, typeParameterName As String, clause As TypeParameterConstraintClauseSyntax) As TypeParameterListSyntax If typeParameterList IsNot Nothing Then Dim typeParameter = typeParameterList.Parameters.FirstOrDefault(Function(tp) tp.Identifier.ToString() = typeParameterName) If typeParameter IsNot Nothing Then Return typeParameterList.WithParameters(typeParameterList.Parameters.Replace(typeParameter, typeParameter.WithTypeParameterConstraintClause(clause))) End If End If Return typeParameterList End Function Public Overrides Function GetParameters(declaration As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Dim list = declaration.GetParameterList() Return If(list IsNot Nothing, list.Parameters, SpecializedCollections.EmptyReadOnlyList(Of SyntaxNode)) End Function Public Overrides Function InsertParameters(declaration As SyntaxNode, index As Integer, parameters As IEnumerable(Of SyntaxNode)) As SyntaxNode Dim currentList = declaration.GetParameterList() Dim newList = GetParameterList(parameters) If currentList IsNot Nothing Then Return WithParameterList(declaration, currentList.WithParameters(currentList.Parameters.InsertRange(index, newList.Parameters))) Else Return WithParameterList(declaration, newList) End If End Function Public Overrides Function GetSwitchSections(switchStatement As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Dim statement = TryCast(switchStatement, SelectBlockSyntax) If statement Is Nothing Then Return SpecializedCollections.EmptyReadOnlyList(Of SyntaxNode) End If Return statement.CaseBlocks End Function Public Overrides Function InsertSwitchSections(switchStatement As SyntaxNode, index As Integer, switchSections As IEnumerable(Of SyntaxNode)) As SyntaxNode Dim statement = TryCast(switchStatement, SelectBlockSyntax) If statement Is Nothing Then Return switchStatement End If Return statement.WithCaseBlocks( statement.CaseBlocks.InsertRange(index, switchSections.Cast(Of CaseBlockSyntax))) End Function Friend Overrides Function GetParameterListNode(declaration As SyntaxNode) As SyntaxNode Return declaration.GetParameterList() End Function Private Function WithParameterList(declaration As SyntaxNode, list As ParameterListSyntax) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement Return DirectCast(declaration, DelegateStatementSyntax).WithParameterList(list) Case SyntaxKind.SubBlock, SyntaxKind.FunctionBlock Return DirectCast(declaration, MethodBlockSyntax).WithBlockStatement(DirectCast(declaration, MethodBlockSyntax).BlockStatement.WithParameterList(list)) Case SyntaxKind.ConstructorBlock Return DirectCast(declaration, ConstructorBlockSyntax).WithBlockStatement(DirectCast(declaration, ConstructorBlockSyntax).BlockStatement.WithParameterList(list)) Case SyntaxKind.OperatorBlock Return DirectCast(declaration, OperatorBlockSyntax).WithBlockStatement(DirectCast(declaration, OperatorBlockSyntax).BlockStatement.WithParameterList(list)) Case SyntaxKind.SubStatement, SyntaxKind.FunctionStatement Return DirectCast(declaration, MethodStatementSyntax).WithParameterList(list) Case SyntaxKind.SubNewStatement Return DirectCast(declaration, SubNewStatementSyntax).WithParameterList(list) Case SyntaxKind.OperatorStatement Return DirectCast(declaration, OperatorStatementSyntax).WithParameterList(list) Case SyntaxKind.DeclareSubStatement, SyntaxKind.DeclareFunctionStatement Return DirectCast(declaration, DeclareStatementSyntax).WithParameterList(list) Case SyntaxKind.DelegateSubStatement, SyntaxKind.DelegateFunctionStatement Return DirectCast(declaration, DelegateStatementSyntax).WithParameterList(list) Case SyntaxKind.PropertyBlock If GetDeclarationKind(declaration) = DeclarationKind.Indexer Then Return DirectCast(declaration, PropertyBlockSyntax).WithPropertyStatement(DirectCast(declaration, PropertyBlockSyntax).PropertyStatement.WithParameterList(list)) End If Case SyntaxKind.PropertyStatement If GetDeclarationKind(declaration) = DeclarationKind.Indexer Then Return DirectCast(declaration, PropertyStatementSyntax).WithParameterList(list) End If Case SyntaxKind.EventBlock Return DirectCast(declaration, EventBlockSyntax).WithEventStatement(DirectCast(declaration, EventBlockSyntax).EventStatement.WithParameterList(list)) Case SyntaxKind.EventStatement Return DirectCast(declaration, EventStatementSyntax).WithParameterList(list) Case SyntaxKind.MultiLineFunctionLambdaExpression, SyntaxKind.MultiLineSubLambdaExpression Return DirectCast(declaration, MultiLineLambdaExpressionSyntax).WithSubOrFunctionHeader(DirectCast(declaration, MultiLineLambdaExpressionSyntax).SubOrFunctionHeader.WithParameterList(list)) Case SyntaxKind.SingleLineFunctionLambdaExpression, SyntaxKind.SingleLineSubLambdaExpression Return DirectCast(declaration, SingleLineLambdaExpressionSyntax).WithSubOrFunctionHeader(DirectCast(declaration, SingleLineLambdaExpressionSyntax).SubOrFunctionHeader.WithParameterList(list)) End Select Return declaration End Function Public Overrides Function GetExpression(declaration As SyntaxNode) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.SingleLineFunctionLambdaExpression, SyntaxKind.SingleLineSubLambdaExpression Return AsExpression(DirectCast(declaration, SingleLineLambdaExpressionSyntax).Body) Case Else Dim ev = GetEqualsValue(declaration) If ev IsNot Nothing Then Return ev.Value End If End Select Return Nothing End Function Private Shared Function AsExpression(node As SyntaxNode) As ExpressionSyntax Dim es = TryCast(node, ExpressionStatementSyntax) If es IsNot Nothing Then Return es.Expression End If Return DirectCast(node, ExpressionSyntax) End Function Public Overrides Function WithExpression(declaration As SyntaxNode, expression As SyntaxNode) As SyntaxNode Return Isolate(declaration, Function(d) WithExpressionInternal(d, expression)) End Function Private Function WithExpressionInternal(declaration As SyntaxNode, expression As SyntaxNode) As SyntaxNode Dim expr = DirectCast(expression, ExpressionSyntax) Select Case declaration.Kind Case SyntaxKind.SingleLineFunctionLambdaExpression Dim sll = DirectCast(declaration, SingleLineLambdaExpressionSyntax) If expression IsNot Nothing Then Return sll.WithBody(expr) Else Return SyntaxFactory.MultiLineLambdaExpression(SyntaxKind.MultiLineFunctionLambdaExpression, sll.SubOrFunctionHeader, SyntaxFactory.EndFunctionStatement()) End If Case SyntaxKind.MultiLineFunctionLambdaExpression Dim mll = DirectCast(declaration, MultiLineLambdaExpressionSyntax) If expression IsNot Nothing Then Return SyntaxFactory.SingleLineLambdaExpression(SyntaxKind.SingleLineFunctionLambdaExpression, mll.SubOrFunctionHeader, expr) End If Case SyntaxKind.SingleLineSubLambdaExpression Dim sll = DirectCast(declaration, SingleLineLambdaExpressionSyntax) If expression IsNot Nothing Then Return sll.WithBody(AsStatement(expr)) Else Return SyntaxFactory.MultiLineLambdaExpression(SyntaxKind.MultiLineSubLambdaExpression, sll.SubOrFunctionHeader, SyntaxFactory.EndSubStatement()) End If Case SyntaxKind.MultiLineSubLambdaExpression Dim mll = DirectCast(declaration, MultiLineLambdaExpressionSyntax) If expression IsNot Nothing Then Return SyntaxFactory.SingleLineLambdaExpression(SyntaxKind.SingleLineSubLambdaExpression, mll.SubOrFunctionHeader, AsStatement(expr)) End If Case Else Dim currentEV = GetEqualsValue(declaration) If currentEV IsNot Nothing Then Return WithEqualsValue(declaration, currentEV.WithValue(expr)) Else Return WithEqualsValue(declaration, SyntaxFactory.EqualsValue(expr)) End If End Select Return declaration End Function Private Shared Function GetEqualsValue(declaration As SyntaxNode) As EqualsValueSyntax Select Case declaration.Kind Case SyntaxKind.Parameter Return DirectCast(declaration, ParameterSyntax).Default Case SyntaxKind.LocalDeclarationStatement Dim ld = DirectCast(declaration, LocalDeclarationStatementSyntax) If ld.Declarators.Count = 1 Then Return ld.Declarators(0).Initializer End If Case SyntaxKind.FieldDeclaration Dim fd = DirectCast(declaration, FieldDeclarationSyntax) If fd.Declarators.Count = 1 Then Return fd.Declarators(0).Initializer End If Case SyntaxKind.VariableDeclarator Return DirectCast(declaration, VariableDeclaratorSyntax).Initializer End Select Return Nothing End Function Private Shared Function WithEqualsValue(declaration As SyntaxNode, ev As EqualsValueSyntax) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.Parameter Return DirectCast(declaration, ParameterSyntax).WithDefault(ev) Case SyntaxKind.LocalDeclarationStatement Dim ld = DirectCast(declaration, LocalDeclarationStatementSyntax) If ld.Declarators.Count = 1 Then Return ReplaceWithTrivia(declaration, ld.Declarators(0), ld.Declarators(0).WithInitializer(ev)) End If Case SyntaxKind.FieldDeclaration Dim fd = DirectCast(declaration, FieldDeclarationSyntax) If fd.Declarators.Count = 1 Then Return ReplaceWithTrivia(declaration, fd.Declarators(0), fd.Declarators(0).WithInitializer(ev)) End If End Select Return declaration End Function Public Overrides Function GetNamespaceImports(declaration As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Return Me.Flatten(GetUnflattenedNamespaceImports(declaration)) End Function Private Shared Function GetUnflattenedNamespaceImports(declaration As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Select Case declaration.Kind Case SyntaxKind.CompilationUnit Return DirectCast(declaration, CompilationUnitSyntax).Imports Case Else Return SpecializedCollections.EmptyReadOnlyList(Of SyntaxNode) End Select End Function Public Overrides Function InsertNamespaceImports(declaration As SyntaxNode, index As Integer, [imports] As IEnumerable(Of SyntaxNode)) As SyntaxNode Return Isolate(declaration, Function(d) InsertNamespaceImportsInternal(d, index, [imports])) End Function Private Function InsertNamespaceImportsInternal(declaration As SyntaxNode, index As Integer, [imports] As IEnumerable(Of SyntaxNode)) As SyntaxNode Dim newImports = AsImports([imports]) Dim existingImports = Me.GetNamespaceImports(declaration) If index >= 0 AndAlso index < existingImports.Count Then Return Me.InsertNodesBefore(declaration, existingImports(index), newImports) ElseIf existingImports.Count > 0 Then Return Me.InsertNodesAfter(declaration, existingImports(existingImports.Count - 1), newImports) Else Select Case declaration.Kind Case SyntaxKind.CompilationUnit Dim cu = DirectCast(declaration, CompilationUnitSyntax) Return cu.WithImports(cu.Imports.AddRange(newImports)) Case Else Return declaration End Select End If End Function Public Overrides Function GetMembers(declaration As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Return Flatten(GetUnflattenedMembers(declaration)) End Function Private Shared Function GetUnflattenedMembers(declaration As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Select Case declaration.Kind Case SyntaxKind.CompilationUnit Return DirectCast(declaration, CompilationUnitSyntax).Members Case SyntaxKind.NamespaceBlock Return DirectCast(declaration, NamespaceBlockSyntax).Members Case SyntaxKind.ClassBlock Return DirectCast(declaration, ClassBlockSyntax).Members Case SyntaxKind.StructureBlock Return DirectCast(declaration, StructureBlockSyntax).Members Case SyntaxKind.InterfaceBlock Return DirectCast(declaration, InterfaceBlockSyntax).Members Case SyntaxKind.EnumBlock Return DirectCast(declaration, EnumBlockSyntax).Members Case Else Return SpecializedCollections.EmptyReadOnlyList(Of SyntaxNode)() End Select End Function Private Function AsMembersOf(declaration As SyntaxNode, members As IEnumerable(Of SyntaxNode)) As IEnumerable(Of StatementSyntax) Select Case declaration.Kind Case SyntaxKind.CompilationUnit Return AsNamespaceMembers(members) Case SyntaxKind.NamespaceBlock Return AsNamespaceMembers(members) Case SyntaxKind.ClassBlock Return AsClassMembers(members) Case SyntaxKind.StructureBlock Return AsClassMembers(members) Case SyntaxKind.InterfaceBlock Return AsInterfaceMembers(members) Case SyntaxKind.EnumBlock Return AsEnumMembers(members) Case Else Return SpecializedCollections.EmptyEnumerable(Of StatementSyntax) End Select End Function Public Overrides Function InsertMembers(declaration As SyntaxNode, index As Integer, members As IEnumerable(Of SyntaxNode)) As SyntaxNode Return Isolate(declaration, Function(d) InsertMembersInternal(d, index, members)) End Function Private Function InsertMembersInternal(declaration As SyntaxNode, index As Integer, members As IEnumerable(Of SyntaxNode)) As SyntaxNode Dim newMembers = Me.AsMembersOf(declaration, members) Dim existingMembers = Me.GetMembers(declaration) If index >= 0 AndAlso index < existingMembers.Count Then Return Me.InsertNodesBefore(declaration, existingMembers(index), members) ElseIf existingMembers.Count > 0 Then Return Me.InsertNodesAfter(declaration, existingMembers(existingMembers.Count - 1), members) End If Select Case declaration.Kind Case SyntaxKind.CompilationUnit Dim cu = DirectCast(declaration, CompilationUnitSyntax) Return cu.WithMembers(cu.Members.AddRange(newMembers)) Case SyntaxKind.NamespaceBlock Dim ns = DirectCast(declaration, NamespaceBlockSyntax) Return ns.WithMembers(ns.Members.AddRange(newMembers)) Case SyntaxKind.ClassBlock Dim cb = DirectCast(declaration, ClassBlockSyntax) Return cb.WithMembers(cb.Members.AddRange(newMembers)) Case SyntaxKind.StructureBlock Dim sb = DirectCast(declaration, StructureBlockSyntax) Return sb.WithMembers(sb.Members.AddRange(newMembers)) Case SyntaxKind.InterfaceBlock Dim ib = DirectCast(declaration, InterfaceBlockSyntax) Return ib.WithMembers(ib.Members.AddRange(newMembers)) Case SyntaxKind.EnumBlock Dim eb = DirectCast(declaration, EnumBlockSyntax) Return eb.WithMembers(eb.Members.AddRange(newMembers)) Case Else Return declaration End Select End Function Public Overrides Function GetStatements(declaration As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Select Case declaration.Kind Case SyntaxKind.FunctionBlock, SyntaxKind.SubBlock, SyntaxKind.ConstructorBlock, SyntaxKind.OperatorBlock Return DirectCast(declaration, MethodBlockBaseSyntax).Statements Case SyntaxKind.MultiLineFunctionLambdaExpression, SyntaxKind.MultiLineSubLambdaExpression Return DirectCast(declaration, MultiLineLambdaExpressionSyntax).Statements Case SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock, SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RaiseEventAccessorBlock Return DirectCast(declaration, AccessorBlockSyntax).Statements Case Else Return SpecializedCollections.EmptyReadOnlyList(Of SyntaxNode) End Select End Function Public Overrides Function WithStatements(declaration As SyntaxNode, statements As IEnumerable(Of SyntaxNode)) As SyntaxNode Return Isolate(declaration, Function(d) WithStatementsInternal(d, statements)) End Function Private Function WithStatementsInternal(declaration As SyntaxNode, statements As IEnumerable(Of SyntaxNode)) As SyntaxNode Dim list = GetStatementList(statements) Select Case declaration.Kind Case SyntaxKind.FunctionBlock, SyntaxKind.SubBlock Return DirectCast(declaration, MethodBlockSyntax).WithStatements(list) Case SyntaxKind.ConstructorBlock Return DirectCast(declaration, ConstructorBlockSyntax).WithStatements(list) Case SyntaxKind.OperatorBlock Return DirectCast(declaration, OperatorBlockSyntax).WithStatements(list) Case SyntaxKind.MultiLineFunctionLambdaExpression, SyntaxKind.MultiLineSubLambdaExpression Return DirectCast(declaration, MultiLineLambdaExpressionSyntax).WithStatements(list) Case SyntaxKind.SingleLineFunctionLambdaExpression Dim sll = DirectCast(declaration, SingleLineLambdaExpressionSyntax) Return SyntaxFactory.MultiLineLambdaExpression(SyntaxKind.MultiLineFunctionLambdaExpression, sll.SubOrFunctionHeader, list, SyntaxFactory.EndFunctionStatement()) Case SyntaxKind.SingleLineSubLambdaExpression Dim sll = DirectCast(declaration, SingleLineLambdaExpressionSyntax) Return SyntaxFactory.MultiLineLambdaExpression(SyntaxKind.MultiLineSubLambdaExpression, sll.SubOrFunctionHeader, list, SyntaxFactory.EndSubStatement()) Case SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock, SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RaiseEventAccessorBlock Return DirectCast(declaration, AccessorBlockSyntax).WithStatements(list) Case Else Return declaration End Select End Function Public Overrides Function GetAccessors(declaration As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Select Case declaration.Kind Case SyntaxKind.PropertyBlock Return DirectCast(declaration, PropertyBlockSyntax).Accessors Case SyntaxKind.EventBlock Return DirectCast(declaration, EventBlockSyntax).Accessors Case Else Return SpecializedCollections.EmptyReadOnlyList(Of SyntaxNode)() End Select End Function Public Overrides Function InsertAccessors(declaration As SyntaxNode, index As Integer, accessors As IEnumerable(Of SyntaxNode)) As SyntaxNode Dim currentList = GetAccessorList(declaration) Dim newList = AsAccessorList(accessors, declaration.Kind) If Not currentList.IsEmpty Then Return WithAccessorList(declaration, currentList.InsertRange(index, newList)) Else Return WithAccessorList(declaration, newList) End If End Function Friend Shared Function GetAccessorList(declaration As SyntaxNode) As SyntaxList(Of AccessorBlockSyntax) Select Case declaration.Kind Case SyntaxKind.PropertyBlock Return DirectCast(declaration, PropertyBlockSyntax).Accessors Case SyntaxKind.EventBlock Return DirectCast(declaration, EventBlockSyntax).Accessors Case Else Return Nothing End Select End Function Private Shared Function WithAccessorList(declaration As SyntaxNode, accessorList As SyntaxList(Of AccessorBlockSyntax)) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.PropertyBlock Return DirectCast(declaration, PropertyBlockSyntax).WithAccessors(accessorList) Case SyntaxKind.EventBlock Return DirectCast(declaration, EventBlockSyntax).WithAccessors(accessorList) Case Else Return declaration End Select End Function Private Shared Function AsAccessorList(nodes As IEnumerable(Of SyntaxNode), parentKind As SyntaxKind) As SyntaxList(Of AccessorBlockSyntax) Return SyntaxFactory.List(nodes.Select(Function(n) AsAccessor(n, parentKind)).Where(Function(n) n IsNot Nothing)) End Function Private Shared Function AsAccessor(node As SyntaxNode, parentKind As SyntaxKind) As AccessorBlockSyntax Select Case parentKind Case SyntaxKind.PropertyBlock Select Case node.Kind Case SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock Return DirectCast(node, AccessorBlockSyntax) End Select Case SyntaxKind.EventBlock Select Case node.Kind Case SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RaiseEventAccessorBlock Return DirectCast(node, AccessorBlockSyntax) End Select End Select Return Nothing End Function Private Shared Function CanHaveAccessors(kind As SyntaxKind) As Boolean Select Case kind Case SyntaxKind.PropertyBlock, SyntaxKind.EventBlock Return True Case Else Return False End Select End Function Public Overrides Function GetGetAccessorStatements(declaration As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Return GetAccessorStatements(declaration, SyntaxKind.GetAccessorBlock) End Function Public Overrides Function WithGetAccessorStatements(declaration As SyntaxNode, statements As IEnumerable(Of SyntaxNode)) As SyntaxNode Return WithAccessorStatements(declaration, statements, SyntaxKind.GetAccessorBlock) End Function Public Overrides Function GetSetAccessorStatements(declaration As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Return GetAccessorStatements(declaration, SyntaxKind.SetAccessorBlock) End Function Public Overrides Function WithSetAccessorStatements(declaration As SyntaxNode, statements As IEnumerable(Of SyntaxNode)) As SyntaxNode Return WithAccessorStatements(declaration, statements, SyntaxKind.SetAccessorBlock) End Function Private Function GetAccessorStatements(declaration As SyntaxNode, kind As SyntaxKind) As IReadOnlyList(Of SyntaxNode) Dim accessor = GetAccessorBlock(declaration, kind) If accessor IsNot Nothing Then Return Me.GetStatements(accessor) Else Return SpecializedCollections.EmptyReadOnlyList(Of SyntaxNode)() End If End Function Private Function WithAccessorStatements(declaration As SyntaxNode, statements As IEnumerable(Of SyntaxNode), kind As SyntaxKind) As SyntaxNode Dim accessor = GetAccessorBlock(declaration, kind) If accessor IsNot Nothing Then accessor = DirectCast(Me.WithStatements(accessor, statements), AccessorBlockSyntax) Return Me.WithAccessorBlock(declaration, kind, accessor) ElseIf CanHaveAccessors(declaration.Kind) Then accessor = Me.AccessorBlock(kind, statements, Me.ClearTrivia(Me.GetType(declaration))) Return Me.WithAccessorBlock(declaration, kind, accessor) Else Return declaration End If End Function Private Shared Function GetAccessorBlock(declaration As SyntaxNode, kind As SyntaxKind) As AccessorBlockSyntax Select Case declaration.Kind Case SyntaxKind.PropertyBlock Return DirectCast(declaration, PropertyBlockSyntax).Accessors.FirstOrDefault(Function(a) a.IsKind(kind)) Case SyntaxKind.EventBlock Return DirectCast(declaration, EventBlockSyntax).Accessors.FirstOrDefault(Function(a) a.IsKind(kind)) Case Else Return Nothing End Select End Function Private Function WithAccessorBlock(declaration As SyntaxNode, kind As SyntaxKind, accessor As AccessorBlockSyntax) As SyntaxNode Dim currentAccessor = GetAccessorBlock(declaration, kind) If currentAccessor IsNot Nothing Then Return Me.ReplaceNode(declaration, currentAccessor, accessor) ElseIf accessor IsNot Nothing Then Select Case declaration.Kind Case SyntaxKind.PropertyBlock Dim pb = DirectCast(declaration, PropertyBlockSyntax) Return pb.WithAccessors(pb.Accessors.Add(accessor)) Case SyntaxKind.EventBlock Dim eb = DirectCast(declaration, EventBlockSyntax) Return eb.WithAccessors(eb.Accessors.Add(accessor)) End Select End If Return declaration End Function Public Overrides Function EventDeclaration(name As String, type As SyntaxNode, Optional accessibility As Accessibility = Accessibility.NotApplicable, Optional modifiers As DeclarationModifiers = Nothing) As SyntaxNode Return SyntaxFactory.EventStatement( attributeLists:=Nothing, modifiers:=GetModifierList(accessibility, modifiers And GetAllowedModifiers(SyntaxKind.EventStatement), declaration:=Nothing, DeclarationKind.Event), customKeyword:=Nothing, eventKeyword:=SyntaxFactory.Token(SyntaxKind.EventKeyword), identifier:=name.ToIdentifierToken(), parameterList:=Nothing, asClause:=SyntaxFactory.SimpleAsClause(DirectCast(type, TypeSyntax)), implementsClause:=Nothing) End Function Public Overrides Function CustomEventDeclaration( name As String, type As SyntaxNode, Optional accessibility As Accessibility = Accessibility.NotApplicable, Optional modifiers As DeclarationModifiers = Nothing, Optional parameters As IEnumerable(Of SyntaxNode) = Nothing, Optional addAccessorStatements As IEnumerable(Of SyntaxNode) = Nothing, Optional removeAccessorStatements As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Return CustomEventDeclarationWithRaise(name, type, accessibility, modifiers, parameters, addAccessorStatements, removeAccessorStatements) End Function Public Function CustomEventDeclarationWithRaise( name As String, type As SyntaxNode, Optional accessibility As Accessibility = Accessibility.NotApplicable, Optional modifiers As DeclarationModifiers = Nothing, Optional parameters As IEnumerable(Of SyntaxNode) = Nothing, Optional addAccessorStatements As IEnumerable(Of SyntaxNode) = Nothing, Optional removeAccessorStatements As IEnumerable(Of SyntaxNode) = Nothing, Optional raiseAccessorStatements As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Dim accessors = New List(Of AccessorBlockSyntax)() If modifiers.IsAbstract Then addAccessorStatements = Nothing removeAccessorStatements = Nothing raiseAccessorStatements = Nothing Else If addAccessorStatements Is Nothing Then addAccessorStatements = SpecializedCollections.EmptyEnumerable(Of SyntaxNode)() End If If removeAccessorStatements Is Nothing Then removeAccessorStatements = SpecializedCollections.EmptyEnumerable(Of SyntaxNode)() End If If raiseAccessorStatements Is Nothing Then raiseAccessorStatements = SpecializedCollections.EmptyEnumerable(Of SyntaxNode)() End If End If accessors.Add(CreateAddHandlerAccessorBlock(type, addAccessorStatements)) accessors.Add(CreateRemoveHandlerAccessorBlock(type, removeAccessorStatements)) accessors.Add(CreateRaiseEventAccessorBlock(parameters, raiseAccessorStatements)) Dim evStatement = SyntaxFactory.EventStatement( attributeLists:=Nothing, modifiers:=GetModifierList(accessibility, modifiers And GetAllowedModifiers(SyntaxKind.EventStatement), declaration:=Nothing, DeclarationKind.Event), customKeyword:=SyntaxFactory.Token(SyntaxKind.CustomKeyword), eventKeyword:=SyntaxFactory.Token(SyntaxKind.EventKeyword), identifier:=name.ToIdentifierToken(), parameterList:=Nothing, asClause:=SyntaxFactory.SimpleAsClause(DirectCast(type, TypeSyntax)), implementsClause:=Nothing) Return SyntaxFactory.EventBlock( eventStatement:=evStatement, accessors:=SyntaxFactory.List(accessors), endEventStatement:=SyntaxFactory.EndEventStatement()) End Function Public Overrides Function GetAttributeArguments(attributeDeclaration As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Dim list = GetArgumentList(attributeDeclaration) If list IsNot Nothing Then Return list.Arguments Else Return SpecializedCollections.EmptyReadOnlyList(Of SyntaxNode)() End If End Function Public Overrides Function InsertAttributeArguments(attributeDeclaration As SyntaxNode, index As Integer, attributeArguments As IEnumerable(Of SyntaxNode)) As SyntaxNode Return Isolate(attributeDeclaration, Function(d) InsertAttributeArgumentsInternal(d, index, attributeArguments)) End Function Private Function InsertAttributeArgumentsInternal(attributeDeclaration As SyntaxNode, index As Integer, attributeArguments As IEnumerable(Of SyntaxNode)) As SyntaxNode Dim list = GetArgumentList(attributeDeclaration) Dim newArguments = AsArgumentList(attributeArguments) If list Is Nothing Then list = newArguments Else list = list.WithArguments(list.Arguments.InsertRange(index, newArguments.Arguments)) End If Return WithArgumentList(attributeDeclaration, list) End Function Private Shared Function GetArgumentList(declaration As SyntaxNode) As ArgumentListSyntax Select Case declaration.Kind Case SyntaxKind.AttributeList Dim al = DirectCast(declaration, AttributeListSyntax) If al.Attributes.Count = 1 Then Return al.Attributes(0).ArgumentList End If Case SyntaxKind.Attribute Return DirectCast(declaration, AttributeSyntax).ArgumentList End Select Return Nothing End Function Private Shared Function WithArgumentList(declaration As SyntaxNode, argumentList As ArgumentListSyntax) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.AttributeList Dim al = DirectCast(declaration, AttributeListSyntax) If al.Attributes.Count = 1 Then Return ReplaceWithTrivia(declaration, al.Attributes(0), al.Attributes(0).WithArgumentList(argumentList)) End If Case SyntaxKind.Attribute Return DirectCast(declaration, AttributeSyntax).WithArgumentList(argumentList) End Select Return declaration End Function Public Overrides Function GetBaseAndInterfaceTypes(declaration As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Return GetInherits(declaration).SelectMany(Function(ih) ih.Types).Concat(GetImplements(declaration).SelectMany(Function(imp) imp.Types)).ToBoxedImmutableArray() End Function Public Overrides Function AddBaseType(declaration As SyntaxNode, baseType As SyntaxNode) As SyntaxNode If declaration.IsKind(SyntaxKind.ClassBlock) Then Dim existingBaseType = GetInherits(declaration).SelectMany(Function(inh) inh.Types).FirstOrDefault() If existingBaseType IsNot Nothing Then Return declaration.ReplaceNode(existingBaseType, baseType.WithTriviaFrom(existingBaseType)) Else Return WithInherits(declaration, SyntaxFactory.SingletonList(SyntaxFactory.InheritsStatement(DirectCast(baseType, TypeSyntax)))) End If Else Return declaration End If End Function Public Overrides Function AddInterfaceType(declaration As SyntaxNode, interfaceType As SyntaxNode) As SyntaxNode If declaration.IsKind(SyntaxKind.InterfaceBlock) Then Dim inh = GetInherits(declaration) Dim last = inh.SelectMany(Function(s) s.Types).LastOrDefault() If inh.Count = 1 AndAlso last IsNot Nothing Then Dim inh0 = inh(0) Dim newInh0 = PreserveTrivia(inh0.TrackNodes(last), Function(_inh0) InsertNodesAfter(_inh0, _inh0.GetCurrentNode(last), {interfaceType})) Return ReplaceNode(declaration, inh0, newInh0) Else Return WithInherits(declaration, inh.Add(SyntaxFactory.InheritsStatement(DirectCast(interfaceType, TypeSyntax)))) End If Else Dim imp = GetImplements(declaration) Dim last = imp.SelectMany(Function(s) s.Types).LastOrDefault() If imp.Count = 1 AndAlso last IsNot Nothing Then Dim imp0 = imp(0) Dim newImp0 = PreserveTrivia(imp0.TrackNodes(last), Function(_imp0) InsertNodesAfter(_imp0, _imp0.GetCurrentNode(last), {interfaceType})) Return ReplaceNode(declaration, imp0, newImp0) Else Return WithImplements(declaration, imp.Add(SyntaxFactory.ImplementsStatement(DirectCast(interfaceType, TypeSyntax)))) End If End If End Function Private Shared Function GetInherits(declaration As SyntaxNode) As SyntaxList(Of InheritsStatementSyntax) Select Case declaration.Kind Case SyntaxKind.ClassBlock Return DirectCast(declaration, ClassBlockSyntax).Inherits Case SyntaxKind.InterfaceBlock Return DirectCast(declaration, InterfaceBlockSyntax).Inherits Case Else Return Nothing End Select End Function Private Shared Function WithInherits(declaration As SyntaxNode, list As SyntaxList(Of InheritsStatementSyntax)) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.ClassBlock Return DirectCast(declaration, ClassBlockSyntax).WithInherits(list) Case SyntaxKind.InterfaceBlock Return DirectCast(declaration, InterfaceBlockSyntax).WithInherits(list) Case Else Return declaration End Select End Function Private Shared Function GetImplements(declaration As SyntaxNode) As SyntaxList(Of ImplementsStatementSyntax) Select Case declaration.Kind Case SyntaxKind.ClassBlock Return DirectCast(declaration, ClassBlockSyntax).Implements Case SyntaxKind.StructureBlock Return DirectCast(declaration, StructureBlockSyntax).Implements Case Else Return Nothing End Select End Function Private Shared Function WithImplements(declaration As SyntaxNode, list As SyntaxList(Of ImplementsStatementSyntax)) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.ClassBlock Return DirectCast(declaration, ClassBlockSyntax).WithImplements(list) Case SyntaxKind.StructureBlock Return DirectCast(declaration, StructureBlockSyntax).WithImplements(list) Case Else Return declaration End Select End Function #End Region #Region "Remove, Replace, Insert" Public Overrides Function ReplaceNode(root As SyntaxNode, declaration As SyntaxNode, newDeclaration As SyntaxNode) As SyntaxNode If newDeclaration Is Nothing Then Return Me.RemoveNode(root, declaration) End If If root.Span.Contains(declaration.Span) Then Dim newFullDecl = Me.AsIsolatedDeclaration(newDeclaration) Dim fullDecl = Me.GetFullDeclaration(declaration) ' special handling for replacing at location of a sub-declaration If fullDecl IsNot declaration AndAlso fullDecl.IsKind(newFullDecl.Kind) Then ' try to replace inline if possible If GetDeclarationCount(newFullDecl) = 1 Then Dim newSubDecl = GetSubDeclarations(newFullDecl)(0) If AreInlineReplaceableSubDeclarations(declaration, newSubDecl) Then Return MyBase.ReplaceNode(root, declaration, newSubDecl) End If End If ' otherwise replace by splitting full-declaration into two parts and inserting newDeclaration between them Dim index = MyBase.IndexOf(GetSubDeclarations(fullDecl), declaration) Return Me.ReplaceSubDeclaration(root, fullDecl, index, newFullDecl) End If ' attempt normal replace Return MyBase.ReplaceNode(root, declaration, newFullDecl) Else Return MyBase.ReplaceNode(root, declaration, newDeclaration) End If End Function ' return true if one sub-declaration can be replaced in-line with another sub-declaration Private Function AreInlineReplaceableSubDeclarations(decl1 As SyntaxNode, decl2 As SyntaxNode) As Boolean Dim kind = decl1.Kind If Not decl2.IsKind(kind) Then Return False End If Select Case kind Case SyntaxKind.ModifiedIdentifier, SyntaxKind.Attribute, SyntaxKind.SimpleImportsClause, SyntaxKind.XmlNamespaceImportsClause Return AreSimilarExceptForSubDeclarations(decl1.Parent, decl2.Parent) End Select Return False End Function Private Function AreSimilarExceptForSubDeclarations(decl1 As SyntaxNode, decl2 As SyntaxNode) As Boolean If decl1 Is Nothing OrElse decl2 Is Nothing Then Return False End If Dim kind = decl1.Kind If Not decl2.IsKind(kind) Then Return False End If Select Case kind Case SyntaxKind.FieldDeclaration Dim fd1 = DirectCast(decl1, FieldDeclarationSyntax) Dim fd2 = DirectCast(decl2, FieldDeclarationSyntax) Return SyntaxFactory.AreEquivalent(fd1.AttributeLists, fd2.AttributeLists) AndAlso SyntaxFactory.AreEquivalent(fd1.Modifiers, fd2.Modifiers) Case SyntaxKind.LocalDeclarationStatement Dim ld1 = DirectCast(decl1, LocalDeclarationStatementSyntax) Dim ld2 = DirectCast(decl2, LocalDeclarationStatementSyntax) Return SyntaxFactory.AreEquivalent(ld1.Modifiers, ld2.Modifiers) Case SyntaxKind.VariableDeclarator Dim vd1 = DirectCast(decl1, VariableDeclaratorSyntax) Dim vd2 = DirectCast(decl2, VariableDeclaratorSyntax) Return SyntaxFactory.AreEquivalent(vd1.AsClause, vd2.AsClause) AndAlso SyntaxFactory.AreEquivalent(vd2.Initializer, vd1.Initializer) AndAlso AreSimilarExceptForSubDeclarations(decl1.Parent, decl2.Parent) Case SyntaxKind.AttributeList, SyntaxKind.ImportsStatement Return True End Select Return False End Function Public Overrides Function InsertNodesBefore(root As SyntaxNode, declaration As SyntaxNode, newDeclarations As IEnumerable(Of SyntaxNode)) As SyntaxNode If root.Span.Contains(declaration.Span) Then Return Isolate(root.TrackNodes(declaration), Function(r) InsertDeclarationsBeforeInternal(r, r.GetCurrentNode(declaration), newDeclarations)) Else Return MyBase.InsertNodesBefore(root, declaration, newDeclarations) End If End Function Private Function InsertDeclarationsBeforeInternal(root As SyntaxNode, declaration As SyntaxNode, newDeclarations As IEnumerable(Of SyntaxNode)) As SyntaxNode Dim fullDecl = Me.GetFullDeclaration(declaration) If fullDecl Is declaration OrElse GetDeclarationCount(fullDecl) = 1 Then Return MyBase.InsertNodesBefore(root, declaration, newDeclarations) End If Dim subDecls = GetSubDeclarations(fullDecl) Dim count = subDecls.Count Dim index = MyBase.IndexOf(subDecls, declaration) ' insert New declaration between full declaration split into two If index > 0 Then Return ReplaceRange(root, fullDecl, SplitAndInsert(fullDecl, subDecls, index, newDeclarations)) End If Return MyBase.InsertNodesBefore(root, fullDecl, newDeclarations) End Function Public Overrides Function InsertNodesAfter(root As SyntaxNode, declaration As SyntaxNode, newDeclarations As IEnumerable(Of SyntaxNode)) As SyntaxNode If root.Span.Contains(declaration.Span) Then Return Isolate(root.TrackNodes(declaration), Function(r) InsertNodesAfterInternal(r, r.GetCurrentNode(declaration), newDeclarations)) Else Return MyBase.InsertNodesAfter(root, declaration, newDeclarations) End If End Function Private Function InsertNodesAfterInternal(root As SyntaxNode, declaration As SyntaxNode, newDeclarations As IEnumerable(Of SyntaxNode)) As SyntaxNode Dim fullDecl = Me.GetFullDeclaration(declaration) If fullDecl Is declaration OrElse GetDeclarationCount(fullDecl) = 1 Then Return MyBase.InsertNodesAfter(root, declaration, newDeclarations) End If Dim subDecls = GetSubDeclarations(fullDecl) Dim count = subDecls.Count Dim index = MyBase.IndexOf(subDecls, declaration) ' insert New declaration between full declaration split into two If index >= 0 AndAlso index < count - 1 Then Return ReplaceRange(root, fullDecl, SplitAndInsert(fullDecl, subDecls, index + 1, newDeclarations)) End If Return MyBase.InsertNodesAfter(root, fullDecl, newDeclarations) End Function Private Function SplitAndInsert(multiPartDeclaration As SyntaxNode, subDeclarations As IReadOnlyList(Of SyntaxNode), index As Integer, newDeclarations As IEnumerable(Of SyntaxNode)) As IEnumerable(Of SyntaxNode) Dim count = subDeclarations.Count Dim newNodes = New List(Of SyntaxNode)() newNodes.Add(Me.WithSubDeclarationsRemoved(multiPartDeclaration, index, count - index).WithTrailingTrivia(SyntaxFactory.ElasticSpace)) newNodes.AddRange(newDeclarations) newNodes.Add(Me.WithSubDeclarationsRemoved(multiPartDeclaration, 0, index).WithLeadingTrivia(SyntaxFactory.ElasticSpace)) Return newNodes End Function ' replaces sub-declaration by splitting multi-part declaration first Private Function ReplaceSubDeclaration(root As SyntaxNode, declaration As SyntaxNode, index As Integer, newDeclaration As SyntaxNode) As SyntaxNode Dim newNodes = New List(Of SyntaxNode)() Dim count = GetDeclarationCount(declaration) If index >= 0 AndAlso index < count Then If (index > 0) Then ' make a single declaration with only the sub-declarations before the sub-declaration being replaced newNodes.Add(Me.WithSubDeclarationsRemoved(declaration, index, count - index).WithTrailingTrivia(SyntaxFactory.ElasticSpace)) End If newNodes.Add(newDeclaration) If (index < count - 1) Then ' make a single declaration with only the sub-declarations after the sub-declaration being replaced newNodes.Add(Me.WithSubDeclarationsRemoved(declaration, 0, index + 1).WithLeadingTrivia(SyntaxFactory.ElasticSpace)) End If ' replace declaration with multiple declarations Return ReplaceRange(root, declaration, newNodes) Else Return root End If End Function Private Function WithSubDeclarationsRemoved(declaration As SyntaxNode, index As Integer, count As Integer) As SyntaxNode Return Me.RemoveNodes(declaration, GetSubDeclarations(declaration).Skip(index).Take(count)) End Function Private Shared Function GetSubDeclarations(declaration As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Select Case declaration.Kind Case SyntaxKind.FieldDeclaration Return DirectCast(declaration, FieldDeclarationSyntax).Declarators.SelectMany(Function(d) d.Names).ToBoxedImmutableArray() Case SyntaxKind.LocalDeclarationStatement Return DirectCast(declaration, LocalDeclarationStatementSyntax).Declarators.SelectMany(Function(d) d.Names).ToBoxedImmutableArray() Case SyntaxKind.AttributeList Return DirectCast(declaration, AttributeListSyntax).Attributes Case SyntaxKind.ImportsStatement Return DirectCast(declaration, ImportsStatementSyntax).ImportsClauses Case Else Return SpecializedCollections.EmptyReadOnlyList(Of SyntaxNode) End Select End Function Private Function Flatten(members As IReadOnlyList(Of SyntaxNode)) As IReadOnlyList(Of SyntaxNode) Dim builder = ArrayBuilder(Of SyntaxNode).GetInstance() Flatten(builder, members) Return builder.ToImmutableAndFree() End Function Private Sub Flatten(builder As ArrayBuilder(Of SyntaxNode), members As IReadOnlyList(Of SyntaxNode)) For Each member In members If GetDeclarationCount(member) > 1 Then Select Case member.Kind Case SyntaxKind.FieldDeclaration Flatten(builder, DirectCast(member, FieldDeclarationSyntax).Declarators) Case SyntaxKind.LocalDeclarationStatement Flatten(builder, DirectCast(member, LocalDeclarationStatementSyntax).Declarators) Case SyntaxKind.VariableDeclarator Flatten(builder, DirectCast(member, VariableDeclaratorSyntax).Names) Case SyntaxKind.AttributesStatement Flatten(builder, DirectCast(member, AttributesStatementSyntax).AttributeLists) Case SyntaxKind.AttributeList Flatten(builder, DirectCast(member, AttributeListSyntax).Attributes) Case SyntaxKind.ImportsStatement Flatten(builder, DirectCast(member, ImportsStatementSyntax).ImportsClauses) Case Else builder.Add(member) End Select Else builder.Add(member) End If Next End Sub Public Overrides Function RemoveNode(root As SyntaxNode, declaration As SyntaxNode) As SyntaxNode Return RemoveNode(root, declaration, DefaultRemoveOptions) End Function Public Overrides Function RemoveNode(root As SyntaxNode, declaration As SyntaxNode, options As SyntaxRemoveOptions) As SyntaxNode If root.Span.Contains(declaration.Span) Then Return Isolate(root.TrackNodes(declaration), Function(r) Me.RemoveNodeInternal(r, r.GetCurrentNode(declaration), options)) Else Return MyBase.RemoveNode(root, declaration, options) End If End Function Private Function RemoveNodeInternal(root As SyntaxNode, node As SyntaxNode, options As SyntaxRemoveOptions) As SyntaxNode ' special case handling for nodes that remove their parents too Select Case node.Kind Case SyntaxKind.ModifiedIdentifier Dim vd = TryCast(node.Parent, VariableDeclaratorSyntax) If vd IsNot Nothing AndAlso vd.Names.Count = 1 Then ' remove entire variable declarator if only name Return RemoveNodeInternal(root, vd, options) End If Case SyntaxKind.VariableDeclarator If IsChildOfVariableDeclaration(node) AndAlso GetDeclarationCount(node.Parent) = 1 Then ' remove entire parent declaration if this is the only declarator Return RemoveNodeInternal(root, node.Parent, options) End If Case SyntaxKind.AttributeList Dim attrList = DirectCast(node, AttributeListSyntax) Dim attrStmt = TryCast(attrList.Parent, AttributesStatementSyntax) If attrStmt IsNot Nothing AndAlso attrStmt.AttributeLists.Count = 1 Then ' remove entire attribute statement if this is the only attribute list Return RemoveNodeInternal(root, attrStmt, options) End If Case SyntaxKind.Attribute Dim attrList = TryCast(node.Parent, AttributeListSyntax) If attrList IsNot Nothing AndAlso attrList.Attributes.Count = 1 Then ' remove entire attribute list if this is the only attribute Return RemoveNodeInternal(root, attrList, options) End If Case SyntaxKind.SimpleArgument If IsChildOf(node, SyntaxKind.ArgumentList) AndAlso IsChildOf(node.Parent, SyntaxKind.Attribute) Then Dim argList = DirectCast(node.Parent, ArgumentListSyntax) If argList.Arguments.Count = 1 Then ' remove attribute's arg list if this is the only argument Return RemoveNodeInternal(root, argList, options) End If End If Case SyntaxKind.SimpleImportsClause, SyntaxKind.XmlNamespaceImportsClause Dim imps = DirectCast(node.Parent, ImportsStatementSyntax) If imps.ImportsClauses.Count = 1 Then ' remove entire imports statement if this is the only clause Return RemoveNodeInternal(root, node.Parent, options) End If Case Else Dim parent = node.Parent If parent IsNot Nothing Then Select Case parent.Kind Case SyntaxKind.ImplementsStatement Dim imp = DirectCast(parent, ImplementsStatementSyntax) If imp.Types.Count = 1 Then Return RemoveNodeInternal(root, parent, options) End If Case SyntaxKind.InheritsStatement Dim inh = DirectCast(parent, InheritsStatementSyntax) If inh.Types.Count = 1 Then Return RemoveNodeInternal(root, parent, options) End If End Select End If End Select ' do it the normal way Return root.RemoveNode(node, options) End Function Friend Overrides Function IdentifierName(identifier As SyntaxToken) As SyntaxNode Return SyntaxFactory.IdentifierName(identifier) End Function Friend Overrides Function NamedAnonymousObjectMemberDeclarator(identifier As SyntaxNode, expression As SyntaxNode) As SyntaxNode Return SyntaxFactory.NamedFieldInitializer( DirectCast(identifier, IdentifierNameSyntax), DirectCast(expression, ExpressionSyntax)) End Function Friend Overrides Function IsRegularOrDocComment(trivia As SyntaxTrivia) As Boolean Return trivia.IsRegularOrDocComment() End Function Friend Overrides Function RemoveAllComments(node As SyntaxNode) As SyntaxNode Return RemoveLeadingAndTrailingComments(node) End Function Friend Overrides Function RemoveCommentLines(syntaxList As SyntaxTriviaList) As SyntaxTriviaList Return syntaxList.Where(Function(s) Not IsRegularOrDocComment(s)).ToSyntaxTriviaList() End Function #End Region End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Composition Imports System.Diagnostics.CodeAnalysis Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Editing Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Simplification Imports Microsoft.CodeAnalysis.VisualBasic.LanguageServices Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGeneration <ExportLanguageService(GetType(SyntaxGenerator), LanguageNames.VisualBasic), [Shared]> Friend Class VisualBasicSyntaxGenerator Inherits SyntaxGenerator Public Shared ReadOnly Instance As SyntaxGenerator = New VisualBasicSyntaxGenerator() <ImportingConstructor> <SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Incorrectly used in production code: https://github.com/dotnet/roslyn/issues/42839")> Public Sub New() End Sub Friend Overrides ReadOnly Property ElasticCarriageReturnLineFeed As SyntaxTrivia = SyntaxFactory.ElasticCarriageReturnLineFeed Friend Overrides ReadOnly Property CarriageReturnLineFeed As SyntaxTrivia = SyntaxFactory.CarriageReturnLineFeed Friend Overrides ReadOnly Property RequiresExplicitImplementationForInterfaceMembers As Boolean = True Friend Overrides ReadOnly Property SyntaxGeneratorInternal As SyntaxGeneratorInternal = VisualBasicSyntaxGeneratorInternal.Instance Friend Overrides Function Whitespace(text As String) As SyntaxTrivia Return SyntaxFactory.Whitespace(text) End Function Friend Overrides Function SingleLineComment(text As String) As SyntaxTrivia Return SyntaxFactory.CommentTrivia("'" + text) End Function Friend Overrides Function SeparatedList(Of TElement As SyntaxNode)(list As SyntaxNodeOrTokenList) As SeparatedSyntaxList(Of TElement) Return SyntaxFactory.SeparatedList(Of TElement)(list) End Function Friend Overrides Function CreateInterpolatedStringStartToken(isVerbatim As Boolean) As SyntaxToken Return SyntaxFactory.Token(SyntaxKind.DollarSignDoubleQuoteToken) End Function Friend Overrides Function CreateInterpolatedStringEndToken() As SyntaxToken Return SyntaxFactory.Token(SyntaxKind.DoubleQuoteToken) End Function Friend Overrides Function SeparatedList(Of TElement As SyntaxNode)(nodes As IEnumerable(Of TElement), separators As IEnumerable(Of SyntaxToken)) As SeparatedSyntaxList(Of TElement) Return SyntaxFactory.SeparatedList(nodes, separators) End Function Friend Overrides Function Trivia(node As SyntaxNode) As SyntaxTrivia Dim structuredTrivia = TryCast(node, StructuredTriviaSyntax) If structuredTrivia IsNot Nothing Then Return SyntaxFactory.Trivia(structuredTrivia) End If Throw ExceptionUtilities.UnexpectedValue(node.Kind()) End Function Friend Overrides Function DocumentationCommentTrivia(nodes As IEnumerable(Of SyntaxNode), trailingTrivia As SyntaxTriviaList, lastWhitespaceTrivia As SyntaxTrivia, endOfLineString As String) As SyntaxNode Dim node = SyntaxFactory.DocumentationCommentTrivia(SyntaxFactory.List(nodes)) node = node.WithLeadingTrivia(SyntaxFactory.DocumentationCommentExteriorTrivia("''' ")). WithTrailingTrivia(node.GetTrailingTrivia()) If lastWhitespaceTrivia = Nothing Then Return node.WithTrailingTrivia(SyntaxFactory.EndOfLine(endOfLineString)) End If Return node.WithTrailingTrivia(SyntaxFactory.EndOfLine(endOfLineString), lastWhitespaceTrivia) End Function Friend Overrides Function DocumentationCommentTriviaWithUpdatedContent(trivia As SyntaxTrivia, content As IEnumerable(Of SyntaxNode)) As SyntaxNode Dim documentationCommentTrivia = TryCast(trivia.GetStructure(), DocumentationCommentTriviaSyntax) If documentationCommentTrivia IsNot Nothing Then Return SyntaxFactory.DocumentationCommentTrivia(SyntaxFactory.List(content)) End If Return Nothing End Function #Region "Expressions and Statements" Public Overrides Function AddEventHandler([event] As SyntaxNode, handler As SyntaxNode) As SyntaxNode Return SyntaxFactory.AddHandlerStatement(CType([event], ExpressionSyntax), CType(handler, ExpressionSyntax)) End Function Public Overrides Function RemoveEventHandler([event] As SyntaxNode, handler As SyntaxNode) As SyntaxNode Return SyntaxFactory.RemoveHandlerStatement(CType([event], ExpressionSyntax), CType(handler, ExpressionSyntax)) End Function Public Overrides Function AwaitExpression(expression As SyntaxNode) As SyntaxNode Return SyntaxFactory.AwaitExpression(DirectCast(expression, ExpressionSyntax)) End Function Public Overrides Function NameOfExpression(expression As SyntaxNode) As SyntaxNode Return SyntaxFactory.NameOfExpression(DirectCast(expression, ExpressionSyntax)) End Function Public Overrides Function TupleExpression(arguments As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.TupleExpression(SyntaxFactory.SeparatedList(arguments.Select(AddressOf AsSimpleArgument))) End Function Private Shared Function Parenthesize(expression As SyntaxNode, Optional addSimplifierAnnotation As Boolean = True) As ParenthesizedExpressionSyntax Return VisualBasicSyntaxGeneratorInternal.Parenthesize(expression, addSimplifierAnnotation) End Function Public Overrides Function AddExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.AddExpression(Parenthesize(left), Parenthesize(right)) End Function Public Overloads Overrides Function Argument(name As String, refKind As RefKind, expression As SyntaxNode) As SyntaxNode If name Is Nothing Then Return SyntaxFactory.SimpleArgument(DirectCast(expression, ExpressionSyntax)) Else Return SyntaxFactory.SimpleArgument(SyntaxFactory.NameColonEquals(name.ToIdentifierName()), DirectCast(expression, ExpressionSyntax)) End If End Function Public Overrides Function TryCastExpression(expression As SyntaxNode, type As SyntaxNode) As SyntaxNode Return SyntaxFactory.TryCastExpression(DirectCast(expression, ExpressionSyntax), DirectCast(type, TypeSyntax)) End Function Public Overrides Function AssignmentStatement(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.SimpleAssignmentStatement( DirectCast(left, ExpressionSyntax), SyntaxFactory.Token(SyntaxKind.EqualsToken), DirectCast(right, ExpressionSyntax)) End Function Public Overrides Function BaseExpression() As SyntaxNode Return SyntaxFactory.MyBaseExpression() End Function Public Overrides Function BitwiseAndExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.AndExpression(Parenthesize(left), Parenthesize(right)) End Function Public Overrides Function BitwiseOrExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.OrExpression(Parenthesize(left), Parenthesize(right)) End Function Public Overrides Function CastExpression(type As SyntaxNode, expression As SyntaxNode) As SyntaxNode Return SyntaxFactory.DirectCastExpression(DirectCast(expression, ExpressionSyntax), DirectCast(type, TypeSyntax)).WithAdditionalAnnotations(Simplifier.Annotation) End Function Public Overrides Function ConvertExpression(type As SyntaxNode, expression As SyntaxNode) As SyntaxNode Return SyntaxFactory.CTypeExpression(DirectCast(expression, ExpressionSyntax), DirectCast(type, TypeSyntax)).WithAdditionalAnnotations(Simplifier.Annotation) End Function Public Overrides Function ConditionalExpression(condition As SyntaxNode, whenTrue As SyntaxNode, whenFalse As SyntaxNode) As SyntaxNode Return SyntaxFactory.TernaryConditionalExpression( DirectCast(condition, ExpressionSyntax), DirectCast(whenTrue, ExpressionSyntax), DirectCast(whenFalse, ExpressionSyntax)) End Function Public Overrides Function LiteralExpression(value As Object) As SyntaxNode Return ExpressionGenerator.GenerateNonEnumValueExpression(Nothing, value, canUseFieldReference:=True) End Function Public Overrides Function TypedConstantExpression(value As TypedConstant) As SyntaxNode Return ExpressionGenerator.GenerateExpression(value) End Function Friend Overrides Function NumericLiteralToken(text As String, value As ULong) As SyntaxToken Return SyntaxFactory.Literal(text, value) End Function Public Overrides Function DefaultExpression(type As ITypeSymbol) As SyntaxNode Return SyntaxFactory.NothingLiteralExpression(SyntaxFactory.Token(SyntaxKind.NothingKeyword)) End Function Public Overrides Function DefaultExpression(type As SyntaxNode) As SyntaxNode Return SyntaxFactory.NothingLiteralExpression(SyntaxFactory.Token(SyntaxKind.NothingKeyword)) End Function Public Overloads Overrides Function ElementAccessExpression(expression As SyntaxNode, arguments As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.InvocationExpression(ParenthesizeLeft(expression), CreateArgumentList(arguments)) End Function Public Overrides Function ExpressionStatement(expression As SyntaxNode) As SyntaxNode If TypeOf expression Is StatementSyntax Then Return expression End If Return SyntaxFactory.ExpressionStatement(DirectCast(expression, ExpressionSyntax)) End Function Public Overloads Overrides Function GenericName(identifier As String, typeArguments As IEnumerable(Of SyntaxNode)) As SyntaxNode Return GenericName(identifier.ToIdentifierToken(), typeArguments) End Function Friend Overrides Function GenericName(identifier As SyntaxToken, typeArguments As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.GenericName( identifier, SyntaxFactory.TypeArgumentList( SyntaxFactory.SeparatedList(typeArguments.Cast(Of TypeSyntax)()))).WithAdditionalAnnotations(Simplifier.Annotation) End Function Public Overrides Function IdentifierName(identifier As String) As SyntaxNode Return identifier.ToIdentifierName() End Function Public Overrides Function IfStatement(condition As SyntaxNode, trueStatements As IEnumerable(Of SyntaxNode), Optional falseStatements As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Dim ifStmt = SyntaxFactory.IfStatement(SyntaxFactory.Token(SyntaxKind.IfKeyword), DirectCast(condition, ExpressionSyntax), SyntaxFactory.Token(SyntaxKind.ThenKeyword)) If falseStatements Is Nothing Then Return SyntaxFactory.MultiLineIfBlock( ifStmt, GetStatementList(trueStatements), Nothing, Nothing ) End If ' convert nested if-blocks into else-if parts Dim statements = falseStatements.ToList() If statements.Count = 1 AndAlso TypeOf statements(0) Is MultiLineIfBlockSyntax Then Dim mifBlock = DirectCast(statements(0), MultiLineIfBlockSyntax) ' insert block's if-part onto head of elseIf-parts Dim elseIfBlocks = mifBlock.ElseIfBlocks.Insert(0, SyntaxFactory.ElseIfBlock( SyntaxFactory.ElseIfStatement(SyntaxFactory.Token(SyntaxKind.ElseIfKeyword), mifBlock.IfStatement.Condition, SyntaxFactory.Token(SyntaxKind.ThenKeyword)), mifBlock.Statements) ) Return SyntaxFactory.MultiLineIfBlock( ifStmt, GetStatementList(trueStatements), elseIfBlocks, mifBlock.ElseBlock ) End If Return SyntaxFactory.MultiLineIfBlock( ifStmt, GetStatementList(trueStatements), Nothing, SyntaxFactory.ElseBlock(GetStatementList(falseStatements)) ) End Function Private Function GetStatementList(nodes As IEnumerable(Of SyntaxNode)) As SyntaxList(Of StatementSyntax) If nodes Is Nothing Then Return Nothing Else Return SyntaxFactory.List(nodes.Select(AddressOf AsStatement)) End If End Function Private Function AsStatement(node As SyntaxNode) As StatementSyntax Dim expr = TryCast(node, ExpressionSyntax) If expr IsNot Nothing Then Return SyntaxFactory.ExpressionStatement(expr) Else Return DirectCast(node, StatementSyntax) End If End Function Public Overloads Overrides Function InvocationExpression(expression As SyntaxNode, arguments As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.InvocationExpression(ParenthesizeLeft(expression), CreateArgumentList(arguments)) End Function Public Overrides Function IsTypeExpression(expression As SyntaxNode, type As SyntaxNode) As SyntaxNode Return SyntaxFactory.TypeOfIsExpression(Parenthesize(expression), DirectCast(type, TypeSyntax)) End Function Public Overrides Function TypeOfExpression(type As SyntaxNode) As SyntaxNode Return SyntaxFactory.GetTypeExpression(DirectCast(type, TypeSyntax)) End Function Public Overrides Function LogicalAndExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.AndAlsoExpression(Parenthesize(left), Parenthesize(right)) End Function Public Overrides Function LogicalNotExpression(expression As SyntaxNode) As SyntaxNode Return SyntaxFactory.NotExpression(Parenthesize(expression)) End Function Public Overrides Function LogicalOrExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.OrElseExpression(Parenthesize(left), Parenthesize(right)) End Function Friend Overrides Function MemberAccessExpressionWorker(expression As SyntaxNode, simpleName As SyntaxNode) As SyntaxNode Return SyntaxFactory.SimpleMemberAccessExpression( If(expression IsNot Nothing, ParenthesizeLeft(expression), Nothing), SyntaxFactory.Token(SyntaxKind.DotToken), DirectCast(simpleName, SimpleNameSyntax)) End Function Public Overrides Function ConditionalAccessExpression(expression As SyntaxNode, whenNotNull As SyntaxNode) As SyntaxNode Return SyntaxGeneratorInternal.ConditionalAccessExpression(expression, whenNotNull) End Function Public Overrides Function MemberBindingExpression(name As SyntaxNode) As SyntaxNode Return SyntaxGeneratorInternal.MemberBindingExpression(name) End Function Public Overrides Function ElementBindingExpression(arguments As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.InvocationExpression(expression:=Nothing, SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList(arguments))) End Function ' parenthesize the left-side of a dot or target of an invocation if not unnecessary Private Shared Function ParenthesizeLeft(expression As SyntaxNode) As ExpressionSyntax Dim expressionSyntax = DirectCast(expression, ExpressionSyntax) If TypeOf expressionSyntax Is TypeSyntax _ OrElse expressionSyntax.IsMeMyBaseOrMyClass() _ OrElse expressionSyntax.IsKind(SyntaxKind.ParenthesizedExpression) _ OrElse expressionSyntax.IsKind(SyntaxKind.InvocationExpression) _ OrElse expressionSyntax.IsKind(SyntaxKind.SimpleMemberAccessExpression) Then Return expressionSyntax Else Return expressionSyntax.Parenthesize() End If End Function Public Overrides Function MultiplyExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.MultiplyExpression(Parenthesize(left), Parenthesize(right)) End Function Public Overrides Function NegateExpression(expression As SyntaxNode) As SyntaxNode Return SyntaxFactory.UnaryMinusExpression(Parenthesize(expression)) End Function Private Shared Function AsExpressionList(expressions As IEnumerable(Of SyntaxNode)) As SeparatedSyntaxList(Of ExpressionSyntax) Return SyntaxFactory.SeparatedList(Of ExpressionSyntax)(expressions.OfType(Of ExpressionSyntax)()) End Function Public Overrides Function ArrayCreationExpression(elementType As SyntaxNode, size As SyntaxNode) As SyntaxNode Dim sizes = SyntaxFactory.ArgumentList(SyntaxFactory.SingletonSeparatedList(AsArgument(size))) Dim initializer = SyntaxFactory.CollectionInitializer() Return SyntaxFactory.ArrayCreationExpression(Nothing, DirectCast(elementType, TypeSyntax), sizes, initializer) End Function Public Overrides Function ArrayCreationExpression(elementType As SyntaxNode, elements As IEnumerable(Of SyntaxNode)) As SyntaxNode Dim sizes = SyntaxFactory.ArgumentList() Dim initializer = SyntaxFactory.CollectionInitializer(AsExpressionList(elements)) Return SyntaxFactory.ArrayCreationExpression(Nothing, DirectCast(elementType, TypeSyntax), sizes, initializer) End Function Public Overloads Overrides Function ObjectCreationExpression(typeName As SyntaxNode, arguments As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.ObjectCreationExpression( attributeLists:=Nothing, DirectCast(typeName, TypeSyntax), CreateArgumentList(arguments), initializer:=Nothing) End Function Friend Overrides Function ObjectCreationExpression(typeName As SyntaxNode, openParen As SyntaxToken, arguments As SeparatedSyntaxList(Of SyntaxNode), closeParen As SyntaxToken) As SyntaxNode Return SyntaxFactory.ObjectCreationExpression( attributeLists:=Nothing, DirectCast(typeName, TypeSyntax), SyntaxFactory.ArgumentList(openParen, arguments, closeParen), initializer:=Nothing) End Function Public Overrides Function QualifiedName(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.QualifiedName(DirectCast(left, NameSyntax), DirectCast(right, SimpleNameSyntax)) End Function Friend Overrides Function GlobalAliasedName(name As SyntaxNode) As SyntaxNode Return QualifiedName(SyntaxFactory.GlobalName(), name) End Function Public Overrides Function ReferenceEqualsExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.IsExpression(Parenthesize(left), Parenthesize(right)) End Function Public Overrides Function ReferenceNotEqualsExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.IsNotExpression(Parenthesize(left), Parenthesize(right)) End Function Public Overrides Function ReturnStatement(Optional expressionOpt As SyntaxNode = Nothing) As SyntaxNode Return SyntaxFactory.ReturnStatement(DirectCast(expressionOpt, ExpressionSyntax)) End Function Public Overrides Function ThisExpression() As SyntaxNode Return SyntaxFactory.MeExpression() End Function Public Overrides Function ThrowStatement(Optional expressionOpt As SyntaxNode = Nothing) As SyntaxNode Return SyntaxFactory.ThrowStatement(DirectCast(expressionOpt, ExpressionSyntax)) End Function Public Overrides Function ThrowExpression(expression As SyntaxNode) As SyntaxNode Throw New NotSupportedException("ThrowExpressions are not supported in Visual Basic") End Function Friend Overrides Function SupportsThrowExpression() As Boolean Return False End Function Public Overrides Function NameExpression(namespaceOrTypeSymbol As INamespaceOrTypeSymbol) As SyntaxNode Return namespaceOrTypeSymbol.GenerateTypeSyntax() End Function Public Overrides Function TypeExpression(typeSymbol As ITypeSymbol) As SyntaxNode Return typeSymbol.GenerateTypeSyntax() End Function Public Overrides Function TypeExpression(specialType As SpecialType) As SyntaxNode Select Case specialType Case SpecialType.System_Boolean Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.BooleanKeyword)) Case SpecialType.System_Byte Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.ByteKeyword)) Case SpecialType.System_Char Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.CharKeyword)) Case SpecialType.System_Decimal Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.DecimalKeyword)) Case SpecialType.System_Double Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.DoubleKeyword)) Case SpecialType.System_Int16 Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.ShortKeyword)) Case SpecialType.System_Int32 Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.IntegerKeyword)) Case SpecialType.System_Int64 Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.LongKeyword)) Case SpecialType.System_Object Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.ObjectKeyword)) Case SpecialType.System_SByte Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.SByteKeyword)) Case SpecialType.System_Single Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.SingleKeyword)) Case SpecialType.System_String Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.StringKeyword)) Case SpecialType.System_UInt16 Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.UShortKeyword)) Case SpecialType.System_UInt32 Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.UIntegerKeyword)) Case SpecialType.System_UInt64 Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.ULongKeyword)) Case SpecialType.System_DateTime Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.DateKeyword)) Case Else Throw New NotSupportedException("Unsupported SpecialType") End Select End Function Public Overloads Overrides Function UsingStatement(type As SyntaxNode, identifier As String, expression As SyntaxNode, statements As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.UsingBlock( SyntaxFactory.UsingStatement( expression:=Nothing, variables:=SyntaxFactory.SingletonSeparatedList(VisualBasicSyntaxGeneratorInternal.VariableDeclarator(type, identifier.ToModifiedIdentifier, expression))), GetStatementList(statements)) End Function Public Overloads Overrides Function UsingStatement(expression As SyntaxNode, statements As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.UsingBlock( SyntaxFactory.UsingStatement( expression:=DirectCast(expression, ExpressionSyntax), variables:=Nothing), GetStatementList(statements)) End Function Public Overrides Function LockStatement(expression As SyntaxNode, statements As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.SyncLockBlock( SyntaxFactory.SyncLockStatement( expression:=DirectCast(expression, ExpressionSyntax)), GetStatementList(statements)) End Function Public Overrides Function ValueEqualsExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.EqualsExpression(Parenthesize(left), Parenthesize(right)) End Function Public Overrides Function ValueNotEqualsExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.NotEqualsExpression(Parenthesize(left), Parenthesize(right)) End Function Private Function CreateArgumentList(arguments As IEnumerable(Of SyntaxNode)) As ArgumentListSyntax Return SyntaxFactory.ArgumentList(CreateArguments(arguments)) End Function Private Function CreateArguments(arguments As IEnumerable(Of SyntaxNode)) As SeparatedSyntaxList(Of ArgumentSyntax) Return SyntaxFactory.SeparatedList(arguments.Select(AddressOf AsArgument)) End Function Private Function AsArgument(argOrExpression As SyntaxNode) As ArgumentSyntax Return If(TryCast(argOrExpression, ArgumentSyntax), SyntaxFactory.SimpleArgument(DirectCast(argOrExpression, ExpressionSyntax))) End Function Private Function AsSimpleArgument(argOrExpression As SyntaxNode) As SimpleArgumentSyntax Return If(TryCast(argOrExpression, SimpleArgumentSyntax), SyntaxFactory.SimpleArgument(DirectCast(argOrExpression, ExpressionSyntax))) End Function Public Overloads Overrides Function LocalDeclarationStatement(type As SyntaxNode, identifier As String, Optional initializer As SyntaxNode = Nothing, Optional isConst As Boolean = False) As SyntaxNode Return LocalDeclarationStatement(type, identifier.ToIdentifierToken, initializer, isConst) End Function Public Overloads Overrides Function SwitchStatement(expression As SyntaxNode, caseClauses As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.SelectBlock( SyntaxFactory.SelectStatement(DirectCast(expression, ExpressionSyntax)), SyntaxFactory.List(caseClauses.Cast(Of CaseBlockSyntax))) End Function Public Overloads Overrides Function SwitchSection(expressions As IEnumerable(Of SyntaxNode), statements As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.CaseBlock( SyntaxFactory.CaseStatement(GetCaseClauses(expressions)), GetStatementList(statements)) End Function Friend Overrides Function SwitchSectionFromLabels(labels As IEnumerable(Of SyntaxNode), statements As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.CaseBlock( SyntaxFactory.CaseStatement(SyntaxFactory.SeparatedList(labels.Cast(Of CaseClauseSyntax))), GetStatementList(statements)) End Function Public Overrides Function DefaultSwitchSection(statements As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.CaseElseBlock( SyntaxFactory.CaseElseStatement(SyntaxFactory.ElseCaseClause()), GetStatementList(statements)) End Function Private Shared Function GetCaseClauses(expressions As IEnumerable(Of SyntaxNode)) As SeparatedSyntaxList(Of CaseClauseSyntax) Dim cases = SyntaxFactory.SeparatedList(Of CaseClauseSyntax) If expressions IsNot Nothing Then cases = cases.AddRange(expressions.Select(Function(e) SyntaxFactory.SimpleCaseClause(DirectCast(e, ExpressionSyntax)))) End If Return cases End Function Public Overrides Function ExitSwitchStatement() As SyntaxNode Return SyntaxFactory.ExitSelectStatement() End Function Public Overloads Overrides Function ValueReturningLambdaExpression(parameters As IEnumerable(Of SyntaxNode), expression As SyntaxNode) As SyntaxNode Return SyntaxFactory.SingleLineFunctionLambdaExpression( SyntaxFactory.FunctionLambdaHeader().WithParameterList(GetParameterList(parameters)), DirectCast(expression, ExpressionSyntax)) End Function Public Overrides Function VoidReturningLambdaExpression(lambdaParameters As IEnumerable(Of SyntaxNode), expression As SyntaxNode) As SyntaxNode Return SyntaxFactory.SingleLineSubLambdaExpression( SyntaxFactory.SubLambdaHeader().WithParameterList(GetParameterList(lambdaParameters)), AsStatement(expression)) End Function Public Overloads Overrides Function ValueReturningLambdaExpression(lambdaParameters As IEnumerable(Of SyntaxNode), statements As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.MultiLineFunctionLambdaExpression( SyntaxFactory.FunctionLambdaHeader().WithParameterList(GetParameterList(lambdaParameters)), GetStatementList(statements), SyntaxFactory.EndFunctionStatement()) End Function Public Overrides Function VoidReturningLambdaExpression(lambdaParameters As IEnumerable(Of SyntaxNode), statements As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.MultiLineSubLambdaExpression( SyntaxFactory.SubLambdaHeader().WithParameterList(GetParameterList(lambdaParameters)), GetStatementList(statements), SyntaxFactory.EndSubStatement()) End Function Public Overrides Function LambdaParameter(identifier As String, Optional type As SyntaxNode = Nothing) As SyntaxNode Return ParameterDeclaration(identifier, type) End Function Public Overrides Function ArrayTypeExpression(type As SyntaxNode) As SyntaxNode Dim arrayType = TryCast(type, ArrayTypeSyntax) If arrayType IsNot Nothing Then Return arrayType.WithRankSpecifiers(arrayType.RankSpecifiers.Add(SyntaxFactory.ArrayRankSpecifier())) Else Return SyntaxFactory.ArrayType(DirectCast(type, TypeSyntax), SyntaxFactory.SingletonList(SyntaxFactory.ArrayRankSpecifier())) End If End Function Public Overrides Function NullableTypeExpression(type As SyntaxNode) As SyntaxNode Dim nullableType = TryCast(type, NullableTypeSyntax) If nullableType IsNot Nothing Then Return nullableType Else Return SyntaxFactory.NullableType(DirectCast(type, TypeSyntax)) End If End Function Friend Overrides Function CreateTupleType(elements As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.TupleType(SyntaxFactory.SeparatedList(elements.Cast(Of TupleElementSyntax)())) End Function Public Overrides Function TupleElementExpression(type As SyntaxNode, Optional name As String = Nothing) As SyntaxNode If name Is Nothing Then Return SyntaxFactory.TypedTupleElement(DirectCast(type, TypeSyntax)) Else Return SyntaxFactory.NamedTupleElement(name.ToIdentifierToken(), SyntaxFactory.SimpleAsClause(DirectCast(type, TypeSyntax))) End If End Function Public Overrides Function WithTypeArguments(name As SyntaxNode, typeArguments As IEnumerable(Of SyntaxNode)) As SyntaxNode If name.IsKind(SyntaxKind.IdentifierName) OrElse name.IsKind(SyntaxKind.GenericName) Then Dim sname = DirectCast(name, SimpleNameSyntax) Return SyntaxFactory.GenericName(sname.Identifier, SyntaxFactory.TypeArgumentList(SyntaxFactory.SeparatedList(typeArguments.Cast(Of TypeSyntax)()))) ElseIf name.IsKind(SyntaxKind.QualifiedName) Then Dim qname = DirectCast(name, QualifiedNameSyntax) Return SyntaxFactory.QualifiedName(qname.Left, DirectCast(WithTypeArguments(qname.Right, typeArguments), SimpleNameSyntax)) ElseIf name.IsKind(SyntaxKind.SimpleMemberAccessExpression) Then Dim sma = DirectCast(name, MemberAccessExpressionSyntax) Return SyntaxFactory.MemberAccessExpression(name.Kind(), sma.Expression, sma.OperatorToken, DirectCast(WithTypeArguments(sma.Name, typeArguments), SimpleNameSyntax)) Else Throw New NotSupportedException() End If End Function Public Overrides Function SubtractExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.SubtractExpression(Parenthesize(left), Parenthesize(right)) End Function Public Overrides Function DivideExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.DivideExpression(Parenthesize(left), Parenthesize(right)) End Function Public Overrides Function ModuloExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.ModuloExpression(Parenthesize(left), Parenthesize(right)) End Function Public Overrides Function BitwiseNotExpression(operand As SyntaxNode) As SyntaxNode Return SyntaxFactory.NotExpression(Parenthesize(operand)) End Function Public Overrides Function CoalesceExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.BinaryConditionalExpression(DirectCast(left, ExpressionSyntax), DirectCast(right, ExpressionSyntax)) End Function Public Overrides Function LessThanExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.LessThanExpression(Parenthesize(left), Parenthesize(right)) End Function Public Overrides Function LessThanOrEqualExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.LessThanOrEqualExpression(Parenthesize(left), Parenthesize(right)) End Function Public Overrides Function GreaterThanExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.GreaterThanExpression(Parenthesize(left), Parenthesize(right)) End Function Public Overrides Function GreaterThanOrEqualExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode Return SyntaxFactory.GreaterThanOrEqualExpression(Parenthesize(left), Parenthesize(right)) End Function Public Overrides Function TryCatchStatement(tryStatements As IEnumerable(Of SyntaxNode), catchClauses As IEnumerable(Of SyntaxNode), Optional finallyStatements As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Return SyntaxFactory.TryBlock( GetStatementList(tryStatements), If(catchClauses IsNot Nothing, SyntaxFactory.List(catchClauses.Cast(Of CatchBlockSyntax)()), Nothing), If(finallyStatements IsNot Nothing, SyntaxFactory.FinallyBlock(GetStatementList(finallyStatements)), Nothing) ) End Function Public Overrides Function CatchClause(type As SyntaxNode, identifier As String, statements As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.CatchBlock( SyntaxFactory.CatchStatement( SyntaxFactory.IdentifierName(identifier), SyntaxFactory.SimpleAsClause(DirectCast(type, TypeSyntax)), whenClause:=Nothing ), GetStatementList(statements) ) End Function Public Overrides Function WhileStatement(condition As SyntaxNode, statements As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.WhileBlock( SyntaxFactory.WhileStatement(DirectCast(condition, ExpressionSyntax)), GetStatementList(statements)) End Function Friend Overrides Function ScopeBlock(statements As IEnumerable(Of SyntaxNode)) As SyntaxNode Throw New NotSupportedException() End Function Friend Overrides Function ParseExpression(stringToParse As String) As SyntaxNode Return SyntaxFactory.ParseExpression(stringToParse) End Function #End Region #Region "Declarations" Private Shared ReadOnly s_fieldModifiers As DeclarationModifiers = DeclarationModifiers.Const Or DeclarationModifiers.[New] Or DeclarationModifiers.ReadOnly Or DeclarationModifiers.Static Or DeclarationModifiers.WithEvents Private Shared ReadOnly s_methodModifiers As DeclarationModifiers = DeclarationModifiers.Abstract Or DeclarationModifiers.Async Or DeclarationModifiers.[New] Or DeclarationModifiers.Override Or DeclarationModifiers.Partial Or DeclarationModifiers.Sealed Or DeclarationModifiers.Static Or DeclarationModifiers.Virtual Private Shared ReadOnly s_constructorModifiers As DeclarationModifiers = DeclarationModifiers.Static Private Shared ReadOnly s_propertyModifiers As DeclarationModifiers = DeclarationModifiers.Abstract Or DeclarationModifiers.[New] Or DeclarationModifiers.Override Or DeclarationModifiers.ReadOnly Or DeclarationModifiers.WriteOnly Or DeclarationModifiers.Sealed Or DeclarationModifiers.Static Or DeclarationModifiers.Virtual Private Shared ReadOnly s_indexerModifiers As DeclarationModifiers = DeclarationModifiers.Abstract Or DeclarationModifiers.[New] Or DeclarationModifiers.Override Or DeclarationModifiers.ReadOnly Or DeclarationModifiers.WriteOnly Or DeclarationModifiers.Sealed Or DeclarationModifiers.Static Or DeclarationModifiers.Virtual Private Shared ReadOnly s_classModifiers As DeclarationModifiers = DeclarationModifiers.Abstract Or DeclarationModifiers.[New] Or DeclarationModifiers.Partial Or DeclarationModifiers.Sealed Or DeclarationModifiers.Static Private Shared ReadOnly s_structModifiers As DeclarationModifiers = DeclarationModifiers.[New] Or DeclarationModifiers.Partial Private Shared ReadOnly s_interfaceModifiers As DeclarationModifiers = DeclarationModifiers.[New] Or DeclarationModifiers.Partial Private Shared ReadOnly s_accessorModifiers As DeclarationModifiers = DeclarationModifiers.Abstract Or DeclarationModifiers.[New] Or DeclarationModifiers.Override Or DeclarationModifiers.Virtual Private Shared Function GetAllowedModifiers(kind As SyntaxKind) As DeclarationModifiers Select Case kind Case SyntaxKind.ClassBlock, SyntaxKind.ClassStatement Return s_classModifiers Case SyntaxKind.EnumBlock, SyntaxKind.EnumStatement Return DeclarationModifiers.[New] Case SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement Return DeclarationModifiers.[New] Case SyntaxKind.InterfaceBlock, SyntaxKind.InterfaceStatement Return s_interfaceModifiers Case SyntaxKind.StructureBlock, SyntaxKind.StructureStatement Return s_structModifiers Case SyntaxKind.FunctionBlock, SyntaxKind.FunctionStatement, SyntaxKind.SubBlock, SyntaxKind.SubStatement, SyntaxKind.OperatorBlock, SyntaxKind.OperatorStatement Return s_methodModifiers Case SyntaxKind.ConstructorBlock, SyntaxKind.SubNewStatement Return s_constructorModifiers Case SyntaxKind.FieldDeclaration Return s_fieldModifiers Case SyntaxKind.PropertyBlock, SyntaxKind.PropertyStatement Return s_propertyModifiers Case SyntaxKind.EventBlock, SyntaxKind.EventStatement Return s_propertyModifiers Case SyntaxKind.GetAccessorBlock, SyntaxKind.GetAccessorStatement, SyntaxKind.SetAccessorBlock, SyntaxKind.SetAccessorStatement, SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.AddHandlerAccessorStatement, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorStatement, SyntaxKind.RaiseEventAccessorBlock, SyntaxKind.RaiseEventAccessorStatement Return s_accessorModifiers Case SyntaxKind.EnumMemberDeclaration Case SyntaxKind.Parameter Case SyntaxKind.LocalDeclarationStatement Case Else Return DeclarationModifiers.None End Select End Function Public Overrides Function FieldDeclaration(name As String, type As SyntaxNode, Optional accessibility As Accessibility = Nothing, Optional modifiers As DeclarationModifiers = Nothing, Optional initializer As SyntaxNode = Nothing) As SyntaxNode Return SyntaxFactory.FieldDeclaration( attributeLists:=Nothing, modifiers:=GetModifierList(accessibility, modifiers And s_fieldModifiers, declaration:=Nothing, DeclarationKind.Field), declarators:=SyntaxFactory.SingletonSeparatedList(VisualBasicSyntaxGeneratorInternal.VariableDeclarator(type, name.ToModifiedIdentifier, initializer))) End Function Public Overrides Function MethodDeclaration( identifier As String, Optional parameters As IEnumerable(Of SyntaxNode) = Nothing, Optional typeParameters As IEnumerable(Of String) = Nothing, Optional returnType As SyntaxNode = Nothing, Optional accessibility As Accessibility = Nothing, Optional modifiers As DeclarationModifiers = Nothing, Optional statements As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Dim statement = SyntaxFactory.MethodStatement( kind:=If(returnType Is Nothing, SyntaxKind.SubStatement, SyntaxKind.FunctionStatement), attributeLists:=Nothing, modifiers:=GetModifierList(accessibility, modifiers And s_methodModifiers, declaration:=Nothing, DeclarationKind.Method), subOrFunctionKeyword:=If(returnType Is Nothing, SyntaxFactory.Token(SyntaxKind.SubKeyword), SyntaxFactory.Token(SyntaxKind.FunctionKeyword)), identifier:=identifier.ToIdentifierToken(), typeParameterList:=GetTypeParameters(typeParameters), parameterList:=GetParameterList(parameters), asClause:=If(returnType IsNot Nothing, SyntaxFactory.SimpleAsClause(DirectCast(returnType, TypeSyntax)), Nothing), handlesClause:=Nothing, implementsClause:=Nothing) If modifiers.IsAbstract Then Return statement Else Return SyntaxFactory.MethodBlock( kind:=If(returnType Is Nothing, SyntaxKind.SubBlock, SyntaxKind.FunctionBlock), subOrFunctionStatement:=statement, statements:=GetStatementList(statements), endSubOrFunctionStatement:=If(returnType Is Nothing, SyntaxFactory.EndSubStatement(), SyntaxFactory.EndFunctionStatement())) End If End Function Public Overrides Function OperatorDeclaration(kind As OperatorKind, Optional parameters As IEnumerable(Of SyntaxNode) = Nothing, Optional returnType As SyntaxNode = Nothing, Optional accessibility As Accessibility = Accessibility.NotApplicable, Optional modifiers As DeclarationModifiers = Nothing, Optional statements As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Dim statement As OperatorStatementSyntax Dim asClause = If(returnType IsNot Nothing, SyntaxFactory.SimpleAsClause(DirectCast(returnType, TypeSyntax)), Nothing) Dim parameterList = GetParameterList(parameters) Dim operatorToken = SyntaxFactory.Token(GetTokenKind(kind)) Dim modifierList As SyntaxTokenList = GetModifierList(accessibility, modifiers And s_methodModifiers, declaration:=Nothing, DeclarationKind.Operator) If kind = OperatorKind.ImplicitConversion OrElse kind = OperatorKind.ExplicitConversion Then modifierList = modifierList.Add(SyntaxFactory.Token( If(kind = OperatorKind.ImplicitConversion, SyntaxKind.WideningKeyword, SyntaxKind.NarrowingKeyword))) statement = SyntaxFactory.OperatorStatement( attributeLists:=Nothing, modifiers:=modifierList, operatorToken:=operatorToken, parameterList:=parameterList, asClause:=asClause) Else statement = SyntaxFactory.OperatorStatement( attributeLists:=Nothing, modifiers:=modifierList, operatorToken:=operatorToken, parameterList:=parameterList, asClause:=asClause) End If If modifiers.IsAbstract Then Return statement Else Return SyntaxFactory.OperatorBlock( operatorStatement:=statement, statements:=GetStatementList(statements), endOperatorStatement:=SyntaxFactory.EndOperatorStatement()) End If End Function Private Shared Function GetTokenKind(kind As OperatorKind) As SyntaxKind Select Case kind Case OperatorKind.ImplicitConversion, OperatorKind.ExplicitConversion Return SyntaxKind.CTypeKeyword Case OperatorKind.Addition Return SyntaxKind.PlusToken Case OperatorKind.BitwiseAnd Return SyntaxKind.AndKeyword Case OperatorKind.BitwiseOr Return SyntaxKind.OrKeyword Case OperatorKind.Division Return SyntaxKind.SlashToken Case OperatorKind.Equality Return SyntaxKind.EqualsToken Case OperatorKind.ExclusiveOr Return SyntaxKind.XorKeyword Case OperatorKind.False Return SyntaxKind.IsFalseKeyword Case OperatorKind.GreaterThan Return SyntaxKind.GreaterThanToken Case OperatorKind.GreaterThanOrEqual Return SyntaxKind.GreaterThanEqualsToken Case OperatorKind.Inequality Return SyntaxKind.LessThanGreaterThanToken Case OperatorKind.LeftShift Return SyntaxKind.LessThanLessThanToken Case OperatorKind.LessThan Return SyntaxKind.LessThanToken Case OperatorKind.LessThanOrEqual Return SyntaxKind.LessThanEqualsToken Case OperatorKind.LogicalNot Return SyntaxKind.NotKeyword Case OperatorKind.Modulus Return SyntaxKind.ModKeyword Case OperatorKind.Multiply Return SyntaxKind.AsteriskToken Case OperatorKind.RightShift Return SyntaxKind.GreaterThanGreaterThanToken Case OperatorKind.Subtraction Return SyntaxKind.MinusToken Case OperatorKind.True Return SyntaxKind.IsTrueKeyword Case OperatorKind.UnaryNegation Return SyntaxKind.MinusToken Case OperatorKind.UnaryPlus Return SyntaxKind.PlusToken Case Else Throw New ArgumentException($"Operator {kind} cannot be generated in Visual Basic.") End Select End Function Private Shared Function GetParameterList(parameters As IEnumerable(Of SyntaxNode)) As ParameterListSyntax Return If(parameters IsNot Nothing, SyntaxFactory.ParameterList(SyntaxFactory.SeparatedList(parameters.Cast(Of ParameterSyntax)())), SyntaxFactory.ParameterList()) End Function Public Overrides Function ParameterDeclaration(name As String, Optional type As SyntaxNode = Nothing, Optional initializer As SyntaxNode = Nothing, Optional refKind As RefKind = Nothing) As SyntaxNode Return SyntaxFactory.Parameter( attributeLists:=Nothing, modifiers:=GetParameterModifiers(refKind, initializer), identifier:=name.ToModifiedIdentifier(), asClause:=If(type IsNot Nothing, SyntaxFactory.SimpleAsClause(DirectCast(type, TypeSyntax)), Nothing), [default]:=If(initializer IsNot Nothing, SyntaxFactory.EqualsValue(DirectCast(initializer, ExpressionSyntax)), Nothing)) End Function Private Shared Function GetParameterModifiers(refKind As RefKind, initializer As SyntaxNode) As SyntaxTokenList Dim tokens As SyntaxTokenList = Nothing If initializer IsNot Nothing Then tokens = tokens.Add(SyntaxFactory.Token(SyntaxKind.OptionalKeyword)) End If If refKind <> RefKind.None Then tokens = tokens.Add(SyntaxFactory.Token(SyntaxKind.ByRefKeyword)) End If Return tokens End Function Public Overrides Function GetAccessorDeclaration(Optional accessibility As Accessibility = Accessibility.NotApplicable, Optional statements As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Return SyntaxFactory.GetAccessorBlock( SyntaxFactory.GetAccessorStatement().WithModifiers(GetModifierList(accessibility, DeclarationModifiers.None, declaration:=Nothing, DeclarationKind.Property)), GetStatementList(statements)) End Function Public Overrides Function SetAccessorDeclaration(Optional accessibility As Accessibility = Accessibility.NotApplicable, Optional statements As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Return SyntaxFactory.SetAccessorBlock( SyntaxFactory.SetAccessorStatement().WithModifiers(GetModifierList(accessibility, DeclarationModifiers.None, declaration:=Nothing, DeclarationKind.Property)), GetStatementList(statements)) End Function Public Overrides Function WithAccessorDeclarations(declaration As SyntaxNode, accessorDeclarations As IEnumerable(Of SyntaxNode)) As SyntaxNode Dim propertyBlock = GetPropertyBlock(declaration) If propertyBlock Is Nothing Then Return declaration End If propertyBlock = propertyBlock.WithAccessors( SyntaxFactory.List(accessorDeclarations.OfType(Of AccessorBlockSyntax))) Dim hasGetAccessor = propertyBlock.Accessors.Any(SyntaxKind.GetAccessorBlock) Dim hasSetAccessor = propertyBlock.Accessors.Any(SyntaxKind.SetAccessorBlock) If hasGetAccessor AndAlso Not hasSetAccessor Then propertyBlock = DirectCast(WithModifiers(propertyBlock, GetModifiers(propertyBlock) Or DeclarationModifiers.ReadOnly), PropertyBlockSyntax) ElseIf Not hasGetAccessor AndAlso hasSetAccessor Then propertyBlock = DirectCast(WithModifiers(propertyBlock, GetModifiers(propertyBlock) Or DeclarationModifiers.WriteOnly), PropertyBlockSyntax) ElseIf hasGetAccessor AndAlso hasSetAccessor Then propertyBlock = DirectCast(WithModifiers(propertyBlock, GetModifiers(propertyBlock).WithIsReadOnly(False).WithIsWriteOnly(False)), PropertyBlockSyntax) End If Return If(propertyBlock.Accessors.Count = 0, propertyBlock.PropertyStatement, DirectCast(propertyBlock, SyntaxNode)) End Function Private Shared Function GetPropertyBlock(declaration As SyntaxNode) As PropertyBlockSyntax Dim propertyBlock = TryCast(declaration, PropertyBlockSyntax) If propertyBlock IsNot Nothing Then Return propertyBlock End If Dim propertyStatement = TryCast(declaration, PropertyStatementSyntax) If propertyStatement IsNot Nothing Then Return SyntaxFactory.PropertyBlock(propertyStatement, SyntaxFactory.List(Of AccessorBlockSyntax)) End If Return Nothing End Function Public Overrides Function PropertyDeclaration( identifier As String, type As SyntaxNode, Optional accessibility As Accessibility = Nothing, Optional modifiers As DeclarationModifiers = Nothing, Optional getAccessorStatements As IEnumerable(Of SyntaxNode) = Nothing, Optional setAccessorStatements As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Dim asClause = SyntaxFactory.SimpleAsClause(DirectCast(type, TypeSyntax)) Dim statement = SyntaxFactory.PropertyStatement( attributeLists:=Nothing, modifiers:=GetModifierList(accessibility, modifiers And s_propertyModifiers, declaration:=Nothing, DeclarationKind.Property), identifier:=identifier.ToIdentifierToken(), parameterList:=Nothing, asClause:=asClause, initializer:=Nothing, implementsClause:=Nothing) If modifiers.IsAbstract Then Return statement Else Dim accessors = New List(Of AccessorBlockSyntax) If Not modifiers.IsWriteOnly Then accessors.Add(CreateGetAccessorBlock(getAccessorStatements)) End If If Not modifiers.IsReadOnly Then accessors.Add(CreateSetAccessorBlock(type, setAccessorStatements)) End If Return SyntaxFactory.PropertyBlock( propertyStatement:=statement, accessors:=SyntaxFactory.List(accessors), endPropertyStatement:=SyntaxFactory.EndPropertyStatement()) End If End Function Public Overrides Function IndexerDeclaration( parameters As IEnumerable(Of SyntaxNode), type As SyntaxNode, Optional accessibility As Accessibility = Nothing, Optional modifiers As DeclarationModifiers = Nothing, Optional getAccessorStatements As IEnumerable(Of SyntaxNode) = Nothing, Optional setAccessorStatements As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Dim asClause = SyntaxFactory.SimpleAsClause(DirectCast(type, TypeSyntax)) Dim statement = SyntaxFactory.PropertyStatement( attributeLists:=Nothing, modifiers:=GetModifierList(accessibility, modifiers And s_indexerModifiers, declaration:=Nothing, DeclarationKind.Indexer, isDefault:=True), identifier:=SyntaxFactory.Identifier("Item"), parameterList:=SyntaxFactory.ParameterList(SyntaxFactory.SeparatedList(parameters.Cast(Of ParameterSyntax))), asClause:=asClause, initializer:=Nothing, implementsClause:=Nothing) If modifiers.IsAbstract Then Return statement Else Dim accessors = New List(Of AccessorBlockSyntax) If Not modifiers.IsWriteOnly Then accessors.Add(CreateGetAccessorBlock(getAccessorStatements)) End If If Not modifiers.IsReadOnly Then accessors.Add(CreateSetAccessorBlock(type, setAccessorStatements)) End If Return SyntaxFactory.PropertyBlock( propertyStatement:=statement, accessors:=SyntaxFactory.List(accessors), endPropertyStatement:=SyntaxFactory.EndPropertyStatement()) End If End Function Private Function AccessorBlock(kind As SyntaxKind, statements As IEnumerable(Of SyntaxNode), type As SyntaxNode) As AccessorBlockSyntax Select Case kind Case SyntaxKind.GetAccessorBlock Return CreateGetAccessorBlock(statements) Case SyntaxKind.SetAccessorBlock Return CreateSetAccessorBlock(type, statements) Case SyntaxKind.AddHandlerAccessorBlock Return CreateAddHandlerAccessorBlock(type, statements) Case SyntaxKind.RemoveHandlerAccessorBlock Return CreateRemoveHandlerAccessorBlock(type, statements) Case Else Return Nothing End Select End Function Private Function CreateGetAccessorBlock(statements As IEnumerable(Of SyntaxNode)) As AccessorBlockSyntax Return SyntaxFactory.AccessorBlock( SyntaxKind.GetAccessorBlock, SyntaxFactory.AccessorStatement(SyntaxKind.GetAccessorStatement, SyntaxFactory.Token(SyntaxKind.GetKeyword)), GetStatementList(statements), SyntaxFactory.EndGetStatement()) End Function Private Function CreateSetAccessorBlock(type As SyntaxNode, statements As IEnumerable(Of SyntaxNode)) As AccessorBlockSyntax Dim asClause = SyntaxFactory.SimpleAsClause(DirectCast(type, TypeSyntax)) Dim valueParameter = SyntaxFactory.Parameter( attributeLists:=Nothing, modifiers:=Nothing, identifier:=SyntaxFactory.ModifiedIdentifier("value"), asClause:=asClause, [default]:=Nothing) Return SyntaxFactory.AccessorBlock( SyntaxKind.SetAccessorBlock, SyntaxFactory.AccessorStatement( kind:=SyntaxKind.SetAccessorStatement, attributeLists:=Nothing, modifiers:=Nothing, accessorKeyword:=SyntaxFactory.Token(SyntaxKind.SetKeyword), parameterList:=SyntaxFactory.ParameterList(SyntaxFactory.SingletonSeparatedList(valueParameter))), GetStatementList(statements), SyntaxFactory.EndSetStatement()) End Function Private Function CreateAddHandlerAccessorBlock(delegateType As SyntaxNode, statements As IEnumerable(Of SyntaxNode)) As AccessorBlockSyntax Dim asClause = SyntaxFactory.SimpleAsClause(DirectCast(delegateType, TypeSyntax)) Dim valueParameter = SyntaxFactory.Parameter( attributeLists:=Nothing, modifiers:=Nothing, identifier:=SyntaxFactory.ModifiedIdentifier("value"), asClause:=asClause, [default]:=Nothing) Return SyntaxFactory.AccessorBlock( SyntaxKind.AddHandlerAccessorBlock, SyntaxFactory.AccessorStatement( kind:=SyntaxKind.AddHandlerAccessorStatement, attributeLists:=Nothing, modifiers:=Nothing, accessorKeyword:=SyntaxFactory.Token(SyntaxKind.AddHandlerKeyword), parameterList:=SyntaxFactory.ParameterList(SyntaxFactory.SingletonSeparatedList(valueParameter))), GetStatementList(statements), SyntaxFactory.EndAddHandlerStatement()) End Function Private Function CreateRemoveHandlerAccessorBlock(delegateType As SyntaxNode, statements As IEnumerable(Of SyntaxNode)) As AccessorBlockSyntax Dim asClause = SyntaxFactory.SimpleAsClause(DirectCast(delegateType, TypeSyntax)) Dim valueParameter = SyntaxFactory.Parameter( attributeLists:=Nothing, modifiers:=Nothing, identifier:=SyntaxFactory.ModifiedIdentifier("value"), asClause:=asClause, [default]:=Nothing) Return SyntaxFactory.AccessorBlock( SyntaxKind.RemoveHandlerAccessorBlock, SyntaxFactory.AccessorStatement( kind:=SyntaxKind.RemoveHandlerAccessorStatement, attributeLists:=Nothing, modifiers:=Nothing, accessorKeyword:=SyntaxFactory.Token(SyntaxKind.RemoveHandlerKeyword), parameterList:=SyntaxFactory.ParameterList(SyntaxFactory.SingletonSeparatedList(valueParameter))), GetStatementList(statements), SyntaxFactory.EndRemoveHandlerStatement()) End Function Private Function CreateRaiseEventAccessorBlock(parameters As IEnumerable(Of SyntaxNode), statements As IEnumerable(Of SyntaxNode)) As AccessorBlockSyntax Dim parameterList = GetParameterList(parameters) Return SyntaxFactory.AccessorBlock( SyntaxKind.RaiseEventAccessorBlock, SyntaxFactory.AccessorStatement( kind:=SyntaxKind.RaiseEventAccessorStatement, attributeLists:=Nothing, modifiers:=Nothing, accessorKeyword:=SyntaxFactory.Token(SyntaxKind.RaiseEventKeyword), parameterList:=parameterList), GetStatementList(statements), SyntaxFactory.EndRaiseEventStatement()) End Function Public Overrides Function AsPublicInterfaceImplementation(declaration As SyntaxNode, interfaceTypeName As SyntaxNode, interfaceMemberName As String) As SyntaxNode Return Isolate(declaration, Function(decl) AsPublicInterfaceImplementationInternal(decl, interfaceTypeName, interfaceMemberName)) End Function Private Function AsPublicInterfaceImplementationInternal(declaration As SyntaxNode, interfaceTypeName As SyntaxNode, interfaceMemberName As String) As SyntaxNode Dim type = DirectCast(interfaceTypeName, NameSyntax) declaration = WithBody(declaration, allowDefault:=True) declaration = WithAccessibility(declaration, Accessibility.Public) Dim memberName = If(interfaceMemberName IsNot Nothing, interfaceMemberName, GetInterfaceMemberName(declaration)) declaration = WithName(declaration, memberName) declaration = WithImplementsClause(declaration, SyntaxFactory.ImplementsClause(SyntaxFactory.QualifiedName(type, SyntaxFactory.IdentifierName(memberName)))) Return declaration End Function Public Overrides Function AsPrivateInterfaceImplementation(declaration As SyntaxNode, interfaceTypeName As SyntaxNode, interfaceMemberName As String) As SyntaxNode Return Isolate(declaration, Function(decl) AsPrivateInterfaceImplementationInternal(decl, interfaceTypeName, interfaceMemberName)) End Function Private Function AsPrivateInterfaceImplementationInternal(declaration As SyntaxNode, interfaceTypeName As SyntaxNode, interfaceMemberName As String) As SyntaxNode Dim type = DirectCast(interfaceTypeName, NameSyntax) declaration = WithBody(declaration, allowDefault:=False) declaration = WithAccessibility(declaration, Accessibility.Private) Dim memberName = If(interfaceMemberName IsNot Nothing, interfaceMemberName, GetInterfaceMemberName(declaration)) declaration = WithName(declaration, GetNameAsIdentifier(interfaceTypeName) & "_" & memberName) declaration = WithImplementsClause(declaration, SyntaxFactory.ImplementsClause(SyntaxFactory.QualifiedName(type, SyntaxFactory.IdentifierName(memberName)))) Return declaration End Function Private Function GetInterfaceMemberName(declaration As SyntaxNode) As String Dim clause = GetImplementsClause(declaration) If clause IsNot Nothing Then Dim qname = clause.InterfaceMembers.FirstOrDefault(Function(n) n.Right IsNot Nothing) If qname IsNot Nothing Then Return qname.Right.ToString() End If End If Return GetName(declaration) End Function Private Shared Function GetImplementsClause(declaration As SyntaxNode) As ImplementsClauseSyntax Select Case declaration.Kind Case SyntaxKind.SubBlock, SyntaxKind.FunctionBlock Return DirectCast(declaration, MethodBlockSyntax).SubOrFunctionStatement.ImplementsClause Case SyntaxKind.SubStatement, SyntaxKind.FunctionStatement Return DirectCast(declaration, MethodStatementSyntax).ImplementsClause Case SyntaxKind.PropertyBlock Return DirectCast(declaration, PropertyBlockSyntax).PropertyStatement.ImplementsClause Case SyntaxKind.PropertyStatement Return DirectCast(declaration, PropertyStatementSyntax).ImplementsClause Case Else Return Nothing End Select End Function Private Shared Function WithImplementsClause(declaration As SyntaxNode, clause As ImplementsClauseSyntax) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.SubBlock, SyntaxKind.FunctionBlock Dim mb = DirectCast(declaration, MethodBlockSyntax) Return mb.WithSubOrFunctionStatement(mb.SubOrFunctionStatement.WithImplementsClause(clause)) Case SyntaxKind.SubStatement, SyntaxKind.FunctionStatement Return DirectCast(declaration, MethodStatementSyntax).WithImplementsClause(clause) Case SyntaxKind.PropertyBlock Dim pb = DirectCast(declaration, PropertyBlockSyntax) Return pb.WithPropertyStatement(pb.PropertyStatement.WithImplementsClause(clause)) Case SyntaxKind.PropertyStatement Return DirectCast(declaration, PropertyStatementSyntax).WithImplementsClause(clause) Case Else Return declaration End Select End Function Private Function GetNameAsIdentifier(type As SyntaxNode) As String Dim name = TryCast(type, IdentifierNameSyntax) If name IsNot Nothing Then Return name.Identifier.ValueText End If Dim gname = TryCast(type, GenericNameSyntax) If gname IsNot Nothing Then Return gname.Identifier.ValueText & "_" & gname.TypeArgumentList.Arguments.Select(Function(t) GetNameAsIdentifier(t)).Aggregate(Function(a, b) a & "_" & b) End If Dim qname = TryCast(type, QualifiedNameSyntax) If qname IsNot Nothing Then Return GetNameAsIdentifier(qname.Right) End If Return "[" & type.ToString() & "]" End Function Private Function WithBody(declaration As SyntaxNode, allowDefault As Boolean) As SyntaxNode declaration = Me.WithModifiersInternal(declaration, Me.GetModifiers(declaration) - DeclarationModifiers.Abstract) Dim method = TryCast(declaration, MethodStatementSyntax) If method IsNot Nothing Then Return SyntaxFactory.MethodBlock( kind:=If(method.IsKind(SyntaxKind.FunctionStatement), SyntaxKind.FunctionBlock, SyntaxKind.SubBlock), subOrFunctionStatement:=method, endSubOrFunctionStatement:=If(method.IsKind(SyntaxKind.FunctionStatement), SyntaxFactory.EndFunctionStatement(), SyntaxFactory.EndSubStatement())) End If Dim prop = TryCast(declaration, PropertyStatementSyntax) If prop IsNot Nothing Then prop = prop.WithModifiers(WithIsDefault(prop.Modifiers, GetIsDefault(prop.Modifiers) And allowDefault, declaration)) Dim accessors = New List(Of AccessorBlockSyntax) accessors.Add(CreateGetAccessorBlock(Nothing)) If (Not prop.Modifiers.Any(SyntaxKind.ReadOnlyKeyword)) Then accessors.Add(CreateSetAccessorBlock(prop.AsClause.Type, Nothing)) End If Return SyntaxFactory.PropertyBlock( propertyStatement:=prop, accessors:=SyntaxFactory.List(accessors), endPropertyStatement:=SyntaxFactory.EndPropertyStatement()) End If Return declaration End Function Private Function GetIsDefault(modifierList As SyntaxTokenList) As Boolean Dim access As Accessibility Dim modifiers As DeclarationModifiers Dim isDefault As Boolean SyntaxFacts.GetAccessibilityAndModifiers(modifierList, access, modifiers, isDefault) Return isDefault End Function Private Function WithIsDefault(modifierList As SyntaxTokenList, isDefault As Boolean, declaration As SyntaxNode) As SyntaxTokenList Dim access As Accessibility Dim modifiers As DeclarationModifiers Dim currentIsDefault As Boolean SyntaxFacts.GetAccessibilityAndModifiers(modifierList, access, modifiers, currentIsDefault) If currentIsDefault <> isDefault Then Return GetModifierList(access, modifiers, declaration, GetDeclarationKind(declaration), isDefault) Else Return modifierList End If End Function Public Overrides Function ConstructorDeclaration( Optional name As String = Nothing, Optional parameters As IEnumerable(Of SyntaxNode) = Nothing, Optional accessibility As Accessibility = Nothing, Optional modifiers As DeclarationModifiers = Nothing, Optional baseConstructorArguments As IEnumerable(Of SyntaxNode) = Nothing, Optional statements As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Dim stats = GetStatementList(statements) If (baseConstructorArguments IsNot Nothing) Then Dim baseCall = DirectCast(Me.ExpressionStatement(Me.InvocationExpression(Me.MemberAccessExpression(Me.BaseExpression(), SyntaxFactory.IdentifierName("New")), baseConstructorArguments)), StatementSyntax) stats = stats.Insert(0, baseCall) End If Return SyntaxFactory.ConstructorBlock( subNewStatement:=SyntaxFactory.SubNewStatement( attributeLists:=Nothing, modifiers:=GetModifierList(accessibility, modifiers And s_constructorModifiers, declaration:=Nothing, DeclarationKind.Constructor), parameterList:=If(parameters IsNot Nothing, SyntaxFactory.ParameterList(SyntaxFactory.SeparatedList(parameters.Cast(Of ParameterSyntax)())), SyntaxFactory.ParameterList())), statements:=stats) End Function Public Overrides Function ClassDeclaration( name As String, Optional typeParameters As IEnumerable(Of String) = Nothing, Optional accessibility As Accessibility = Nothing, Optional modifiers As DeclarationModifiers = Nothing, Optional baseType As SyntaxNode = Nothing, Optional interfaceTypes As IEnumerable(Of SyntaxNode) = Nothing, Optional members As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Dim itypes = If(interfaceTypes IsNot Nothing, interfaceTypes.Cast(Of TypeSyntax), Nothing) If itypes IsNot Nothing AndAlso itypes.Count = 0 Then itypes = Nothing End If Return SyntaxFactory.ClassBlock( classStatement:=SyntaxFactory.ClassStatement( attributeLists:=Nothing, modifiers:=GetModifierList(accessibility, modifiers And s_classModifiers, declaration:=Nothing, DeclarationKind.Class), identifier:=name.ToIdentifierToken(), typeParameterList:=GetTypeParameters(typeParameters)), [inherits]:=If(baseType IsNot Nothing, SyntaxFactory.SingletonList(SyntaxFactory.InheritsStatement(DirectCast(baseType, TypeSyntax))), Nothing), [implements]:=If(itypes IsNot Nothing, SyntaxFactory.SingletonList(SyntaxFactory.ImplementsStatement(SyntaxFactory.SeparatedList(itypes))), Nothing), members:=AsClassMembers(members)) End Function Private Function AsClassMembers(nodes As IEnumerable(Of SyntaxNode)) As SyntaxList(Of StatementSyntax) If nodes IsNot Nothing Then Return SyntaxFactory.List(nodes.Select(AddressOf AsClassMember).Where(Function(n) n IsNot Nothing)) Else Return Nothing End If End Function Private Function AsClassMember(node As SyntaxNode) As StatementSyntax Return TryCast(AsIsolatedDeclaration(node), StatementSyntax) End Function Public Overrides Function StructDeclaration( name As String, Optional typeParameters As IEnumerable(Of String) = Nothing, Optional accessibility As Accessibility = Nothing, Optional modifiers As DeclarationModifiers = Nothing, Optional interfaceTypes As IEnumerable(Of SyntaxNode) = Nothing, Optional members As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Dim itypes = If(interfaceTypes IsNot Nothing, interfaceTypes.Cast(Of TypeSyntax), Nothing) If itypes IsNot Nothing AndAlso itypes.Count = 0 Then itypes = Nothing End If Return SyntaxFactory.StructureBlock( structureStatement:=SyntaxFactory.StructureStatement( attributeLists:=Nothing, modifiers:=GetModifierList(accessibility, modifiers And s_structModifiers, declaration:=Nothing, DeclarationKind.Struct), identifier:=name.ToIdentifierToken(), typeParameterList:=GetTypeParameters(typeParameters)), [inherits]:=Nothing, [implements]:=If(itypes IsNot Nothing, SyntaxFactory.SingletonList(SyntaxFactory.ImplementsStatement(SyntaxFactory.SeparatedList(itypes))), Nothing), members:=If(members IsNot Nothing, SyntaxFactory.List(members.Cast(Of StatementSyntax)()), Nothing)) End Function Public Overrides Function InterfaceDeclaration( name As String, Optional typeParameters As IEnumerable(Of String) = Nothing, Optional accessibility As Accessibility = Nothing, Optional interfaceTypes As IEnumerable(Of SyntaxNode) = Nothing, Optional members As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Dim itypes = If(interfaceTypes IsNot Nothing, interfaceTypes.Cast(Of TypeSyntax), Nothing) If itypes IsNot Nothing AndAlso itypes.Count = 0 Then itypes = Nothing End If Return SyntaxFactory.InterfaceBlock( interfaceStatement:=SyntaxFactory.InterfaceStatement( attributeLists:=Nothing, modifiers:=GetModifierList(accessibility, DeclarationModifiers.None, declaration:=Nothing, DeclarationKind.Interface), identifier:=name.ToIdentifierToken(), typeParameterList:=GetTypeParameters(typeParameters)), [inherits]:=If(itypes IsNot Nothing, SyntaxFactory.SingletonList(SyntaxFactory.InheritsStatement(SyntaxFactory.SeparatedList(itypes))), Nothing), [implements]:=Nothing, members:=AsInterfaceMembers(members)) End Function Private Function AsInterfaceMembers(nodes As IEnumerable(Of SyntaxNode)) As SyntaxList(Of StatementSyntax) If nodes IsNot Nothing Then Return SyntaxFactory.List(nodes.Select(AddressOf AsInterfaceMember).Where(Function(n) n IsNot Nothing)) Else Return Nothing End If End Function Friend Overrides Function AsInterfaceMember(node As SyntaxNode) As SyntaxNode If node IsNot Nothing Then Select Case node.Kind Case SyntaxKind.FunctionBlock, SyntaxKind.SubBlock Return AsInterfaceMember(DirectCast(node, MethodBlockSyntax).BlockStatement) Case SyntaxKind.FunctionStatement, SyntaxKind.SubStatement Return Isolate(node, Function(d) DirectCast(d, MethodStatementSyntax).WithModifiers(Nothing)) Case SyntaxKind.PropertyBlock Return AsInterfaceMember(DirectCast(node, PropertyBlockSyntax).PropertyStatement) Case SyntaxKind.PropertyStatement Return Isolate( node, Function(d) Dim propertyStatement = DirectCast(d, PropertyStatementSyntax) Dim mods = SyntaxFactory.TokenList(propertyStatement.Modifiers.Where(Function(tk) tk.IsKind(SyntaxKind.ReadOnlyKeyword) Or tk.IsKind(SyntaxKind.DefaultKeyword))) Return propertyStatement.WithModifiers(mods) End Function) Case SyntaxKind.EventBlock Return AsInterfaceMember(DirectCast(node, EventBlockSyntax).EventStatement) Case SyntaxKind.EventStatement Return Isolate(node, Function(d) DirectCast(d, EventStatementSyntax).WithModifiers(Nothing).WithCustomKeyword(Nothing)) End Select End If Return Nothing End Function Public Overrides Function EnumDeclaration( name As String, Optional accessibility As Accessibility = Nothing, Optional modifiers As DeclarationModifiers = Nothing, Optional members As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Return EnumDeclaration(name, Nothing, accessibility, modifiers, members) End Function Friend Overrides Function EnumDeclaration(name As String, underlyingType As SyntaxNode, Optional accessibility As Accessibility = Accessibility.NotApplicable, Optional modifiers As DeclarationModifiers = Nothing, Optional members As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Dim underlyingTypeClause = If(underlyingType Is Nothing, Nothing, SyntaxFactory.SimpleAsClause(DirectCast(underlyingType, TypeSyntax))) Return SyntaxFactory.EnumBlock( enumStatement:=SyntaxFactory.EnumStatement( attributeLists:=Nothing, modifiers:=GetModifierList(accessibility, modifiers And GetAllowedModifiers(SyntaxKind.EnumStatement), declaration:=Nothing, DeclarationKind.Enum), identifier:=name.ToIdentifierToken(), underlyingType:=underlyingTypeClause), members:=AsEnumMembers(members)) End Function Public Overrides Function EnumMember(name As String, Optional expression As SyntaxNode = Nothing) As SyntaxNode Return SyntaxFactory.EnumMemberDeclaration( attributeLists:=Nothing, identifier:=name.ToIdentifierToken(), initializer:=If(expression IsNot Nothing, SyntaxFactory.EqualsValue(DirectCast(expression, ExpressionSyntax)), Nothing)) End Function Private Function AsEnumMembers(nodes As IEnumerable(Of SyntaxNode)) As SyntaxList(Of StatementSyntax) If nodes IsNot Nothing Then Return SyntaxFactory.List(nodes.Select(AddressOf AsEnumMember).Where(Function(n) n IsNot Nothing)) Else Return Nothing End If End Function Private Function AsEnumMember(node As SyntaxNode) As StatementSyntax Select Case node.Kind Case SyntaxKind.IdentifierName Dim id = DirectCast(node, IdentifierNameSyntax) Return DirectCast(EnumMember(id.Identifier.ValueText), EnumMemberDeclarationSyntax) Case SyntaxKind.FieldDeclaration Dim fd = DirectCast(node, FieldDeclarationSyntax) If fd.Declarators.Count = 1 Then Dim vd = fd.Declarators(0) If vd.Initializer IsNot Nothing AndAlso vd.Names.Count = 1 Then Return DirectCast(EnumMember(vd.Names(0).Identifier.ValueText, vd.Initializer.Value), EnumMemberDeclarationSyntax) End If End If End Select Return TryCast(node, EnumMemberDeclarationSyntax) End Function Public Overrides Function DelegateDeclaration( name As String, Optional parameters As IEnumerable(Of SyntaxNode) = Nothing, Optional typeParameters As IEnumerable(Of String) = Nothing, Optional returnType As SyntaxNode = Nothing, Optional accessibility As Accessibility = Accessibility.NotApplicable, Optional modifiers As DeclarationModifiers = Nothing) As SyntaxNode Dim kind = If(returnType Is Nothing, SyntaxKind.DelegateSubStatement, SyntaxKind.DelegateFunctionStatement) Return SyntaxFactory.DelegateStatement( kind:=kind, attributeLists:=Nothing, modifiers:=GetModifierList(accessibility, modifiers And GetAllowedModifiers(kind), declaration:=Nothing, DeclarationKind.Delegate), subOrFunctionKeyword:=If(kind = SyntaxKind.DelegateSubStatement, SyntaxFactory.Token(SyntaxKind.SubKeyword), SyntaxFactory.Token(SyntaxKind.FunctionKeyword)), identifier:=name.ToIdentifierToken(), typeParameterList:=GetTypeParameters(typeParameters), parameterList:=GetParameterList(parameters), asClause:=If(kind = SyntaxKind.DelegateFunctionStatement, SyntaxFactory.SimpleAsClause(DirectCast(returnType, TypeSyntax)), Nothing)) End Function Public Overrides Function CompilationUnit(declarations As IEnumerable(Of SyntaxNode)) As SyntaxNode Return SyntaxFactory.CompilationUnit().WithImports(AsImports(declarations)).WithMembers(AsNamespaceMembers(declarations)) End Function Private Function AsImports(declarations As IEnumerable(Of SyntaxNode)) As SyntaxList(Of ImportsStatementSyntax) Return If(declarations Is Nothing, Nothing, SyntaxFactory.List(declarations.Select(AddressOf AsNamespaceImport).OfType(Of ImportsStatementSyntax)())) End Function Private Function AsNamespaceImport(node As SyntaxNode) As SyntaxNode Dim name = TryCast(node, NameSyntax) If name IsNot Nothing Then Return Me.NamespaceImportDeclaration(name) End If Return TryCast(node, ImportsStatementSyntax) End Function Private Shared Function AsNamespaceMembers(declarations As IEnumerable(Of SyntaxNode)) As SyntaxList(Of StatementSyntax) Return If(declarations Is Nothing, Nothing, SyntaxFactory.List(declarations.OfType(Of StatementSyntax)().Where(Function(s) Not TypeOf s Is ImportsStatementSyntax))) End Function Public Overrides Function NamespaceImportDeclaration(name As SyntaxNode) As SyntaxNode Return SyntaxFactory.ImportsStatement(SyntaxFactory.SingletonSeparatedList(Of ImportsClauseSyntax)(SyntaxFactory.SimpleImportsClause(DirectCast(name, NameSyntax)))) End Function Public Overrides Function AliasImportDeclaration(aliasIdentifierName As String, name As SyntaxNode) As SyntaxNode If TypeOf name Is NameSyntax Then Return SyntaxFactory.ImportsStatement(SyntaxFactory.SeparatedList(Of ImportsClauseSyntax).Add( SyntaxFactory.SimpleImportsClause( SyntaxFactory.ImportAliasClause(aliasIdentifierName), CType(name, NameSyntax)))) End If Throw New ArgumentException("name is not a NameSyntax.", NameOf(name)) End Function Public Overrides Function NamespaceDeclaration(name As SyntaxNode, nestedDeclarations As IEnumerable(Of SyntaxNode)) As SyntaxNode Dim imps As IEnumerable(Of StatementSyntax) = AsImports(nestedDeclarations) Dim members As IEnumerable(Of StatementSyntax) = AsNamespaceMembers(nestedDeclarations) ' put imports at start Dim statements = imps.Concat(members) Return SyntaxFactory.NamespaceBlock( SyntaxFactory.NamespaceStatement(DirectCast(name, NameSyntax)), members:=SyntaxFactory.List(statements)) End Function Public Overrides Function Attribute(name As SyntaxNode, Optional attributeArguments As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Dim attr = SyntaxFactory.Attribute( target:=Nothing, name:=DirectCast(name, TypeSyntax), argumentList:=AsArgumentList(attributeArguments)) Return AsAttributeList(attr) End Function Private Function AsArgumentList(arguments As IEnumerable(Of SyntaxNode)) As ArgumentListSyntax If arguments IsNot Nothing Then Return SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList(arguments.Select(AddressOf AsArgument))) Else Return Nothing End If End Function Public Overrides Function AttributeArgument(name As String, expression As SyntaxNode) As SyntaxNode Return Argument(name, RefKind.None, expression) End Function Public Overrides Function ClearTrivia(Of TNode As SyntaxNode)(node As TNode) As TNode If node IsNot Nothing Then Return node.WithLeadingTrivia(SyntaxFactory.ElasticMarker).WithTrailingTrivia(SyntaxFactory.ElasticMarker) Else Return Nothing End If End Function Private Function AsAttributeLists(attributes As IEnumerable(Of SyntaxNode)) As SyntaxList(Of AttributeListSyntax) If attributes IsNot Nothing Then Return SyntaxFactory.List(attributes.Select(AddressOf AsAttributeList)) Else Return Nothing End If End Function Private Function AsAttributeList(node As SyntaxNode) As AttributeListSyntax Dim attr = TryCast(node, AttributeSyntax) If attr IsNot Nothing Then Return SyntaxFactory.AttributeList(SyntaxFactory.SingletonSeparatedList(WithNoTarget(attr))) Else Return WithNoTargets(DirectCast(node, AttributeListSyntax)) End If End Function Private Overloads Function WithNoTargets(attrs As AttributeListSyntax) As AttributeListSyntax If (attrs.Attributes.Any(Function(a) a.Target IsNot Nothing)) Then Return attrs.WithAttributes(SyntaxFactory.SeparatedList(attrs.Attributes.Select(AddressOf WithAssemblyTarget))) Else Return attrs End If End Function Private Shared Function WithNoTarget(attr As AttributeSyntax) As AttributeSyntax Return attr.WithTarget(Nothing) End Function Friend Overrides Function GetTypeInheritance(declaration As SyntaxNode) As ImmutableArray(Of SyntaxNode) Dim typeDecl = TryCast(declaration, TypeBlockSyntax) If typeDecl Is Nothing Then Return ImmutableArray(Of SyntaxNode).Empty End If Dim builder = ArrayBuilder(Of SyntaxNode).GetInstance() builder.AddRange(typeDecl.Inherits) builder.AddRange(typeDecl.Implements) Return builder.ToImmutableAndFree() End Function Public Overrides Function GetAttributes(declaration As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Return Me.Flatten(declaration.GetAttributeLists()) End Function Public Overrides Function InsertAttributes(declaration As SyntaxNode, index As Integer, attributes As IEnumerable(Of SyntaxNode)) As SyntaxNode Return Isolate(declaration, Function(d) InsertAttributesInternal(d, index, attributes)) End Function Private Function InsertAttributesInternal(declaration As SyntaxNode, index As Integer, attributes As IEnumerable(Of SyntaxNode)) As SyntaxNode Dim newAttributes = AsAttributeLists(attributes) Dim existingAttributes = Me.GetAttributes(declaration) If index >= 0 AndAlso index < existingAttributes.Count Then Return Me.InsertNodesBefore(declaration, existingAttributes(index), newAttributes) ElseIf existingAttributes.Count > 0 Then Return Me.InsertNodesAfter(declaration, existingAttributes(existingAttributes.Count - 1), newAttributes) Else Dim lists = GetAttributeLists(declaration) Return Me.WithAttributeLists(declaration, lists.AddRange(AsAttributeLists(attributes))) End If End Function Private Shared Function HasAssemblyTarget(attr As AttributeSyntax) As Boolean Return attr.Target IsNot Nothing AndAlso attr.Target.AttributeModifier.IsKind(SyntaxKind.AssemblyKeyword) End Function Private Overloads Function WithAssemblyTargets(attrs As AttributeListSyntax) As AttributeListSyntax If attrs.Attributes.Any(Function(a) Not HasAssemblyTarget(a)) Then Return attrs.WithAttributes(SyntaxFactory.SeparatedList(attrs.Attributes.Select(AddressOf WithAssemblyTarget))) Else Return attrs End If End Function Private Overloads Function WithAssemblyTarget(attr As AttributeSyntax) As AttributeSyntax If Not HasAssemblyTarget(attr) Then Return attr.WithTarget(SyntaxFactory.AttributeTarget(SyntaxFactory.Token(SyntaxKind.AssemblyKeyword))) Else Return attr End If End Function Public Overrides Function GetReturnAttributes(declaration As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Return Me.Flatten(GetReturnAttributeLists(declaration)) End Function Public Overrides Function InsertReturnAttributes(declaration As SyntaxNode, index As Integer, attributes As IEnumerable(Of SyntaxNode)) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.FunctionBlock, SyntaxKind.FunctionStatement, SyntaxKind.DelegateFunctionStatement Return Isolate(declaration, Function(d) InsertReturnAttributesInternal(d, index, attributes)) Case Else Return declaration End Select End Function Private Function InsertReturnAttributesInternal(declaration As SyntaxNode, index As Integer, attributes As IEnumerable(Of SyntaxNode)) As SyntaxNode Dim newAttributes = AsAttributeLists(attributes) Dim existingReturnAttributes = Me.GetReturnAttributes(declaration) If index >= 0 AndAlso index < existingReturnAttributes.Count Then Return Me.InsertNodesBefore(declaration, existingReturnAttributes(index), newAttributes) ElseIf existingReturnAttributes.Count > 0 Then Return Me.InsertNodesAfter(declaration, existingReturnAttributes(existingReturnAttributes.Count - 1), newAttributes) Else Dim lists = GetReturnAttributeLists(declaration) Dim newLists = lists.AddRange(newAttributes) Return Me.WithReturnAttributeLists(declaration, newLists) End If End Function Private Shared Function GetReturnAttributeLists(declaration As SyntaxNode) As SyntaxList(Of AttributeListSyntax) Dim asClause = GetAsClause(declaration) If asClause IsNot Nothing Then Select Case declaration.Kind() Case SyntaxKind.FunctionBlock, SyntaxKind.FunctionStatement, SyntaxKind.DelegateFunctionStatement Return asClause.Attributes End Select End If Return Nothing End Function Private Function WithReturnAttributeLists(declaration As SyntaxNode, lists As IEnumerable(Of AttributeListSyntax)) As SyntaxNode If declaration Is Nothing Then Return Nothing End If Select Case declaration.Kind() Case SyntaxKind.FunctionBlock Dim fb = DirectCast(declaration, MethodBlockSyntax) Dim asClause = DirectCast(WithReturnAttributeLists(GetAsClause(declaration), lists), SimpleAsClauseSyntax) Return fb.WithSubOrFunctionStatement(fb.SubOrFunctionStatement.WithAsClause(asClause)) Case SyntaxKind.FunctionStatement Dim ms = DirectCast(declaration, MethodStatementSyntax) Dim asClause = DirectCast(WithReturnAttributeLists(GetAsClause(declaration), lists), SimpleAsClauseSyntax) Return ms.WithAsClause(asClause) Case SyntaxKind.DelegateFunctionStatement Dim df = DirectCast(declaration, DelegateStatementSyntax) Dim asClause = DirectCast(WithReturnAttributeLists(GetAsClause(declaration), lists), SimpleAsClauseSyntax) Return df.WithAsClause(asClause) Case SyntaxKind.SimpleAsClause Return DirectCast(declaration, SimpleAsClauseSyntax).WithAttributeLists(SyntaxFactory.List(lists)) Case Else Return Nothing End Select End Function Private Function WithAttributeLists(node As SyntaxNode, lists As IEnumerable(Of AttributeListSyntax)) As SyntaxNode Dim arg = SyntaxFactory.List(lists) Select Case node.Kind Case SyntaxKind.CompilationUnit 'convert to assembly target arg = SyntaxFactory.List(lists.Select(Function(lst) Me.WithAssemblyTargets(lst))) ' add as single attributes statement Return DirectCast(node, CompilationUnitSyntax).WithAttributes(SyntaxFactory.SingletonList(SyntaxFactory.AttributesStatement(arg))) Case SyntaxKind.ClassBlock Return DirectCast(node, ClassBlockSyntax).WithClassStatement(DirectCast(node, ClassBlockSyntax).ClassStatement.WithAttributeLists(arg)) Case SyntaxKind.ClassStatement Return DirectCast(node, ClassStatementSyntax).WithAttributeLists(arg) Case SyntaxKind.StructureBlock Return DirectCast(node, StructureBlockSyntax).WithStructureStatement(DirectCast(node, StructureBlockSyntax).StructureStatement.WithAttributeLists(arg)) Case SyntaxKind.StructureStatement Return DirectCast(node, StructureStatementSyntax).WithAttributeLists(arg) Case SyntaxKind.InterfaceBlock Return DirectCast(node, InterfaceBlockSyntax).WithInterfaceStatement(DirectCast(node, InterfaceBlockSyntax).InterfaceStatement.WithAttributeLists(arg)) Case SyntaxKind.InterfaceStatement Return DirectCast(node, InterfaceStatementSyntax).WithAttributeLists(arg) Case SyntaxKind.EnumBlock Return DirectCast(node, EnumBlockSyntax).WithEnumStatement(DirectCast(node, EnumBlockSyntax).EnumStatement.WithAttributeLists(arg)) Case SyntaxKind.EnumStatement Return DirectCast(node, EnumStatementSyntax).WithAttributeLists(arg) Case SyntaxKind.EnumMemberDeclaration Return DirectCast(node, EnumMemberDeclarationSyntax).WithAttributeLists(arg) Case SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement Return DirectCast(node, DelegateStatementSyntax).WithAttributeLists(arg) Case SyntaxKind.FieldDeclaration Return DirectCast(node, FieldDeclarationSyntax).WithAttributeLists(arg) Case SyntaxKind.FunctionBlock, SyntaxKind.SubBlock Return DirectCast(node, MethodBlockSyntax).WithSubOrFunctionStatement(DirectCast(node, MethodBlockSyntax).SubOrFunctionStatement.WithAttributeLists(arg)) Case SyntaxKind.FunctionStatement, SyntaxKind.SubStatement Return DirectCast(node, MethodStatementSyntax).WithAttributeLists(arg) Case SyntaxKind.ConstructorBlock Return DirectCast(node, ConstructorBlockSyntax).WithSubNewStatement(DirectCast(node, ConstructorBlockSyntax).SubNewStatement.WithAttributeLists(arg)) Case SyntaxKind.SubNewStatement Return DirectCast(node, SubNewStatementSyntax).WithAttributeLists(arg) Case SyntaxKind.Parameter Return DirectCast(node, ParameterSyntax).WithAttributeLists(arg) Case SyntaxKind.PropertyBlock Return DirectCast(node, PropertyBlockSyntax).WithPropertyStatement(DirectCast(node, PropertyBlockSyntax).PropertyStatement.WithAttributeLists(arg)) Case SyntaxKind.PropertyStatement Return DirectCast(node, PropertyStatementSyntax).WithAttributeLists(arg) Case SyntaxKind.OperatorBlock Return DirectCast(node, OperatorBlockSyntax).WithOperatorStatement(DirectCast(node, OperatorBlockSyntax).OperatorStatement.WithAttributeLists(arg)) Case SyntaxKind.OperatorStatement Return DirectCast(node, OperatorStatementSyntax).WithAttributeLists(arg) Case SyntaxKind.EventBlock Return DirectCast(node, EventBlockSyntax).WithEventStatement(DirectCast(node, EventBlockSyntax).EventStatement.WithAttributeLists(arg)) Case SyntaxKind.EventStatement Return DirectCast(node, EventStatementSyntax).WithAttributeLists(arg) Case SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock, SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RaiseEventAccessorBlock Return DirectCast(node, AccessorBlockSyntax).WithAccessorStatement(DirectCast(node, AccessorBlockSyntax).AccessorStatement.WithAttributeLists(arg)) Case SyntaxKind.GetAccessorStatement, SyntaxKind.SetAccessorStatement, SyntaxKind.AddHandlerAccessorStatement, SyntaxKind.RemoveHandlerAccessorStatement, SyntaxKind.RaiseEventAccessorStatement Return DirectCast(node, AccessorStatementSyntax).WithAttributeLists(arg) Case Else Return node End Select End Function Public Overrides Function GetDeclarationKind(declaration As SyntaxNode) As DeclarationKind Return SyntaxFacts.GetDeclarationKind(declaration) End Function Private Shared Function GetDeclarationCount(node As SyntaxNode) As Integer Return VisualBasicSyntaxFacts.GetDeclarationCount(node) End Function Private Shared Function IsChildOf(node As SyntaxNode, kind As SyntaxKind) As Boolean Return VisualBasicSyntaxFacts.IsChildOf(node, kind) End Function Private Shared Function IsChildOfVariableDeclaration(node As SyntaxNode) As Boolean Return VisualBasicSyntaxFacts.IsChildOfVariableDeclaration(node) End Function Private Function Isolate(declaration As SyntaxNode, editor As Func(Of SyntaxNode, SyntaxNode)) As SyntaxNode Dim isolated = AsIsolatedDeclaration(declaration) Return PreserveTrivia(isolated, editor) End Function Private Function GetFullDeclaration(declaration As SyntaxNode) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.ModifiedIdentifier If IsChildOf(declaration, SyntaxKind.VariableDeclarator) Then Return GetFullDeclaration(declaration.Parent) End If Case SyntaxKind.VariableDeclarator If IsChildOfVariableDeclaration(declaration) Then Return declaration.Parent End If Case SyntaxKind.Attribute If declaration.Parent IsNot Nothing Then Return declaration.Parent End If Case SyntaxKind.SimpleImportsClause, SyntaxKind.XmlNamespaceImportsClause If declaration.Parent IsNot Nothing Then Return declaration.Parent End If End Select Return declaration End Function Private Function AsIsolatedDeclaration(declaration As SyntaxNode) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.ModifiedIdentifier Dim full = GetFullDeclaration(declaration) If full IsNot declaration Then Return WithSingleVariable(full, DirectCast(declaration, ModifiedIdentifierSyntax)) End If Case SyntaxKind.Attribute Dim list = TryCast(declaration.Parent, AttributeListSyntax) If list IsNot Nothing Then Return list.WithAttributes(SyntaxFactory.SingletonSeparatedList(DirectCast(declaration, AttributeSyntax))) End If Case SyntaxKind.SimpleImportsClause, SyntaxKind.XmlNamespaceImportsClause Dim stmt = TryCast(declaration.Parent, ImportsStatementSyntax) If stmt IsNot Nothing Then Return stmt.WithImportsClauses(SyntaxFactory.SingletonSeparatedList(DirectCast(declaration, ImportsClauseSyntax))) End If End Select Return declaration End Function Private Shared Function WithSingleVariable(declaration As SyntaxNode, variable As ModifiedIdentifierSyntax) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.FieldDeclaration Dim fd = DirectCast(declaration, FieldDeclarationSyntax) Return ReplaceWithTrivia(declaration, fd.Declarators(0), fd.Declarators(0).WithNames(SyntaxFactory.SingletonSeparatedList(variable))) Case SyntaxKind.LocalDeclarationStatement Dim ld = DirectCast(declaration, LocalDeclarationStatementSyntax) Return ReplaceWithTrivia(declaration, ld.Declarators(0), ld.Declarators(0).WithNames(SyntaxFactory.SingletonSeparatedList(variable))) Case SyntaxKind.VariableDeclarator Dim vd = DirectCast(declaration, VariableDeclaratorSyntax) Return vd.WithNames(SyntaxFactory.SingletonSeparatedList(variable)) Case Else Return declaration End Select End Function Public Overrides Function GetName(declaration As SyntaxNode) As String Select Case declaration.Kind Case SyntaxKind.ClassBlock Return DirectCast(declaration, ClassBlockSyntax).BlockStatement.Identifier.ValueText Case SyntaxKind.StructureBlock Return DirectCast(declaration, StructureBlockSyntax).BlockStatement.Identifier.ValueText Case SyntaxKind.InterfaceBlock Return DirectCast(declaration, InterfaceBlockSyntax).BlockStatement.Identifier.ValueText Case SyntaxKind.EnumBlock Return DirectCast(declaration, EnumBlockSyntax).EnumStatement.Identifier.ValueText Case SyntaxKind.EnumMemberDeclaration Return DirectCast(declaration, EnumMemberDeclarationSyntax).Identifier.ValueText Case SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement Return DirectCast(declaration, DelegateStatementSyntax).Identifier.ValueText Case SyntaxKind.FunctionBlock, SyntaxKind.SubBlock Return DirectCast(declaration, MethodBlockSyntax).SubOrFunctionStatement.Identifier.ValueText Case SyntaxKind.FunctionStatement, SyntaxKind.SubStatement Return DirectCast(declaration, MethodStatementSyntax).Identifier.ValueText Case SyntaxKind.PropertyBlock Return DirectCast(declaration, PropertyBlockSyntax).PropertyStatement.Identifier.ValueText Case SyntaxKind.PropertyStatement Return DirectCast(declaration, PropertyStatementSyntax).Identifier.ValueText Case SyntaxKind.EventBlock Return DirectCast(declaration, EventBlockSyntax).EventStatement.Identifier.ValueText Case SyntaxKind.EventStatement Return DirectCast(declaration, EventStatementSyntax).Identifier.ValueText Case SyntaxKind.EventStatement Return DirectCast(declaration, EventStatementSyntax).Identifier.ValueText Case SyntaxKind.Parameter Return DirectCast(declaration, ParameterSyntax).Identifier.Identifier.ValueText Case SyntaxKind.NamespaceBlock Return DirectCast(declaration, NamespaceBlockSyntax).NamespaceStatement.Name.ToString() Case SyntaxKind.FieldDeclaration Dim fd = DirectCast(declaration, FieldDeclarationSyntax) If GetDeclarationCount(fd) = 1 Then Return fd.Declarators(0).Names(0).Identifier.ValueText End If Case SyntaxKind.LocalDeclarationStatement Dim ld = DirectCast(declaration, LocalDeclarationStatementSyntax) If GetDeclarationCount(ld) = 1 Then Return ld.Declarators(0).Names(0).Identifier.ValueText End If Case SyntaxKind.VariableDeclarator Dim vd = DirectCast(declaration, VariableDeclaratorSyntax) If vd.Names.Count = 1 Then Return vd.Names(0).Identifier.ValueText End If Case SyntaxKind.ModifiedIdentifier Return DirectCast(declaration, ModifiedIdentifierSyntax).Identifier.ValueText Case SyntaxKind.Attribute Return DirectCast(declaration, AttributeSyntax).Name.ToString() Case SyntaxKind.AttributeList Dim list = DirectCast(declaration, AttributeListSyntax) If list.Attributes.Count = 1 Then Return list.Attributes(0).Name.ToString() End If Case SyntaxKind.ImportsStatement Dim stmt = DirectCast(declaration, ImportsStatementSyntax) If stmt.ImportsClauses.Count = 1 Then Return GetName(stmt.ImportsClauses(0)) End If Case SyntaxKind.SimpleImportsClause Return DirectCast(declaration, SimpleImportsClauseSyntax).Name.ToString() End Select Return String.Empty End Function Public Overrides Function WithName(declaration As SyntaxNode, name As String) As SyntaxNode Return Isolate(declaration, Function(d) WithNameInternal(d, name)) End Function Private Function WithNameInternal(declaration As SyntaxNode, name As String) As SyntaxNode Dim id = name.ToIdentifierToken() Select Case declaration.Kind Case SyntaxKind.ClassBlock Return ReplaceWithTrivia(declaration, DirectCast(declaration, ClassBlockSyntax).BlockStatement.Identifier, id) Case SyntaxKind.StructureBlock Return ReplaceWithTrivia(declaration, DirectCast(declaration, StructureBlockSyntax).BlockStatement.Identifier, id) Case SyntaxKind.InterfaceBlock Return ReplaceWithTrivia(declaration, DirectCast(declaration, InterfaceBlockSyntax).BlockStatement.Identifier, id) Case SyntaxKind.EnumBlock Return ReplaceWithTrivia(declaration, DirectCast(declaration, EnumBlockSyntax).EnumStatement.Identifier, id) Case SyntaxKind.EnumMemberDeclaration Return ReplaceWithTrivia(declaration, DirectCast(declaration, EnumMemberDeclarationSyntax).Identifier, id) Case SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement Return ReplaceWithTrivia(declaration, DirectCast(declaration, DelegateStatementSyntax).Identifier, id) Case SyntaxKind.FunctionBlock, SyntaxKind.SubBlock Return ReplaceWithTrivia(declaration, DirectCast(declaration, MethodBlockSyntax).SubOrFunctionStatement.Identifier, id) Case SyntaxKind.FunctionStatement, SyntaxKind.SubStatement Return ReplaceWithTrivia(declaration, DirectCast(declaration, MethodStatementSyntax).Identifier, id) Case SyntaxKind.PropertyBlock Return ReplaceWithTrivia(declaration, DirectCast(declaration, PropertyBlockSyntax).PropertyStatement.Identifier, id) Case SyntaxKind.PropertyStatement Return ReplaceWithTrivia(declaration, DirectCast(declaration, PropertyStatementSyntax).Identifier, id) Case SyntaxKind.EventBlock Return ReplaceWithTrivia(declaration, DirectCast(declaration, EventBlockSyntax).EventStatement.Identifier, id) Case SyntaxKind.EventStatement Return ReplaceWithTrivia(declaration, DirectCast(declaration, EventStatementSyntax).Identifier, id) Case SyntaxKind.EventStatement Return ReplaceWithTrivia(declaration, DirectCast(declaration, EventStatementSyntax).Identifier, id) Case SyntaxKind.Parameter Return ReplaceWithTrivia(declaration, DirectCast(declaration, ParameterSyntax).Identifier.Identifier, id) Case SyntaxKind.NamespaceBlock Return ReplaceWithTrivia(declaration, DirectCast(declaration, NamespaceBlockSyntax).NamespaceStatement.Name, Me.DottedName(name)) Case SyntaxKind.LocalDeclarationStatement Dim ld = DirectCast(declaration, LocalDeclarationStatementSyntax) If ld.Declarators.Count = 1 AndAlso ld.Declarators(0).Names.Count = 1 Then Return ReplaceWithTrivia(declaration, ld.Declarators(0).Names(0).Identifier, id) End If Case SyntaxKind.FieldDeclaration Dim fd = DirectCast(declaration, FieldDeclarationSyntax) If fd.Declarators.Count = 1 AndAlso fd.Declarators(0).Names.Count = 1 Then Return ReplaceWithTrivia(declaration, fd.Declarators(0).Names(0).Identifier, id) End If Case SyntaxKind.Attribute Return ReplaceWithTrivia(declaration, DirectCast(declaration, AttributeSyntax).Name, Me.DottedName(name)) Case SyntaxKind.AttributeList Dim al = DirectCast(declaration, AttributeListSyntax) If al.Attributes.Count = 1 Then Return ReplaceWithTrivia(declaration, al.Attributes(0).Name, Me.DottedName(name)) End If Case SyntaxKind.ImportsStatement Dim stmt = DirectCast(declaration, ImportsStatementSyntax) If stmt.ImportsClauses.Count = 1 Then Dim clause = stmt.ImportsClauses(0) Select Case clause.Kind Case SyntaxKind.SimpleImportsClause Return ReplaceWithTrivia(declaration, DirectCast(clause, SimpleImportsClauseSyntax).Name, Me.DottedName(name)) End Select End If End Select Return declaration End Function Public Overrides Function [GetType](declaration As SyntaxNode) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.ModifiedIdentifier Dim vd = TryCast(declaration.Parent, VariableDeclaratorSyntax) If vd IsNot Nothing Then Return [GetType](vd) End If Case Else Dim asClause = GetAsClause(declaration) If asClause IsNot Nothing Then Return asClause.Type End If End Select Return Nothing End Function Public Overrides Function WithType(declaration As SyntaxNode, type As SyntaxNode) As SyntaxNode Return Isolate(declaration, Function(d) WithTypeInternal(d, type)) End Function Private Function WithTypeInternal(declaration As SyntaxNode, type As SyntaxNode) As SyntaxNode If type Is Nothing Then declaration = AsSub(declaration) Else declaration = AsFunction(declaration) End If Dim asClause = GetAsClause(declaration) If asClause IsNot Nothing Then If type IsNot Nothing Then Select Case asClause.Kind Case SyntaxKind.SimpleAsClause asClause = DirectCast(asClause, SimpleAsClauseSyntax).WithType(DirectCast(type, TypeSyntax)) Case SyntaxKind.AsNewClause Dim asNew = DirectCast(asClause, AsNewClauseSyntax) Select Case asNew.NewExpression.Kind Case SyntaxKind.ObjectCreationExpression asClause = asNew.WithNewExpression(DirectCast(asNew.NewExpression, ObjectCreationExpressionSyntax).WithType(DirectCast(type, TypeSyntax))) Case SyntaxKind.ArrayCreationExpression asClause = asNew.WithNewExpression(DirectCast(asNew.NewExpression, ArrayCreationExpressionSyntax).WithType(DirectCast(type, TypeSyntax))) End Select End Select Else asClause = Nothing End If ElseIf type IsNot Nothing Then asClause = SyntaxFactory.SimpleAsClause(DirectCast(type, TypeSyntax)) End If Return WithAsClause(declaration, asClause) End Function Private Shared Function GetAsClause(declaration As SyntaxNode) As AsClauseSyntax Select Case declaration.Kind Case SyntaxKind.DelegateFunctionStatement Return DirectCast(declaration, DelegateStatementSyntax).AsClause Case SyntaxKind.FunctionBlock Return DirectCast(declaration, MethodBlockSyntax).SubOrFunctionStatement.AsClause Case SyntaxKind.FunctionStatement Return DirectCast(declaration, MethodStatementSyntax).AsClause Case SyntaxKind.PropertyBlock Return DirectCast(declaration, PropertyBlockSyntax).PropertyStatement.AsClause Case SyntaxKind.PropertyStatement Return DirectCast(declaration, PropertyStatementSyntax).AsClause Case SyntaxKind.EventBlock Return DirectCast(declaration, EventBlockSyntax).EventStatement.AsClause Case SyntaxKind.EventStatement Return DirectCast(declaration, EventStatementSyntax).AsClause Case SyntaxKind.Parameter Return DirectCast(declaration, ParameterSyntax).AsClause Case SyntaxKind.FieldDeclaration Dim fd = DirectCast(declaration, FieldDeclarationSyntax) If fd.Declarators.Count = 1 Then Return fd.Declarators(0).AsClause End If Case SyntaxKind.LocalDeclarationStatement Dim ld = DirectCast(declaration, LocalDeclarationStatementSyntax) If ld.Declarators.Count = 1 Then Return ld.Declarators(0).AsClause End If Case SyntaxKind.VariableDeclarator Return DirectCast(declaration, VariableDeclaratorSyntax).AsClause Case SyntaxKind.ModifiedIdentifier Dim vd = TryCast(declaration.Parent, VariableDeclaratorSyntax) If vd IsNot Nothing Then Return vd.AsClause End If End Select Return Nothing End Function Private Shared Function WithAsClause(declaration As SyntaxNode, asClause As AsClauseSyntax) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.DelegateFunctionStatement Return DirectCast(declaration, DelegateStatementSyntax).WithAsClause(DirectCast(asClause, SimpleAsClauseSyntax)) Case SyntaxKind.FieldDeclaration Dim fd = DirectCast(declaration, FieldDeclarationSyntax) If fd.Declarators.Count = 1 Then Return ReplaceWithTrivia(declaration, fd.Declarators(0), fd.Declarators(0).WithAsClause(asClause)) End If Case SyntaxKind.FunctionBlock Return DirectCast(declaration, MethodBlockSyntax).WithSubOrFunctionStatement(DirectCast(declaration, MethodBlockSyntax).SubOrFunctionStatement.WithAsClause(DirectCast(asClause, SimpleAsClauseSyntax))) Case SyntaxKind.FunctionStatement Return DirectCast(declaration, MethodStatementSyntax).WithAsClause(DirectCast(asClause, SimpleAsClauseSyntax)) Case SyntaxKind.PropertyBlock Return DirectCast(declaration, PropertyBlockSyntax).WithPropertyStatement(DirectCast(declaration, PropertyBlockSyntax).PropertyStatement.WithAsClause(asClause)) Case SyntaxKind.PropertyStatement Return DirectCast(declaration, PropertyStatementSyntax).WithAsClause(asClause) Case SyntaxKind.EventBlock Return DirectCast(declaration, EventBlockSyntax).WithEventStatement(DirectCast(declaration, EventBlockSyntax).EventStatement.WithAsClause(DirectCast(asClause, SimpleAsClauseSyntax))) Case SyntaxKind.EventStatement Return DirectCast(declaration, EventStatementSyntax).WithAsClause(DirectCast(asClause, SimpleAsClauseSyntax)) Case SyntaxKind.Parameter Return DirectCast(declaration, ParameterSyntax).WithAsClause(DirectCast(asClause, SimpleAsClauseSyntax)) Case SyntaxKind.LocalDeclarationStatement Dim ld = DirectCast(declaration, LocalDeclarationStatementSyntax) If ld.Declarators.Count = 1 Then Return ReplaceWithTrivia(declaration, ld.Declarators(0), ld.Declarators(0).WithAsClause(asClause)) End If Case SyntaxKind.VariableDeclarator Return DirectCast(declaration, VariableDeclaratorSyntax).WithAsClause(asClause) End Select Return declaration End Function Private Function AsFunction(declaration As SyntaxNode) As SyntaxNode Return Isolate(declaration, AddressOf AsFunctionInternal) End Function Private Function AsFunctionInternal(declaration As SyntaxNode) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.SubBlock Dim sb = DirectCast(declaration, MethodBlockSyntax) Return SyntaxFactory.MethodBlock( SyntaxKind.FunctionBlock, DirectCast(AsFunction(sb.BlockStatement), MethodStatementSyntax), sb.Statements, SyntaxFactory.EndBlockStatement( SyntaxKind.EndFunctionStatement, sb.EndBlockStatement.EndKeyword, SyntaxFactory.Token(sb.EndBlockStatement.BlockKeyword.LeadingTrivia, SyntaxKind.FunctionKeyword, sb.EndBlockStatement.BlockKeyword.TrailingTrivia) )) Case SyntaxKind.SubStatement Dim ss = DirectCast(declaration, MethodStatementSyntax) Return SyntaxFactory.MethodStatement( SyntaxKind.FunctionStatement, ss.AttributeLists, ss.Modifiers, SyntaxFactory.Token(ss.DeclarationKeyword.LeadingTrivia, SyntaxKind.FunctionKeyword, ss.DeclarationKeyword.TrailingTrivia), ss.Identifier, ss.TypeParameterList, ss.ParameterList, SyntaxFactory.SimpleAsClause(SyntaxFactory.IdentifierName("Object")), ss.HandlesClause, ss.ImplementsClause) Case SyntaxKind.DelegateSubStatement Dim ds = DirectCast(declaration, DelegateStatementSyntax) Return SyntaxFactory.DelegateStatement( SyntaxKind.DelegateFunctionStatement, ds.AttributeLists, ds.Modifiers, SyntaxFactory.Token(ds.DeclarationKeyword.LeadingTrivia, SyntaxKind.FunctionKeyword, ds.DeclarationKeyword.TrailingTrivia), ds.Identifier, ds.TypeParameterList, ds.ParameterList, SyntaxFactory.SimpleAsClause(SyntaxFactory.IdentifierName("Object"))) Case SyntaxKind.MultiLineSubLambdaExpression Dim ml = DirectCast(declaration, MultiLineLambdaExpressionSyntax) Return SyntaxFactory.MultiLineLambdaExpression( SyntaxKind.MultiLineFunctionLambdaExpression, DirectCast(AsFunction(ml.SubOrFunctionHeader), LambdaHeaderSyntax), ml.Statements, SyntaxFactory.EndBlockStatement( SyntaxKind.EndFunctionStatement, ml.EndSubOrFunctionStatement.EndKeyword, SyntaxFactory.Token(ml.EndSubOrFunctionStatement.BlockKeyword.LeadingTrivia, SyntaxKind.FunctionKeyword, ml.EndSubOrFunctionStatement.BlockKeyword.TrailingTrivia) )) Case SyntaxKind.SingleLineSubLambdaExpression Dim sl = DirectCast(declaration, SingleLineLambdaExpressionSyntax) Return SyntaxFactory.SingleLineLambdaExpression( SyntaxKind.SingleLineFunctionLambdaExpression, DirectCast(AsFunction(sl.SubOrFunctionHeader), LambdaHeaderSyntax), sl.Body) Case SyntaxKind.SubLambdaHeader Dim lh = DirectCast(declaration, LambdaHeaderSyntax) Return SyntaxFactory.LambdaHeader( SyntaxKind.FunctionLambdaHeader, lh.AttributeLists, lh.Modifiers, SyntaxFactory.Token(lh.DeclarationKeyword.LeadingTrivia, SyntaxKind.FunctionKeyword, lh.DeclarationKeyword.TrailingTrivia), lh.ParameterList, asClause:=Nothing) Case SyntaxKind.DeclareSubStatement Dim ds = DirectCast(declaration, DeclareStatementSyntax) Return SyntaxFactory.DeclareStatement( SyntaxKind.DeclareFunctionStatement, ds.AttributeLists, ds.Modifiers, ds.CharsetKeyword, SyntaxFactory.Token(ds.DeclarationKeyword.LeadingTrivia, SyntaxKind.FunctionKeyword, ds.DeclarationKeyword.TrailingTrivia), ds.Identifier, ds.LibraryName, ds.AliasName, ds.ParameterList, SyntaxFactory.SimpleAsClause(SyntaxFactory.IdentifierName("Object"))) Case Else Return declaration End Select End Function Private Function AsSub(declaration As SyntaxNode) As SyntaxNode Return Isolate(declaration, AddressOf AsSubInternal) End Function Private Function AsSubInternal(declaration As SyntaxNode) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.FunctionBlock Dim mb = DirectCast(declaration, MethodBlockSyntax) Return SyntaxFactory.MethodBlock( SyntaxKind.SubBlock, DirectCast(AsSub(mb.BlockStatement), MethodStatementSyntax), mb.Statements, SyntaxFactory.EndBlockStatement( SyntaxKind.EndSubStatement, mb.EndBlockStatement.EndKeyword, SyntaxFactory.Token(mb.EndBlockStatement.BlockKeyword.LeadingTrivia, SyntaxKind.SubKeyword, mb.EndBlockStatement.BlockKeyword.TrailingTrivia) )) Case SyntaxKind.FunctionStatement Dim ms = DirectCast(declaration, MethodStatementSyntax) Return SyntaxFactory.MethodStatement( SyntaxKind.SubStatement, ms.AttributeLists, ms.Modifiers, SyntaxFactory.Token(ms.DeclarationKeyword.LeadingTrivia, SyntaxKind.SubKeyword, ms.DeclarationKeyword.TrailingTrivia), ms.Identifier, ms.TypeParameterList, ms.ParameterList, asClause:=Nothing, handlesClause:=ms.HandlesClause, implementsClause:=ms.ImplementsClause) Case SyntaxKind.DelegateFunctionStatement Dim ds = DirectCast(declaration, DelegateStatementSyntax) Return SyntaxFactory.DelegateStatement( SyntaxKind.DelegateSubStatement, ds.AttributeLists, ds.Modifiers, SyntaxFactory.Token(ds.DeclarationKeyword.LeadingTrivia, SyntaxKind.SubKeyword, ds.DeclarationKeyword.TrailingTrivia), ds.Identifier, ds.TypeParameterList, ds.ParameterList, asClause:=Nothing) Case SyntaxKind.MultiLineFunctionLambdaExpression Dim ml = DirectCast(declaration, MultiLineLambdaExpressionSyntax) Return SyntaxFactory.MultiLineLambdaExpression( SyntaxKind.MultiLineSubLambdaExpression, DirectCast(AsSub(ml.SubOrFunctionHeader), LambdaHeaderSyntax), ml.Statements, SyntaxFactory.EndBlockStatement( SyntaxKind.EndSubStatement, ml.EndSubOrFunctionStatement.EndKeyword, SyntaxFactory.Token(ml.EndSubOrFunctionStatement.BlockKeyword.LeadingTrivia, SyntaxKind.SubKeyword, ml.EndSubOrFunctionStatement.BlockKeyword.TrailingTrivia) )) Case SyntaxKind.SingleLineFunctionLambdaExpression Dim sl = DirectCast(declaration, SingleLineLambdaExpressionSyntax) Return SyntaxFactory.SingleLineLambdaExpression( SyntaxKind.SingleLineSubLambdaExpression, DirectCast(AsSub(sl.SubOrFunctionHeader), LambdaHeaderSyntax), sl.Body) Case SyntaxKind.FunctionLambdaHeader Dim lh = DirectCast(declaration, LambdaHeaderSyntax) Return SyntaxFactory.LambdaHeader( SyntaxKind.SubLambdaHeader, lh.AttributeLists, lh.Modifiers, SyntaxFactory.Token(lh.DeclarationKeyword.LeadingTrivia, SyntaxKind.SubKeyword, lh.DeclarationKeyword.TrailingTrivia), lh.ParameterList, asClause:=Nothing) Case SyntaxKind.DeclareFunctionStatement Dim ds = DirectCast(declaration, DeclareStatementSyntax) Return SyntaxFactory.DeclareStatement( SyntaxKind.DeclareSubStatement, ds.AttributeLists, ds.Modifiers, ds.CharsetKeyword, SyntaxFactory.Token(ds.DeclarationKeyword.LeadingTrivia, SyntaxKind.SubKeyword, ds.DeclarationKeyword.TrailingTrivia), ds.Identifier, ds.LibraryName, ds.AliasName, ds.ParameterList, asClause:=Nothing) Case Else Return declaration End Select End Function Public Overrides Function GetModifiers(declaration As SyntaxNode) As DeclarationModifiers Dim tokens = SyntaxFacts.GetModifierTokens(declaration) Dim acc As Accessibility Dim mods As DeclarationModifiers Dim isDefault As Boolean SyntaxFacts.GetAccessibilityAndModifiers(tokens, acc, mods, isDefault) Return mods End Function Public Overrides Function WithModifiers(declaration As SyntaxNode, modifiers As DeclarationModifiers) As SyntaxNode Return Isolate(declaration, Function(d) Me.WithModifiersInternal(d, modifiers)) End Function Private Function WithModifiersInternal(declaration As SyntaxNode, modifiers As DeclarationModifiers) As SyntaxNode Dim tokens = SyntaxFacts.GetModifierTokens(declaration) Dim acc As Accessibility Dim currentMods As DeclarationModifiers Dim isDefault As Boolean SyntaxFacts.GetAccessibilityAndModifiers(tokens, acc, currentMods, isDefault) If currentMods <> modifiers Then Dim newTokens = GetModifierList(acc, modifiers And GetAllowedModifiers(declaration.Kind), declaration, GetDeclarationKind(declaration), isDefault) Return WithModifierTokens(declaration, Merge(tokens, newTokens)) Else Return declaration End If End Function Private Function WithModifierTokens(declaration As SyntaxNode, tokens As SyntaxTokenList) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.ClassBlock Return DirectCast(declaration, ClassBlockSyntax).WithClassStatement(DirectCast(declaration, ClassBlockSyntax).ClassStatement.WithModifiers(tokens)) Case SyntaxKind.ClassStatement Return DirectCast(declaration, ClassStatementSyntax).WithModifiers(tokens) Case SyntaxKind.StructureBlock Return DirectCast(declaration, StructureBlockSyntax).WithStructureStatement(DirectCast(declaration, StructureBlockSyntax).StructureStatement.WithModifiers(tokens)) Case SyntaxKind.StructureStatement Return DirectCast(declaration, StructureStatementSyntax).WithModifiers(tokens) Case SyntaxKind.InterfaceBlock Return DirectCast(declaration, InterfaceBlockSyntax).WithInterfaceStatement(DirectCast(declaration, InterfaceBlockSyntax).InterfaceStatement.WithModifiers(tokens)) Case SyntaxKind.InterfaceStatement Return DirectCast(declaration, InterfaceStatementSyntax).WithModifiers(tokens) Case SyntaxKind.EnumBlock Return DirectCast(declaration, EnumBlockSyntax).WithEnumStatement(DirectCast(declaration, EnumBlockSyntax).EnumStatement.WithModifiers(tokens)) Case SyntaxKind.EnumStatement Return DirectCast(declaration, EnumStatementSyntax).WithModifiers(tokens) Case SyntaxKind.ModuleBlock Return DirectCast(declaration, ModuleBlockSyntax).WithModuleStatement(DirectCast(declaration, ModuleBlockSyntax).ModuleStatement.WithModifiers(tokens)) Case SyntaxKind.ModuleStatement Return DirectCast(declaration, ModuleStatementSyntax).WithModifiers(tokens) Case SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement Return DirectCast(declaration, DelegateStatementSyntax).WithModifiers(tokens) Case SyntaxKind.FieldDeclaration Return DirectCast(declaration, FieldDeclarationSyntax).WithModifiers(tokens) Case SyntaxKind.FunctionBlock, SyntaxKind.SubBlock Return DirectCast(declaration, MethodBlockSyntax).WithSubOrFunctionStatement(DirectCast(declaration, MethodBlockSyntax).SubOrFunctionStatement.WithModifiers(tokens)) Case SyntaxKind.ConstructorBlock Return DirectCast(declaration, ConstructorBlockSyntax).WithSubNewStatement(DirectCast(declaration, ConstructorBlockSyntax).SubNewStatement.WithModifiers(tokens)) Case SyntaxKind.FunctionStatement, SyntaxKind.SubStatement Return DirectCast(declaration, MethodStatementSyntax).WithModifiers(tokens) Case SyntaxKind.SubNewStatement Return DirectCast(declaration, SubNewStatementSyntax).WithModifiers(tokens) Case SyntaxKind.PropertyBlock Return DirectCast(declaration, PropertyBlockSyntax).WithPropertyStatement(DirectCast(declaration, PropertyBlockSyntax).PropertyStatement.WithModifiers(tokens)) Case SyntaxKind.PropertyStatement Return DirectCast(declaration, PropertyStatementSyntax).WithModifiers(tokens) Case SyntaxKind.OperatorBlock Return DirectCast(declaration, OperatorBlockSyntax).WithOperatorStatement(DirectCast(declaration, OperatorBlockSyntax).OperatorStatement.WithModifiers(tokens)) Case SyntaxKind.OperatorStatement Return DirectCast(declaration, OperatorStatementSyntax).WithModifiers(tokens) Case SyntaxKind.EventBlock Return DirectCast(declaration, EventBlockSyntax).WithEventStatement(DirectCast(declaration, EventBlockSyntax).EventStatement.WithModifiers(tokens)) Case SyntaxKind.EventStatement Return DirectCast(declaration, EventStatementSyntax).WithModifiers(tokens) Case SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock, SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RaiseEventAccessorBlock Return DirectCast(declaration, AccessorBlockSyntax).WithAccessorStatement( DirectCast(Me.WithModifierTokens(DirectCast(declaration, AccessorBlockSyntax).AccessorStatement, tokens), AccessorStatementSyntax)) Case SyntaxKind.GetAccessorStatement, SyntaxKind.SetAccessorStatement, SyntaxKind.AddHandlerAccessorStatement, SyntaxKind.RemoveHandlerAccessorStatement, SyntaxKind.RaiseEventAccessorStatement Return DirectCast(declaration, AccessorStatementSyntax).WithModifiers(tokens) Case Else Return declaration End Select End Function Public Overrides Function GetAccessibility(declaration As SyntaxNode) As Accessibility Return SyntaxFacts.GetAccessibility(declaration) End Function Public Overrides Function WithAccessibility(declaration As SyntaxNode, accessibility As Accessibility) As SyntaxNode If Not SyntaxFacts.CanHaveAccessibility(declaration) AndAlso accessibility <> Accessibility.NotApplicable Then Return declaration End If Return Isolate(declaration, Function(d) Me.WithAccessibilityInternal(d, accessibility)) End Function Private Function WithAccessibilityInternal(declaration As SyntaxNode, accessibility As Accessibility) As SyntaxNode If Not SyntaxFacts.CanHaveAccessibility(declaration) Then Return declaration End If Dim tokens = SyntaxFacts.GetModifierTokens(declaration) Dim currentAcc As Accessibility Dim mods As DeclarationModifiers Dim isDefault As Boolean SyntaxFacts.GetAccessibilityAndModifiers(tokens, currentAcc, mods, isDefault) If currentAcc = accessibility Then Return declaration End If Dim newTokens = GetModifierList(accessibility, mods, declaration, GetDeclarationKind(declaration), isDefault) 'GetDeclarationKind returns None for Field if the count is > 1 'To handle multiple declarations on a field if the Accessibility is NotApplicable, we need to add the Dim If declaration.Kind = SyntaxKind.FieldDeclaration AndAlso accessibility = Accessibility.NotApplicable AndAlso newTokens.Count = 0 Then ' Add the Dim newTokens = newTokens.Add(SyntaxFactory.Token(SyntaxKind.DimKeyword)) End If Return WithModifierTokens(declaration, Merge(tokens, newTokens)) End Function Private Shared Function GetModifierList(accessibility As Accessibility, modifiers As DeclarationModifiers, declaration As SyntaxNode, kind As DeclarationKind, Optional isDefault As Boolean = False) As SyntaxTokenList Dim _list = SyntaxFactory.TokenList() ' While partial must always be last in C#, its preferred position in VB is to be first, ' even before accessibility modifiers. This order is enforced by line commit. If modifiers.IsPartial Then _list = _list.Add(SyntaxFactory.Token(SyntaxKind.PartialKeyword)) End If If isDefault Then _list = _list.Add(SyntaxFactory.Token(SyntaxKind.DefaultKeyword)) End If Select Case (accessibility) Case Accessibility.Internal _list = _list.Add(SyntaxFactory.Token(SyntaxKind.FriendKeyword)) Case Accessibility.Public _list = _list.Add(SyntaxFactory.Token(SyntaxKind.PublicKeyword)) Case Accessibility.Private _list = _list.Add(SyntaxFactory.Token(SyntaxKind.PrivateKeyword)) Case Accessibility.Protected _list = _list.Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword)) Case Accessibility.ProtectedOrInternal _list = _list.Add(SyntaxFactory.Token(SyntaxKind.FriendKeyword)).Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword)) Case Accessibility.ProtectedAndInternal _list = _list.Add(SyntaxFactory.Token(SyntaxKind.PrivateKeyword)).Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword)) Case Accessibility.NotApplicable Case Else Throw New NotSupportedException(String.Format("Accessibility '{0}' not supported.", accessibility)) End Select Dim isClass = kind = DeclarationKind.Class OrElse declaration.IsKind(SyntaxKind.ClassStatement) If modifiers.IsAbstract Then If isClass Then _list = _list.Add(SyntaxFactory.Token(SyntaxKind.MustInheritKeyword)) Else _list = _list.Add(SyntaxFactory.Token(SyntaxKind.MustOverrideKeyword)) End If End If If modifiers.IsNew Then _list = _list.Add(SyntaxFactory.Token(SyntaxKind.ShadowsKeyword)) End If If modifiers.IsSealed Then If isClass Then _list = _list.Add(SyntaxFactory.Token(SyntaxKind.NotInheritableKeyword)) Else _list = _list.Add(SyntaxFactory.Token(SyntaxKind.NotOverridableKeyword)) End If End If If modifiers.IsOverride Then _list = _list.Add(SyntaxFactory.Token(SyntaxKind.OverridesKeyword)) End If If modifiers.IsVirtual Then _list = _list.Add(SyntaxFactory.Token(SyntaxKind.OverridableKeyword)) End If If modifiers.IsStatic Then _list = _list.Add(SyntaxFactory.Token(SyntaxKind.SharedKeyword)) End If If modifiers.IsAsync Then _list = _list.Add(SyntaxFactory.Token(SyntaxKind.AsyncKeyword)) End If If modifiers.IsConst Then _list = _list.Add(SyntaxFactory.Token(SyntaxKind.ConstKeyword)) End If If modifiers.IsReadOnly Then _list = _list.Add(SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword)) End If If modifiers.IsWriteOnly Then _list = _list.Add(SyntaxFactory.Token(SyntaxKind.WriteOnlyKeyword)) End If If modifiers.IsUnsafe Then Throw New NotSupportedException("Unsupported modifier") ''''_list = _list.Add(SyntaxFactory.Token(SyntaxKind.UnsafeKeyword)) End If If modifiers.IsWithEvents Then _list = _list.Add(SyntaxFactory.Token(SyntaxKind.WithEventsKeyword)) End If If (kind = DeclarationKind.Field AndAlso _list.Count = 0) Then _list = _list.Add(SyntaxFactory.Token(SyntaxKind.DimKeyword)) End If Return _list End Function Private Shared Function GetTypeParameters(typeParameterNames As IEnumerable(Of String)) As TypeParameterListSyntax If typeParameterNames Is Nothing Then Return Nothing End If Dim typeParameterList = SyntaxFactory.TypeParameterList(SyntaxFactory.SeparatedList(typeParameterNames.Select(Function(name) SyntaxFactory.TypeParameter(name)))) If typeParameterList.Parameters.Count = 0 Then typeParameterList = Nothing End If Return typeParameterList End Function Public Overrides Function WithTypeParameters(declaration As SyntaxNode, typeParameterNames As IEnumerable(Of String)) As SyntaxNode Dim typeParameterList = GetTypeParameters(typeParameterNames) Return ReplaceTypeParameterList(declaration, Function(old) typeParameterList) End Function Private Shared Function ReplaceTypeParameterList(declaration As SyntaxNode, replacer As Func(Of TypeParameterListSyntax, TypeParameterListSyntax)) As SyntaxNode Dim method = TryCast(declaration, MethodStatementSyntax) If method IsNot Nothing Then Return method.WithTypeParameterList(replacer(method.TypeParameterList)) End If Dim methodBlock = TryCast(declaration, MethodBlockSyntax) If methodBlock IsNot Nothing Then Return methodBlock.WithSubOrFunctionStatement(methodBlock.SubOrFunctionStatement.WithTypeParameterList(replacer(methodBlock.SubOrFunctionStatement.TypeParameterList))) End If Dim classBlock = TryCast(declaration, ClassBlockSyntax) If classBlock IsNot Nothing Then Return classBlock.WithClassStatement(classBlock.ClassStatement.WithTypeParameterList(replacer(classBlock.ClassStatement.TypeParameterList))) End If Dim structureBlock = TryCast(declaration, StructureBlockSyntax) If structureBlock IsNot Nothing Then Return structureBlock.WithStructureStatement(structureBlock.StructureStatement.WithTypeParameterList(replacer(structureBlock.StructureStatement.TypeParameterList))) End If Dim interfaceBlock = TryCast(declaration, InterfaceBlockSyntax) If interfaceBlock IsNot Nothing Then Return interfaceBlock.WithInterfaceStatement(interfaceBlock.InterfaceStatement.WithTypeParameterList(replacer(interfaceBlock.InterfaceStatement.TypeParameterList))) End If Return declaration End Function Friend Overrides Function WithExplicitInterfaceImplementations(declaration As SyntaxNode, explicitInterfaceImplementations As ImmutableArray(Of ISymbol)) As SyntaxNode If TypeOf declaration Is MethodStatementSyntax Then Dim methodStatement = DirectCast(declaration, MethodStatementSyntax) Dim interfaceMembers = explicitInterfaceImplementations.Select(AddressOf GenerateInterfaceMember) Return methodStatement.WithImplementsClause( SyntaxFactory.ImplementsClause(SyntaxFactory.SeparatedList(interfaceMembers))) ElseIf TypeOf declaration Is MethodBlockSyntax Then Dim methodBlock = DirectCast(declaration, MethodBlockSyntax) Return methodBlock.WithSubOrFunctionStatement( DirectCast(WithExplicitInterfaceImplementations(methodBlock.SubOrFunctionStatement, explicitInterfaceImplementations), MethodStatementSyntax)) Else Debug.Fail("Unhandled kind to add explicit implementations for: " & declaration.Kind()) End If Return declaration End Function Private Function GenerateInterfaceMember(method As ISymbol) As QualifiedNameSyntax Dim interfaceName = method.ContainingType.GenerateTypeSyntax() Return SyntaxFactory.QualifiedName( DirectCast(interfaceName, NameSyntax), SyntaxFactory.IdentifierName(method.Name)) End Function Public Overrides Function WithTypeConstraint(declaration As SyntaxNode, typeParameterName As String, kinds As SpecialTypeConstraintKind, Optional types As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Dim constraints = SyntaxFactory.SeparatedList(Of ConstraintSyntax) If types IsNot Nothing Then constraints = constraints.AddRange(types.Select(Function(t) SyntaxFactory.TypeConstraint(DirectCast(t, TypeSyntax)))) End If If (kinds And SpecialTypeConstraintKind.Constructor) <> 0 Then constraints = constraints.Add(SyntaxFactory.NewConstraint(SyntaxFactory.Token(SyntaxKind.NewKeyword))) End If Dim isReferenceType = (kinds And SpecialTypeConstraintKind.ReferenceType) <> 0 Dim isValueType = (kinds And SpecialTypeConstraintKind.ValueType) <> 0 If isReferenceType Then constraints = constraints.Insert(0, SyntaxFactory.ClassConstraint(SyntaxFactory.Token(SyntaxKind.ClassKeyword))) ElseIf isValueType Then constraints = constraints.Insert(0, SyntaxFactory.StructureConstraint(SyntaxFactory.Token(SyntaxKind.StructureKeyword))) End If Dim clause As TypeParameterConstraintClauseSyntax = Nothing If constraints.Count = 1 Then clause = SyntaxFactory.TypeParameterSingleConstraintClause(constraints(0)) ElseIf constraints.Count > 1 Then clause = SyntaxFactory.TypeParameterMultipleConstraintClause(constraints) End If Return ReplaceTypeParameterList(declaration, Function(old) WithTypeParameterConstraints(old, typeParameterName, clause)) End Function Private Shared Function WithTypeParameterConstraints(typeParameterList As TypeParameterListSyntax, typeParameterName As String, clause As TypeParameterConstraintClauseSyntax) As TypeParameterListSyntax If typeParameterList IsNot Nothing Then Dim typeParameter = typeParameterList.Parameters.FirstOrDefault(Function(tp) tp.Identifier.ToString() = typeParameterName) If typeParameter IsNot Nothing Then Return typeParameterList.WithParameters(typeParameterList.Parameters.Replace(typeParameter, typeParameter.WithTypeParameterConstraintClause(clause))) End If End If Return typeParameterList End Function Public Overrides Function GetParameters(declaration As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Dim list = declaration.GetParameterList() Return If(list IsNot Nothing, list.Parameters, SpecializedCollections.EmptyReadOnlyList(Of SyntaxNode)) End Function Public Overrides Function InsertParameters(declaration As SyntaxNode, index As Integer, parameters As IEnumerable(Of SyntaxNode)) As SyntaxNode Dim currentList = declaration.GetParameterList() Dim newList = GetParameterList(parameters) If currentList IsNot Nothing Then Return WithParameterList(declaration, currentList.WithParameters(currentList.Parameters.InsertRange(index, newList.Parameters))) Else Return WithParameterList(declaration, newList) End If End Function Public Overrides Function GetSwitchSections(switchStatement As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Dim statement = TryCast(switchStatement, SelectBlockSyntax) If statement Is Nothing Then Return SpecializedCollections.EmptyReadOnlyList(Of SyntaxNode) End If Return statement.CaseBlocks End Function Public Overrides Function InsertSwitchSections(switchStatement As SyntaxNode, index As Integer, switchSections As IEnumerable(Of SyntaxNode)) As SyntaxNode Dim statement = TryCast(switchStatement, SelectBlockSyntax) If statement Is Nothing Then Return switchStatement End If Return statement.WithCaseBlocks( statement.CaseBlocks.InsertRange(index, switchSections.Cast(Of CaseBlockSyntax))) End Function Friend Overrides Function GetParameterListNode(declaration As SyntaxNode) As SyntaxNode Return declaration.GetParameterList() End Function Private Function WithParameterList(declaration As SyntaxNode, list As ParameterListSyntax) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement Return DirectCast(declaration, DelegateStatementSyntax).WithParameterList(list) Case SyntaxKind.SubBlock, SyntaxKind.FunctionBlock Return DirectCast(declaration, MethodBlockSyntax).WithBlockStatement(DirectCast(declaration, MethodBlockSyntax).BlockStatement.WithParameterList(list)) Case SyntaxKind.ConstructorBlock Return DirectCast(declaration, ConstructorBlockSyntax).WithBlockStatement(DirectCast(declaration, ConstructorBlockSyntax).BlockStatement.WithParameterList(list)) Case SyntaxKind.OperatorBlock Return DirectCast(declaration, OperatorBlockSyntax).WithBlockStatement(DirectCast(declaration, OperatorBlockSyntax).BlockStatement.WithParameterList(list)) Case SyntaxKind.SubStatement, SyntaxKind.FunctionStatement Return DirectCast(declaration, MethodStatementSyntax).WithParameterList(list) Case SyntaxKind.SubNewStatement Return DirectCast(declaration, SubNewStatementSyntax).WithParameterList(list) Case SyntaxKind.OperatorStatement Return DirectCast(declaration, OperatorStatementSyntax).WithParameterList(list) Case SyntaxKind.DeclareSubStatement, SyntaxKind.DeclareFunctionStatement Return DirectCast(declaration, DeclareStatementSyntax).WithParameterList(list) Case SyntaxKind.DelegateSubStatement, SyntaxKind.DelegateFunctionStatement Return DirectCast(declaration, DelegateStatementSyntax).WithParameterList(list) Case SyntaxKind.PropertyBlock If GetDeclarationKind(declaration) = DeclarationKind.Indexer Then Return DirectCast(declaration, PropertyBlockSyntax).WithPropertyStatement(DirectCast(declaration, PropertyBlockSyntax).PropertyStatement.WithParameterList(list)) End If Case SyntaxKind.PropertyStatement If GetDeclarationKind(declaration) = DeclarationKind.Indexer Then Return DirectCast(declaration, PropertyStatementSyntax).WithParameterList(list) End If Case SyntaxKind.EventBlock Return DirectCast(declaration, EventBlockSyntax).WithEventStatement(DirectCast(declaration, EventBlockSyntax).EventStatement.WithParameterList(list)) Case SyntaxKind.EventStatement Return DirectCast(declaration, EventStatementSyntax).WithParameterList(list) Case SyntaxKind.MultiLineFunctionLambdaExpression, SyntaxKind.MultiLineSubLambdaExpression Return DirectCast(declaration, MultiLineLambdaExpressionSyntax).WithSubOrFunctionHeader(DirectCast(declaration, MultiLineLambdaExpressionSyntax).SubOrFunctionHeader.WithParameterList(list)) Case SyntaxKind.SingleLineFunctionLambdaExpression, SyntaxKind.SingleLineSubLambdaExpression Return DirectCast(declaration, SingleLineLambdaExpressionSyntax).WithSubOrFunctionHeader(DirectCast(declaration, SingleLineLambdaExpressionSyntax).SubOrFunctionHeader.WithParameterList(list)) End Select Return declaration End Function Public Overrides Function GetExpression(declaration As SyntaxNode) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.SingleLineFunctionLambdaExpression, SyntaxKind.SingleLineSubLambdaExpression Return AsExpression(DirectCast(declaration, SingleLineLambdaExpressionSyntax).Body) Case Else Dim ev = GetEqualsValue(declaration) If ev IsNot Nothing Then Return ev.Value End If End Select Return Nothing End Function Private Shared Function AsExpression(node As SyntaxNode) As ExpressionSyntax Dim es = TryCast(node, ExpressionStatementSyntax) If es IsNot Nothing Then Return es.Expression End If Return DirectCast(node, ExpressionSyntax) End Function Public Overrides Function WithExpression(declaration As SyntaxNode, expression As SyntaxNode) As SyntaxNode Return Isolate(declaration, Function(d) WithExpressionInternal(d, expression)) End Function Private Function WithExpressionInternal(declaration As SyntaxNode, expression As SyntaxNode) As SyntaxNode Dim expr = DirectCast(expression, ExpressionSyntax) Select Case declaration.Kind Case SyntaxKind.SingleLineFunctionLambdaExpression Dim sll = DirectCast(declaration, SingleLineLambdaExpressionSyntax) If expression IsNot Nothing Then Return sll.WithBody(expr) Else Return SyntaxFactory.MultiLineLambdaExpression(SyntaxKind.MultiLineFunctionLambdaExpression, sll.SubOrFunctionHeader, SyntaxFactory.EndFunctionStatement()) End If Case SyntaxKind.MultiLineFunctionLambdaExpression Dim mll = DirectCast(declaration, MultiLineLambdaExpressionSyntax) If expression IsNot Nothing Then Return SyntaxFactory.SingleLineLambdaExpression(SyntaxKind.SingleLineFunctionLambdaExpression, mll.SubOrFunctionHeader, expr) End If Case SyntaxKind.SingleLineSubLambdaExpression Dim sll = DirectCast(declaration, SingleLineLambdaExpressionSyntax) If expression IsNot Nothing Then Return sll.WithBody(AsStatement(expr)) Else Return SyntaxFactory.MultiLineLambdaExpression(SyntaxKind.MultiLineSubLambdaExpression, sll.SubOrFunctionHeader, SyntaxFactory.EndSubStatement()) End If Case SyntaxKind.MultiLineSubLambdaExpression Dim mll = DirectCast(declaration, MultiLineLambdaExpressionSyntax) If expression IsNot Nothing Then Return SyntaxFactory.SingleLineLambdaExpression(SyntaxKind.SingleLineSubLambdaExpression, mll.SubOrFunctionHeader, AsStatement(expr)) End If Case Else Dim currentEV = GetEqualsValue(declaration) If currentEV IsNot Nothing Then Return WithEqualsValue(declaration, currentEV.WithValue(expr)) Else Return WithEqualsValue(declaration, SyntaxFactory.EqualsValue(expr)) End If End Select Return declaration End Function Private Shared Function GetEqualsValue(declaration As SyntaxNode) As EqualsValueSyntax Select Case declaration.Kind Case SyntaxKind.Parameter Return DirectCast(declaration, ParameterSyntax).Default Case SyntaxKind.LocalDeclarationStatement Dim ld = DirectCast(declaration, LocalDeclarationStatementSyntax) If ld.Declarators.Count = 1 Then Return ld.Declarators(0).Initializer End If Case SyntaxKind.FieldDeclaration Dim fd = DirectCast(declaration, FieldDeclarationSyntax) If fd.Declarators.Count = 1 Then Return fd.Declarators(0).Initializer End If Case SyntaxKind.VariableDeclarator Return DirectCast(declaration, VariableDeclaratorSyntax).Initializer End Select Return Nothing End Function Private Shared Function WithEqualsValue(declaration As SyntaxNode, ev As EqualsValueSyntax) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.Parameter Return DirectCast(declaration, ParameterSyntax).WithDefault(ev) Case SyntaxKind.LocalDeclarationStatement Dim ld = DirectCast(declaration, LocalDeclarationStatementSyntax) If ld.Declarators.Count = 1 Then Return ReplaceWithTrivia(declaration, ld.Declarators(0), ld.Declarators(0).WithInitializer(ev)) End If Case SyntaxKind.FieldDeclaration Dim fd = DirectCast(declaration, FieldDeclarationSyntax) If fd.Declarators.Count = 1 Then Return ReplaceWithTrivia(declaration, fd.Declarators(0), fd.Declarators(0).WithInitializer(ev)) End If End Select Return declaration End Function Public Overrides Function GetNamespaceImports(declaration As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Return Me.Flatten(GetUnflattenedNamespaceImports(declaration)) End Function Private Shared Function GetUnflattenedNamespaceImports(declaration As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Select Case declaration.Kind Case SyntaxKind.CompilationUnit Return DirectCast(declaration, CompilationUnitSyntax).Imports Case Else Return SpecializedCollections.EmptyReadOnlyList(Of SyntaxNode) End Select End Function Public Overrides Function InsertNamespaceImports(declaration As SyntaxNode, index As Integer, [imports] As IEnumerable(Of SyntaxNode)) As SyntaxNode Return Isolate(declaration, Function(d) InsertNamespaceImportsInternal(d, index, [imports])) End Function Private Function InsertNamespaceImportsInternal(declaration As SyntaxNode, index As Integer, [imports] As IEnumerable(Of SyntaxNode)) As SyntaxNode Dim newImports = AsImports([imports]) Dim existingImports = Me.GetNamespaceImports(declaration) If index >= 0 AndAlso index < existingImports.Count Then Return Me.InsertNodesBefore(declaration, existingImports(index), newImports) ElseIf existingImports.Count > 0 Then Return Me.InsertNodesAfter(declaration, existingImports(existingImports.Count - 1), newImports) Else Select Case declaration.Kind Case SyntaxKind.CompilationUnit Dim cu = DirectCast(declaration, CompilationUnitSyntax) Return cu.WithImports(cu.Imports.AddRange(newImports)) Case Else Return declaration End Select End If End Function Public Overrides Function GetMembers(declaration As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Return Flatten(GetUnflattenedMembers(declaration)) End Function Private Shared Function GetUnflattenedMembers(declaration As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Select Case declaration.Kind Case SyntaxKind.CompilationUnit Return DirectCast(declaration, CompilationUnitSyntax).Members Case SyntaxKind.NamespaceBlock Return DirectCast(declaration, NamespaceBlockSyntax).Members Case SyntaxKind.ClassBlock Return DirectCast(declaration, ClassBlockSyntax).Members Case SyntaxKind.StructureBlock Return DirectCast(declaration, StructureBlockSyntax).Members Case SyntaxKind.InterfaceBlock Return DirectCast(declaration, InterfaceBlockSyntax).Members Case SyntaxKind.EnumBlock Return DirectCast(declaration, EnumBlockSyntax).Members Case Else Return SpecializedCollections.EmptyReadOnlyList(Of SyntaxNode)() End Select End Function Private Function AsMembersOf(declaration As SyntaxNode, members As IEnumerable(Of SyntaxNode)) As IEnumerable(Of StatementSyntax) Select Case declaration.Kind Case SyntaxKind.CompilationUnit Return AsNamespaceMembers(members) Case SyntaxKind.NamespaceBlock Return AsNamespaceMembers(members) Case SyntaxKind.ClassBlock Return AsClassMembers(members) Case SyntaxKind.StructureBlock Return AsClassMembers(members) Case SyntaxKind.InterfaceBlock Return AsInterfaceMembers(members) Case SyntaxKind.EnumBlock Return AsEnumMembers(members) Case Else Return SpecializedCollections.EmptyEnumerable(Of StatementSyntax) End Select End Function Public Overrides Function InsertMembers(declaration As SyntaxNode, index As Integer, members As IEnumerable(Of SyntaxNode)) As SyntaxNode Return Isolate(declaration, Function(d) InsertMembersInternal(d, index, members)) End Function Private Function InsertMembersInternal(declaration As SyntaxNode, index As Integer, members As IEnumerable(Of SyntaxNode)) As SyntaxNode Dim newMembers = Me.AsMembersOf(declaration, members) Dim existingMembers = Me.GetMembers(declaration) If index >= 0 AndAlso index < existingMembers.Count Then Return Me.InsertNodesBefore(declaration, existingMembers(index), members) ElseIf existingMembers.Count > 0 Then Return Me.InsertNodesAfter(declaration, existingMembers(existingMembers.Count - 1), members) End If Select Case declaration.Kind Case SyntaxKind.CompilationUnit Dim cu = DirectCast(declaration, CompilationUnitSyntax) Return cu.WithMembers(cu.Members.AddRange(newMembers)) Case SyntaxKind.NamespaceBlock Dim ns = DirectCast(declaration, NamespaceBlockSyntax) Return ns.WithMembers(ns.Members.AddRange(newMembers)) Case SyntaxKind.ClassBlock Dim cb = DirectCast(declaration, ClassBlockSyntax) Return cb.WithMembers(cb.Members.AddRange(newMembers)) Case SyntaxKind.StructureBlock Dim sb = DirectCast(declaration, StructureBlockSyntax) Return sb.WithMembers(sb.Members.AddRange(newMembers)) Case SyntaxKind.InterfaceBlock Dim ib = DirectCast(declaration, InterfaceBlockSyntax) Return ib.WithMembers(ib.Members.AddRange(newMembers)) Case SyntaxKind.EnumBlock Dim eb = DirectCast(declaration, EnumBlockSyntax) Return eb.WithMembers(eb.Members.AddRange(newMembers)) Case Else Return declaration End Select End Function Public Overrides Function GetStatements(declaration As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Select Case declaration.Kind Case SyntaxKind.FunctionBlock, SyntaxKind.SubBlock, SyntaxKind.ConstructorBlock, SyntaxKind.OperatorBlock Return DirectCast(declaration, MethodBlockBaseSyntax).Statements Case SyntaxKind.MultiLineFunctionLambdaExpression, SyntaxKind.MultiLineSubLambdaExpression Return DirectCast(declaration, MultiLineLambdaExpressionSyntax).Statements Case SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock, SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RaiseEventAccessorBlock Return DirectCast(declaration, AccessorBlockSyntax).Statements Case Else Return SpecializedCollections.EmptyReadOnlyList(Of SyntaxNode) End Select End Function Public Overrides Function WithStatements(declaration As SyntaxNode, statements As IEnumerable(Of SyntaxNode)) As SyntaxNode Return Isolate(declaration, Function(d) WithStatementsInternal(d, statements)) End Function Private Function WithStatementsInternal(declaration As SyntaxNode, statements As IEnumerable(Of SyntaxNode)) As SyntaxNode Dim list = GetStatementList(statements) Select Case declaration.Kind Case SyntaxKind.FunctionBlock, SyntaxKind.SubBlock Return DirectCast(declaration, MethodBlockSyntax).WithStatements(list) Case SyntaxKind.ConstructorBlock Return DirectCast(declaration, ConstructorBlockSyntax).WithStatements(list) Case SyntaxKind.OperatorBlock Return DirectCast(declaration, OperatorBlockSyntax).WithStatements(list) Case SyntaxKind.MultiLineFunctionLambdaExpression, SyntaxKind.MultiLineSubLambdaExpression Return DirectCast(declaration, MultiLineLambdaExpressionSyntax).WithStatements(list) Case SyntaxKind.SingleLineFunctionLambdaExpression Dim sll = DirectCast(declaration, SingleLineLambdaExpressionSyntax) Return SyntaxFactory.MultiLineLambdaExpression(SyntaxKind.MultiLineFunctionLambdaExpression, sll.SubOrFunctionHeader, list, SyntaxFactory.EndFunctionStatement()) Case SyntaxKind.SingleLineSubLambdaExpression Dim sll = DirectCast(declaration, SingleLineLambdaExpressionSyntax) Return SyntaxFactory.MultiLineLambdaExpression(SyntaxKind.MultiLineSubLambdaExpression, sll.SubOrFunctionHeader, list, SyntaxFactory.EndSubStatement()) Case SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock, SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RaiseEventAccessorBlock Return DirectCast(declaration, AccessorBlockSyntax).WithStatements(list) Case Else Return declaration End Select End Function Public Overrides Function GetAccessors(declaration As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Select Case declaration.Kind Case SyntaxKind.PropertyBlock Return DirectCast(declaration, PropertyBlockSyntax).Accessors Case SyntaxKind.EventBlock Return DirectCast(declaration, EventBlockSyntax).Accessors Case Else Return SpecializedCollections.EmptyReadOnlyList(Of SyntaxNode)() End Select End Function Public Overrides Function InsertAccessors(declaration As SyntaxNode, index As Integer, accessors As IEnumerable(Of SyntaxNode)) As SyntaxNode Dim currentList = GetAccessorList(declaration) Dim newList = AsAccessorList(accessors, declaration.Kind) If Not currentList.IsEmpty Then Return WithAccessorList(declaration, currentList.InsertRange(index, newList)) Else Return WithAccessorList(declaration, newList) End If End Function Friend Shared Function GetAccessorList(declaration As SyntaxNode) As SyntaxList(Of AccessorBlockSyntax) Select Case declaration.Kind Case SyntaxKind.PropertyBlock Return DirectCast(declaration, PropertyBlockSyntax).Accessors Case SyntaxKind.EventBlock Return DirectCast(declaration, EventBlockSyntax).Accessors Case Else Return Nothing End Select End Function Private Shared Function WithAccessorList(declaration As SyntaxNode, accessorList As SyntaxList(Of AccessorBlockSyntax)) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.PropertyBlock Return DirectCast(declaration, PropertyBlockSyntax).WithAccessors(accessorList) Case SyntaxKind.EventBlock Return DirectCast(declaration, EventBlockSyntax).WithAccessors(accessorList) Case Else Return declaration End Select End Function Private Shared Function AsAccessorList(nodes As IEnumerable(Of SyntaxNode), parentKind As SyntaxKind) As SyntaxList(Of AccessorBlockSyntax) Return SyntaxFactory.List(nodes.Select(Function(n) AsAccessor(n, parentKind)).Where(Function(n) n IsNot Nothing)) End Function Private Shared Function AsAccessor(node As SyntaxNode, parentKind As SyntaxKind) As AccessorBlockSyntax Select Case parentKind Case SyntaxKind.PropertyBlock Select Case node.Kind Case SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock Return DirectCast(node, AccessorBlockSyntax) End Select Case SyntaxKind.EventBlock Select Case node.Kind Case SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RaiseEventAccessorBlock Return DirectCast(node, AccessorBlockSyntax) End Select End Select Return Nothing End Function Private Shared Function CanHaveAccessors(kind As SyntaxKind) As Boolean Select Case kind Case SyntaxKind.PropertyBlock, SyntaxKind.EventBlock Return True Case Else Return False End Select End Function Public Overrides Function GetGetAccessorStatements(declaration As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Return GetAccessorStatements(declaration, SyntaxKind.GetAccessorBlock) End Function Public Overrides Function WithGetAccessorStatements(declaration As SyntaxNode, statements As IEnumerable(Of SyntaxNode)) As SyntaxNode Return WithAccessorStatements(declaration, statements, SyntaxKind.GetAccessorBlock) End Function Public Overrides Function GetSetAccessorStatements(declaration As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Return GetAccessorStatements(declaration, SyntaxKind.SetAccessorBlock) End Function Public Overrides Function WithSetAccessorStatements(declaration As SyntaxNode, statements As IEnumerable(Of SyntaxNode)) As SyntaxNode Return WithAccessorStatements(declaration, statements, SyntaxKind.SetAccessorBlock) End Function Private Function GetAccessorStatements(declaration As SyntaxNode, kind As SyntaxKind) As IReadOnlyList(Of SyntaxNode) Dim accessor = GetAccessorBlock(declaration, kind) If accessor IsNot Nothing Then Return Me.GetStatements(accessor) Else Return SpecializedCollections.EmptyReadOnlyList(Of SyntaxNode)() End If End Function Private Function WithAccessorStatements(declaration As SyntaxNode, statements As IEnumerable(Of SyntaxNode), kind As SyntaxKind) As SyntaxNode Dim accessor = GetAccessorBlock(declaration, kind) If accessor IsNot Nothing Then accessor = DirectCast(Me.WithStatements(accessor, statements), AccessorBlockSyntax) Return Me.WithAccessorBlock(declaration, kind, accessor) ElseIf CanHaveAccessors(declaration.Kind) Then accessor = Me.AccessorBlock(kind, statements, Me.ClearTrivia(Me.GetType(declaration))) Return Me.WithAccessorBlock(declaration, kind, accessor) Else Return declaration End If End Function Private Shared Function GetAccessorBlock(declaration As SyntaxNode, kind As SyntaxKind) As AccessorBlockSyntax Select Case declaration.Kind Case SyntaxKind.PropertyBlock Return DirectCast(declaration, PropertyBlockSyntax).Accessors.FirstOrDefault(Function(a) a.IsKind(kind)) Case SyntaxKind.EventBlock Return DirectCast(declaration, EventBlockSyntax).Accessors.FirstOrDefault(Function(a) a.IsKind(kind)) Case Else Return Nothing End Select End Function Private Function WithAccessorBlock(declaration As SyntaxNode, kind As SyntaxKind, accessor As AccessorBlockSyntax) As SyntaxNode Dim currentAccessor = GetAccessorBlock(declaration, kind) If currentAccessor IsNot Nothing Then Return Me.ReplaceNode(declaration, currentAccessor, accessor) ElseIf accessor IsNot Nothing Then Select Case declaration.Kind Case SyntaxKind.PropertyBlock Dim pb = DirectCast(declaration, PropertyBlockSyntax) Return pb.WithAccessors(pb.Accessors.Add(accessor)) Case SyntaxKind.EventBlock Dim eb = DirectCast(declaration, EventBlockSyntax) Return eb.WithAccessors(eb.Accessors.Add(accessor)) End Select End If Return declaration End Function Public Overrides Function EventDeclaration(name As String, type As SyntaxNode, Optional accessibility As Accessibility = Accessibility.NotApplicable, Optional modifiers As DeclarationModifiers = Nothing) As SyntaxNode Return SyntaxFactory.EventStatement( attributeLists:=Nothing, modifiers:=GetModifierList(accessibility, modifiers And GetAllowedModifiers(SyntaxKind.EventStatement), declaration:=Nothing, DeclarationKind.Event), customKeyword:=Nothing, eventKeyword:=SyntaxFactory.Token(SyntaxKind.EventKeyword), identifier:=name.ToIdentifierToken(), parameterList:=Nothing, asClause:=SyntaxFactory.SimpleAsClause(DirectCast(type, TypeSyntax)), implementsClause:=Nothing) End Function Public Overrides Function CustomEventDeclaration( name As String, type As SyntaxNode, Optional accessibility As Accessibility = Accessibility.NotApplicable, Optional modifiers As DeclarationModifiers = Nothing, Optional parameters As IEnumerable(Of SyntaxNode) = Nothing, Optional addAccessorStatements As IEnumerable(Of SyntaxNode) = Nothing, Optional removeAccessorStatements As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Return CustomEventDeclarationWithRaise(name, type, accessibility, modifiers, parameters, addAccessorStatements, removeAccessorStatements) End Function Public Function CustomEventDeclarationWithRaise( name As String, type As SyntaxNode, Optional accessibility As Accessibility = Accessibility.NotApplicable, Optional modifiers As DeclarationModifiers = Nothing, Optional parameters As IEnumerable(Of SyntaxNode) = Nothing, Optional addAccessorStatements As IEnumerable(Of SyntaxNode) = Nothing, Optional removeAccessorStatements As IEnumerable(Of SyntaxNode) = Nothing, Optional raiseAccessorStatements As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode Dim accessors = New List(Of AccessorBlockSyntax)() If modifiers.IsAbstract Then addAccessorStatements = Nothing removeAccessorStatements = Nothing raiseAccessorStatements = Nothing Else If addAccessorStatements Is Nothing Then addAccessorStatements = SpecializedCollections.EmptyEnumerable(Of SyntaxNode)() End If If removeAccessorStatements Is Nothing Then removeAccessorStatements = SpecializedCollections.EmptyEnumerable(Of SyntaxNode)() End If If raiseAccessorStatements Is Nothing Then raiseAccessorStatements = SpecializedCollections.EmptyEnumerable(Of SyntaxNode)() End If End If accessors.Add(CreateAddHandlerAccessorBlock(type, addAccessorStatements)) accessors.Add(CreateRemoveHandlerAccessorBlock(type, removeAccessorStatements)) accessors.Add(CreateRaiseEventAccessorBlock(parameters, raiseAccessorStatements)) Dim evStatement = SyntaxFactory.EventStatement( attributeLists:=Nothing, modifiers:=GetModifierList(accessibility, modifiers And GetAllowedModifiers(SyntaxKind.EventStatement), declaration:=Nothing, DeclarationKind.Event), customKeyword:=SyntaxFactory.Token(SyntaxKind.CustomKeyword), eventKeyword:=SyntaxFactory.Token(SyntaxKind.EventKeyword), identifier:=name.ToIdentifierToken(), parameterList:=Nothing, asClause:=SyntaxFactory.SimpleAsClause(DirectCast(type, TypeSyntax)), implementsClause:=Nothing) Return SyntaxFactory.EventBlock( eventStatement:=evStatement, accessors:=SyntaxFactory.List(accessors), endEventStatement:=SyntaxFactory.EndEventStatement()) End Function Public Overrides Function GetAttributeArguments(attributeDeclaration As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Dim list = GetArgumentList(attributeDeclaration) If list IsNot Nothing Then Return list.Arguments Else Return SpecializedCollections.EmptyReadOnlyList(Of SyntaxNode)() End If End Function Public Overrides Function InsertAttributeArguments(attributeDeclaration As SyntaxNode, index As Integer, attributeArguments As IEnumerable(Of SyntaxNode)) As SyntaxNode Return Isolate(attributeDeclaration, Function(d) InsertAttributeArgumentsInternal(d, index, attributeArguments)) End Function Private Function InsertAttributeArgumentsInternal(attributeDeclaration As SyntaxNode, index As Integer, attributeArguments As IEnumerable(Of SyntaxNode)) As SyntaxNode Dim list = GetArgumentList(attributeDeclaration) Dim newArguments = AsArgumentList(attributeArguments) If list Is Nothing Then list = newArguments Else list = list.WithArguments(list.Arguments.InsertRange(index, newArguments.Arguments)) End If Return WithArgumentList(attributeDeclaration, list) End Function Private Shared Function GetArgumentList(declaration As SyntaxNode) As ArgumentListSyntax Select Case declaration.Kind Case SyntaxKind.AttributeList Dim al = DirectCast(declaration, AttributeListSyntax) If al.Attributes.Count = 1 Then Return al.Attributes(0).ArgumentList End If Case SyntaxKind.Attribute Return DirectCast(declaration, AttributeSyntax).ArgumentList End Select Return Nothing End Function Private Shared Function WithArgumentList(declaration As SyntaxNode, argumentList As ArgumentListSyntax) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.AttributeList Dim al = DirectCast(declaration, AttributeListSyntax) If al.Attributes.Count = 1 Then Return ReplaceWithTrivia(declaration, al.Attributes(0), al.Attributes(0).WithArgumentList(argumentList)) End If Case SyntaxKind.Attribute Return DirectCast(declaration, AttributeSyntax).WithArgumentList(argumentList) End Select Return declaration End Function Public Overrides Function GetBaseAndInterfaceTypes(declaration As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Return GetInherits(declaration).SelectMany(Function(ih) ih.Types).Concat(GetImplements(declaration).SelectMany(Function(imp) imp.Types)).ToBoxedImmutableArray() End Function Public Overrides Function AddBaseType(declaration As SyntaxNode, baseType As SyntaxNode) As SyntaxNode If declaration.IsKind(SyntaxKind.ClassBlock) Then Dim existingBaseType = GetInherits(declaration).SelectMany(Function(inh) inh.Types).FirstOrDefault() If existingBaseType IsNot Nothing Then Return declaration.ReplaceNode(existingBaseType, baseType.WithTriviaFrom(existingBaseType)) Else Return WithInherits(declaration, SyntaxFactory.SingletonList(SyntaxFactory.InheritsStatement(DirectCast(baseType, TypeSyntax)))) End If Else Return declaration End If End Function Public Overrides Function AddInterfaceType(declaration As SyntaxNode, interfaceType As SyntaxNode) As SyntaxNode If declaration.IsKind(SyntaxKind.InterfaceBlock) Then Dim inh = GetInherits(declaration) Dim last = inh.SelectMany(Function(s) s.Types).LastOrDefault() If inh.Count = 1 AndAlso last IsNot Nothing Then Dim inh0 = inh(0) Dim newInh0 = PreserveTrivia(inh0.TrackNodes(last), Function(_inh0) InsertNodesAfter(_inh0, _inh0.GetCurrentNode(last), {interfaceType})) Return ReplaceNode(declaration, inh0, newInh0) Else Return WithInherits(declaration, inh.Add(SyntaxFactory.InheritsStatement(DirectCast(interfaceType, TypeSyntax)))) End If Else Dim imp = GetImplements(declaration) Dim last = imp.SelectMany(Function(s) s.Types).LastOrDefault() If imp.Count = 1 AndAlso last IsNot Nothing Then Dim imp0 = imp(0) Dim newImp0 = PreserveTrivia(imp0.TrackNodes(last), Function(_imp0) InsertNodesAfter(_imp0, _imp0.GetCurrentNode(last), {interfaceType})) Return ReplaceNode(declaration, imp0, newImp0) Else Return WithImplements(declaration, imp.Add(SyntaxFactory.ImplementsStatement(DirectCast(interfaceType, TypeSyntax)))) End If End If End Function Private Shared Function GetInherits(declaration As SyntaxNode) As SyntaxList(Of InheritsStatementSyntax) Select Case declaration.Kind Case SyntaxKind.ClassBlock Return DirectCast(declaration, ClassBlockSyntax).Inherits Case SyntaxKind.InterfaceBlock Return DirectCast(declaration, InterfaceBlockSyntax).Inherits Case Else Return Nothing End Select End Function Private Shared Function WithInherits(declaration As SyntaxNode, list As SyntaxList(Of InheritsStatementSyntax)) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.ClassBlock Return DirectCast(declaration, ClassBlockSyntax).WithInherits(list) Case SyntaxKind.InterfaceBlock Return DirectCast(declaration, InterfaceBlockSyntax).WithInherits(list) Case Else Return declaration End Select End Function Private Shared Function GetImplements(declaration As SyntaxNode) As SyntaxList(Of ImplementsStatementSyntax) Select Case declaration.Kind Case SyntaxKind.ClassBlock Return DirectCast(declaration, ClassBlockSyntax).Implements Case SyntaxKind.StructureBlock Return DirectCast(declaration, StructureBlockSyntax).Implements Case Else Return Nothing End Select End Function Private Shared Function WithImplements(declaration As SyntaxNode, list As SyntaxList(Of ImplementsStatementSyntax)) As SyntaxNode Select Case declaration.Kind Case SyntaxKind.ClassBlock Return DirectCast(declaration, ClassBlockSyntax).WithImplements(list) Case SyntaxKind.StructureBlock Return DirectCast(declaration, StructureBlockSyntax).WithImplements(list) Case Else Return declaration End Select End Function #End Region #Region "Remove, Replace, Insert" Public Overrides Function ReplaceNode(root As SyntaxNode, declaration As SyntaxNode, newDeclaration As SyntaxNode) As SyntaxNode If newDeclaration Is Nothing Then Return Me.RemoveNode(root, declaration) End If If root.Span.Contains(declaration.Span) Then Dim newFullDecl = Me.AsIsolatedDeclaration(newDeclaration) Dim fullDecl = Me.GetFullDeclaration(declaration) ' special handling for replacing at location of a sub-declaration If fullDecl IsNot declaration AndAlso fullDecl.IsKind(newFullDecl.Kind) Then ' try to replace inline if possible If GetDeclarationCount(newFullDecl) = 1 Then Dim newSubDecl = GetSubDeclarations(newFullDecl)(0) If AreInlineReplaceableSubDeclarations(declaration, newSubDecl) Then Return MyBase.ReplaceNode(root, declaration, newSubDecl) End If End If ' otherwise replace by splitting full-declaration into two parts and inserting newDeclaration between them Dim index = MyBase.IndexOf(GetSubDeclarations(fullDecl), declaration) Return Me.ReplaceSubDeclaration(root, fullDecl, index, newFullDecl) End If ' attempt normal replace Return MyBase.ReplaceNode(root, declaration, newFullDecl) Else Return MyBase.ReplaceNode(root, declaration, newDeclaration) End If End Function ' return true if one sub-declaration can be replaced in-line with another sub-declaration Private Function AreInlineReplaceableSubDeclarations(decl1 As SyntaxNode, decl2 As SyntaxNode) As Boolean Dim kind = decl1.Kind If Not decl2.IsKind(kind) Then Return False End If Select Case kind Case SyntaxKind.ModifiedIdentifier, SyntaxKind.Attribute, SyntaxKind.SimpleImportsClause, SyntaxKind.XmlNamespaceImportsClause Return AreSimilarExceptForSubDeclarations(decl1.Parent, decl2.Parent) End Select Return False End Function Private Function AreSimilarExceptForSubDeclarations(decl1 As SyntaxNode, decl2 As SyntaxNode) As Boolean If decl1 Is Nothing OrElse decl2 Is Nothing Then Return False End If Dim kind = decl1.Kind If Not decl2.IsKind(kind) Then Return False End If Select Case kind Case SyntaxKind.FieldDeclaration Dim fd1 = DirectCast(decl1, FieldDeclarationSyntax) Dim fd2 = DirectCast(decl2, FieldDeclarationSyntax) Return SyntaxFactory.AreEquivalent(fd1.AttributeLists, fd2.AttributeLists) AndAlso SyntaxFactory.AreEquivalent(fd1.Modifiers, fd2.Modifiers) Case SyntaxKind.LocalDeclarationStatement Dim ld1 = DirectCast(decl1, LocalDeclarationStatementSyntax) Dim ld2 = DirectCast(decl2, LocalDeclarationStatementSyntax) Return SyntaxFactory.AreEquivalent(ld1.Modifiers, ld2.Modifiers) Case SyntaxKind.VariableDeclarator Dim vd1 = DirectCast(decl1, VariableDeclaratorSyntax) Dim vd2 = DirectCast(decl2, VariableDeclaratorSyntax) Return SyntaxFactory.AreEquivalent(vd1.AsClause, vd2.AsClause) AndAlso SyntaxFactory.AreEquivalent(vd2.Initializer, vd1.Initializer) AndAlso AreSimilarExceptForSubDeclarations(decl1.Parent, decl2.Parent) Case SyntaxKind.AttributeList, SyntaxKind.ImportsStatement Return True End Select Return False End Function Public Overrides Function InsertNodesBefore(root As SyntaxNode, declaration As SyntaxNode, newDeclarations As IEnumerable(Of SyntaxNode)) As SyntaxNode If root.Span.Contains(declaration.Span) Then Return Isolate(root.TrackNodes(declaration), Function(r) InsertDeclarationsBeforeInternal(r, r.GetCurrentNode(declaration), newDeclarations)) Else Return MyBase.InsertNodesBefore(root, declaration, newDeclarations) End If End Function Private Function InsertDeclarationsBeforeInternal(root As SyntaxNode, declaration As SyntaxNode, newDeclarations As IEnumerable(Of SyntaxNode)) As SyntaxNode Dim fullDecl = Me.GetFullDeclaration(declaration) If fullDecl Is declaration OrElse GetDeclarationCount(fullDecl) = 1 Then Return MyBase.InsertNodesBefore(root, declaration, newDeclarations) End If Dim subDecls = GetSubDeclarations(fullDecl) Dim count = subDecls.Count Dim index = MyBase.IndexOf(subDecls, declaration) ' insert New declaration between full declaration split into two If index > 0 Then Return ReplaceRange(root, fullDecl, SplitAndInsert(fullDecl, subDecls, index, newDeclarations)) End If Return MyBase.InsertNodesBefore(root, fullDecl, newDeclarations) End Function Public Overrides Function InsertNodesAfter(root As SyntaxNode, declaration As SyntaxNode, newDeclarations As IEnumerable(Of SyntaxNode)) As SyntaxNode If root.Span.Contains(declaration.Span) Then Return Isolate(root.TrackNodes(declaration), Function(r) InsertNodesAfterInternal(r, r.GetCurrentNode(declaration), newDeclarations)) Else Return MyBase.InsertNodesAfter(root, declaration, newDeclarations) End If End Function Private Function InsertNodesAfterInternal(root As SyntaxNode, declaration As SyntaxNode, newDeclarations As IEnumerable(Of SyntaxNode)) As SyntaxNode Dim fullDecl = Me.GetFullDeclaration(declaration) If fullDecl Is declaration OrElse GetDeclarationCount(fullDecl) = 1 Then Return MyBase.InsertNodesAfter(root, declaration, newDeclarations) End If Dim subDecls = GetSubDeclarations(fullDecl) Dim count = subDecls.Count Dim index = MyBase.IndexOf(subDecls, declaration) ' insert New declaration between full declaration split into two If index >= 0 AndAlso index < count - 1 Then Return ReplaceRange(root, fullDecl, SplitAndInsert(fullDecl, subDecls, index + 1, newDeclarations)) End If Return MyBase.InsertNodesAfter(root, fullDecl, newDeclarations) End Function Private Function SplitAndInsert(multiPartDeclaration As SyntaxNode, subDeclarations As IReadOnlyList(Of SyntaxNode), index As Integer, newDeclarations As IEnumerable(Of SyntaxNode)) As IEnumerable(Of SyntaxNode) Dim count = subDeclarations.Count Dim newNodes = New List(Of SyntaxNode)() newNodes.Add(Me.WithSubDeclarationsRemoved(multiPartDeclaration, index, count - index).WithTrailingTrivia(SyntaxFactory.ElasticSpace)) newNodes.AddRange(newDeclarations) newNodes.Add(Me.WithSubDeclarationsRemoved(multiPartDeclaration, 0, index).WithLeadingTrivia(SyntaxFactory.ElasticSpace)) Return newNodes End Function ' replaces sub-declaration by splitting multi-part declaration first Private Function ReplaceSubDeclaration(root As SyntaxNode, declaration As SyntaxNode, index As Integer, newDeclaration As SyntaxNode) As SyntaxNode Dim newNodes = New List(Of SyntaxNode)() Dim count = GetDeclarationCount(declaration) If index >= 0 AndAlso index < count Then If (index > 0) Then ' make a single declaration with only the sub-declarations before the sub-declaration being replaced newNodes.Add(Me.WithSubDeclarationsRemoved(declaration, index, count - index).WithTrailingTrivia(SyntaxFactory.ElasticSpace)) End If newNodes.Add(newDeclaration) If (index < count - 1) Then ' make a single declaration with only the sub-declarations after the sub-declaration being replaced newNodes.Add(Me.WithSubDeclarationsRemoved(declaration, 0, index + 1).WithLeadingTrivia(SyntaxFactory.ElasticSpace)) End If ' replace declaration with multiple declarations Return ReplaceRange(root, declaration, newNodes) Else Return root End If End Function Private Function WithSubDeclarationsRemoved(declaration As SyntaxNode, index As Integer, count As Integer) As SyntaxNode Return Me.RemoveNodes(declaration, GetSubDeclarations(declaration).Skip(index).Take(count)) End Function Private Shared Function GetSubDeclarations(declaration As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Select Case declaration.Kind Case SyntaxKind.FieldDeclaration Return DirectCast(declaration, FieldDeclarationSyntax).Declarators.SelectMany(Function(d) d.Names).ToBoxedImmutableArray() Case SyntaxKind.LocalDeclarationStatement Return DirectCast(declaration, LocalDeclarationStatementSyntax).Declarators.SelectMany(Function(d) d.Names).ToBoxedImmutableArray() Case SyntaxKind.AttributeList Return DirectCast(declaration, AttributeListSyntax).Attributes Case SyntaxKind.ImportsStatement Return DirectCast(declaration, ImportsStatementSyntax).ImportsClauses Case Else Return SpecializedCollections.EmptyReadOnlyList(Of SyntaxNode) End Select End Function Private Function Flatten(members As IReadOnlyList(Of SyntaxNode)) As IReadOnlyList(Of SyntaxNode) Dim builder = ArrayBuilder(Of SyntaxNode).GetInstance() Flatten(builder, members) Return builder.ToImmutableAndFree() End Function Private Sub Flatten(builder As ArrayBuilder(Of SyntaxNode), members As IReadOnlyList(Of SyntaxNode)) For Each member In members If GetDeclarationCount(member) > 1 Then Select Case member.Kind Case SyntaxKind.FieldDeclaration Flatten(builder, DirectCast(member, FieldDeclarationSyntax).Declarators) Case SyntaxKind.LocalDeclarationStatement Flatten(builder, DirectCast(member, LocalDeclarationStatementSyntax).Declarators) Case SyntaxKind.VariableDeclarator Flatten(builder, DirectCast(member, VariableDeclaratorSyntax).Names) Case SyntaxKind.AttributesStatement Flatten(builder, DirectCast(member, AttributesStatementSyntax).AttributeLists) Case SyntaxKind.AttributeList Flatten(builder, DirectCast(member, AttributeListSyntax).Attributes) Case SyntaxKind.ImportsStatement Flatten(builder, DirectCast(member, ImportsStatementSyntax).ImportsClauses) Case Else builder.Add(member) End Select Else builder.Add(member) End If Next End Sub Public Overrides Function RemoveNode(root As SyntaxNode, declaration As SyntaxNode) As SyntaxNode Return RemoveNode(root, declaration, DefaultRemoveOptions) End Function Public Overrides Function RemoveNode(root As SyntaxNode, declaration As SyntaxNode, options As SyntaxRemoveOptions) As SyntaxNode If root.Span.Contains(declaration.Span) Then Return Isolate(root.TrackNodes(declaration), Function(r) Me.RemoveNodeInternal(r, r.GetCurrentNode(declaration), options)) Else Return MyBase.RemoveNode(root, declaration, options) End If End Function Private Function RemoveNodeInternal(root As SyntaxNode, node As SyntaxNode, options As SyntaxRemoveOptions) As SyntaxNode ' special case handling for nodes that remove their parents too Select Case node.Kind Case SyntaxKind.ModifiedIdentifier Dim vd = TryCast(node.Parent, VariableDeclaratorSyntax) If vd IsNot Nothing AndAlso vd.Names.Count = 1 Then ' remove entire variable declarator if only name Return RemoveNodeInternal(root, vd, options) End If Case SyntaxKind.VariableDeclarator If IsChildOfVariableDeclaration(node) AndAlso GetDeclarationCount(node.Parent) = 1 Then ' remove entire parent declaration if this is the only declarator Return RemoveNodeInternal(root, node.Parent, options) End If Case SyntaxKind.AttributeList Dim attrList = DirectCast(node, AttributeListSyntax) Dim attrStmt = TryCast(attrList.Parent, AttributesStatementSyntax) If attrStmt IsNot Nothing AndAlso attrStmt.AttributeLists.Count = 1 Then ' remove entire attribute statement if this is the only attribute list Return RemoveNodeInternal(root, attrStmt, options) End If Case SyntaxKind.Attribute Dim attrList = TryCast(node.Parent, AttributeListSyntax) If attrList IsNot Nothing AndAlso attrList.Attributes.Count = 1 Then ' remove entire attribute list if this is the only attribute Return RemoveNodeInternal(root, attrList, options) End If Case SyntaxKind.SimpleArgument If IsChildOf(node, SyntaxKind.ArgumentList) AndAlso IsChildOf(node.Parent, SyntaxKind.Attribute) Then Dim argList = DirectCast(node.Parent, ArgumentListSyntax) If argList.Arguments.Count = 1 Then ' remove attribute's arg list if this is the only argument Return RemoveNodeInternal(root, argList, options) End If End If Case SyntaxKind.SimpleImportsClause, SyntaxKind.XmlNamespaceImportsClause Dim imps = DirectCast(node.Parent, ImportsStatementSyntax) If imps.ImportsClauses.Count = 1 Then ' remove entire imports statement if this is the only clause Return RemoveNodeInternal(root, node.Parent, options) End If Case Else Dim parent = node.Parent If parent IsNot Nothing Then Select Case parent.Kind Case SyntaxKind.ImplementsStatement Dim imp = DirectCast(parent, ImplementsStatementSyntax) If imp.Types.Count = 1 Then Return RemoveNodeInternal(root, parent, options) End If Case SyntaxKind.InheritsStatement Dim inh = DirectCast(parent, InheritsStatementSyntax) If inh.Types.Count = 1 Then Return RemoveNodeInternal(root, parent, options) End If End Select End If End Select ' do it the normal way Return root.RemoveNode(node, options) End Function Friend Overrides Function IdentifierName(identifier As SyntaxToken) As SyntaxNode Return SyntaxFactory.IdentifierName(identifier) End Function Friend Overrides Function NamedAnonymousObjectMemberDeclarator(identifier As SyntaxNode, expression As SyntaxNode) As SyntaxNode Return SyntaxFactory.NamedFieldInitializer( DirectCast(identifier, IdentifierNameSyntax), DirectCast(expression, ExpressionSyntax)) End Function Friend Overrides Function IsRegularOrDocComment(trivia As SyntaxTrivia) As Boolean Return trivia.IsRegularOrDocComment() End Function Friend Overrides Function RemoveAllComments(node As SyntaxNode) As SyntaxNode Return RemoveLeadingAndTrailingComments(node) End Function Friend Overrides Function RemoveCommentLines(syntaxList As SyntaxTriviaList) As SyntaxTriviaList Return syntaxList.Where(Function(s) Not IsRegularOrDocComment(s)).ToSyntaxTriviaList() End Function #End Region End Class End Namespace
-1
dotnet/roslyn
56,011
React to string comparison changing on .NET Core
The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
jaredpar
"2021-08-30T17:18:52Z"
"2021-08-30T20:20:04Z"
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
4d99cda6e446e77dbb302e26388c1093bd3ef569
React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
./src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenTuples.vb
' 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.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 Imports Roslyn.Test.Utilities.TestMetadata 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 &lt;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 &lt;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) Assert.True(DirectCast(mFirst, IFieldSymbol).IsExplicitlyNamedTupleElement) 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) Assert.False(DirectCast(mItem1, IFieldSymbol).IsExplicitlyNamedTupleElement) 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 &lt;System.Runtime.CompilerServices.Extension()&gt; 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 = CreateCompilationWithMscorlib45AndVBRuntime( <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 &lt;System.Runtime.CompilerServices.Extension()&gt; Public Function A(self As (Integer, Action)) As String Return Nothing End Function End Module </file> </compilation>, references:={ValueTupleRef, Net451.SystemRuntime, Net451.SystemCore}, 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 &lt;System.Runtime.CompilerServices.Extension()&gt; 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 = CreateCompilationWithMscorlib45AndVBRuntime(source, references:={ValueTupleRef, Net451.SystemRuntime, Net451.SystemCore}, 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, allReferences:={ValueTupleRef, Net451.mscorlib, Net451.SystemCore, Net451.SystemRuntime, Net451.MicrosoftVisualBasic}, 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 &lt;System.Runtime.CompilerServices.Extension()&gt; 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 &lt;System.Runtime.CompilerServices.Extension()&gt; 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) Assert.False(DirectCast(m3Item8, IFieldSymbol).IsExplicitlyNamedTupleElement) 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) Assert.False(DirectCast(m4Item8, IFieldSymbol).IsExplicitlyNamedTupleElement) 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) Assert.True(DirectCast(m4h4, IFieldSymbol).IsExplicitlyNamedTupleElement) 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.True(DirectCast(m5Item8, IFieldSymbol).IsExplicitlyNamedTupleElement) 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.False(DirectCast(m8Item8, IFieldSymbol).IsExplicitlyNamedTupleElement) 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.True(DirectCast(m8Item1, IFieldSymbol).IsExplicitlyNamedTupleElement) 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.False(DirectCast(m1Item1, IFieldSymbol).IsExplicitlyNamedTupleElement) 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.False(DirectCast(m2Item1, IFieldSymbol).IsExplicitlyNamedTupleElement) 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.True(DirectCast(m2a2, IFieldSymbol).IsExplicitlyNamedTupleElement) 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 &lt; _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: " &amp; temp.key) Console.WriteLine("val: " &amp; temp.val) Dim c2 = New C2(Of Test2)(New Test2()) Dim temp2 = c2.Get.Get Console.WriteLine(temp2) Console.WriteLine("key: " &amp; temp2.key) Console.WriteLine("val: " &amp; 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: " &amp; temp4.key) Console.WriteLine("val: " &amp; 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}) Dim found = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2) Assert.False(found.IsErrorType()) Assert.Equal("corlib", found.ContainingAssembly.Name) 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.NotEqual(underlyingType, type) Assert.True(type.Equals(underlyingType, TypeCompareKind.AllIgnoreOptions)) Assert.True(underlyingType.Equals(type, TypeCompareKind.AllIgnoreOptions)) Assert.False(type.Equals(underlyingType, TypeCompareKind.ConsiderEverything)) Assert.False(underlyingType.Equals(type, TypeCompareKind.ConsiderEverything)) Assert.True(DirectCast(type, Symbol).Equals(underlyingType, TypeCompareKind.AllIgnoreOptions)) Assert.True(DirectCast(underlyingType, Symbol).Equals(type, TypeCompareKind.AllIgnoreOptions)) Assert.False(DirectCast(type, Symbol).Equals(underlyingType, TypeCompareKind.ConsiderEverything)) Assert.False(DirectCast(underlyingType, Symbol).Equals(type, 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
' 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.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 Imports Roslyn.Test.Utilities.TestMetadata 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 &lt;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 &lt;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) Assert.True(DirectCast(mFirst, IFieldSymbol).IsExplicitlyNamedTupleElement) 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) Assert.False(DirectCast(mItem1, IFieldSymbol).IsExplicitlyNamedTupleElement) 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 &lt;System.Runtime.CompilerServices.Extension()&gt; 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 = CreateCompilationWithMscorlib45AndVBRuntime( <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 &lt;System.Runtime.CompilerServices.Extension()&gt; Public Function A(self As (Integer, Action)) As String Return Nothing End Function End Module </file> </compilation>, references:={ValueTupleRef, Net451.SystemRuntime, Net451.SystemCore}, 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 &lt;System.Runtime.CompilerServices.Extension()&gt; 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 = CreateCompilationWithMscorlib45AndVBRuntime(source, references:={ValueTupleRef, Net451.SystemRuntime, Net451.SystemCore}, 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, allReferences:={ValueTupleRef, Net451.mscorlib, Net451.SystemCore, Net451.SystemRuntime, Net451.MicrosoftVisualBasic}, 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 &lt;System.Runtime.CompilerServices.Extension()&gt; 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 &lt;System.Runtime.CompilerServices.Extension()&gt; 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) Assert.False(DirectCast(m3Item8, IFieldSymbol).IsExplicitlyNamedTupleElement) 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) Assert.False(DirectCast(m4Item8, IFieldSymbol).IsExplicitlyNamedTupleElement) 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) Assert.True(DirectCast(m4h4, IFieldSymbol).IsExplicitlyNamedTupleElement) 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.True(DirectCast(m5Item8, IFieldSymbol).IsExplicitlyNamedTupleElement) 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.False(DirectCast(m8Item8, IFieldSymbol).IsExplicitlyNamedTupleElement) 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.True(DirectCast(m8Item1, IFieldSymbol).IsExplicitlyNamedTupleElement) 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.False(DirectCast(m1Item1, IFieldSymbol).IsExplicitlyNamedTupleElement) 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.False(DirectCast(m2Item1, IFieldSymbol).IsExplicitlyNamedTupleElement) 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.True(DirectCast(m2a2, IFieldSymbol).IsExplicitlyNamedTupleElement) 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 &lt; _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: " &amp; temp.key) Console.WriteLine("val: " &amp; temp.val) Dim c2 = New C2(Of Test2)(New Test2()) Dim temp2 = c2.Get.Get Console.WriteLine(temp2) Console.WriteLine("key: " &amp; temp2.key) Console.WriteLine("val: " &amp; 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: " &amp; temp4.key) Console.WriteLine("val: " &amp; 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}) Dim found = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2) Assert.False(found.IsErrorType()) Assert.Equal("corlib", found.ContainingAssembly.Name) 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.NotEqual(underlyingType, type) Assert.True(type.Equals(underlyingType, TypeCompareKind.AllIgnoreOptions)) Assert.True(underlyingType.Equals(type, TypeCompareKind.AllIgnoreOptions)) Assert.False(type.Equals(underlyingType, TypeCompareKind.ConsiderEverything)) Assert.False(underlyingType.Equals(type, TypeCompareKind.ConsiderEverything)) Assert.True(DirectCast(type, Symbol).Equals(underlyingType, TypeCompareKind.AllIgnoreOptions)) Assert.True(DirectCast(underlyingType, Symbol).Equals(type, TypeCompareKind.AllIgnoreOptions)) Assert.False(DirectCast(type, Symbol).Equals(underlyingType, TypeCompareKind.ConsiderEverything)) Assert.False(DirectCast(underlyingType, Symbol).Equals(type, 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
-1
dotnet/roslyn
56,011
React to string comparison changing on .NET Core
The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
jaredpar
"2021-08-30T17:18:52Z"
"2021-08-30T20:20:04Z"
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
4d99cda6e446e77dbb302e26388c1093bd3ef569
React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/Extensions/SimpleNameSyntaxExtensions.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Runtime.CompilerServices Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Extensions Friend Module SimpleNameSyntaxExtensions <Extension()> Public Function GetLeftSideOfDot(name As SimpleNameSyntax) As ExpressionSyntax Debug.Assert(IsSimpleMemberAccessExpressionName(name) OrElse IsRightSideOfQualifiedName(name)) If IsSimpleMemberAccessExpressionName(name) Then Return DirectCast(name.Parent, MemberAccessExpressionSyntax).Expression Else Return DirectCast(name.Parent, QualifiedNameSyntax).Left End If End Function ' Returns true if this looks like a possible type name that is on it's own (i.e. not after a ' dot). This function is not exhaustive and additional checks may be added if they are ' believed to be valuable. <Extension()> Public Function LooksLikeStandaloneTypeName(simpleName As SimpleNameSyntax) As Boolean If simpleName Is Nothing Then Return False End If ' Isn't stand-alone if it's on the right of a dot/arrow If simpleName.IsRightSideOfDot() Then Return False End If ' type names can't be invoked. If simpleName.IsParentKind(SyntaxKind.InvocationExpression) Then Dim invocationExpression = DirectCast(simpleName.Parent, InvocationExpressionSyntax) If invocationExpression.Expression Is simpleName AndAlso invocationExpression.ArgumentList IsNot Nothing Then Return False End If End If ' Looks good. However, feel free to add additional checks if this function is too ' lenient in some circumstances. Return True End Function End Module End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Runtime.CompilerServices Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Extensions Friend Module SimpleNameSyntaxExtensions <Extension()> Public Function GetLeftSideOfDot(name As SimpleNameSyntax) As ExpressionSyntax Debug.Assert(IsSimpleMemberAccessExpressionName(name) OrElse IsRightSideOfQualifiedName(name)) If IsSimpleMemberAccessExpressionName(name) Then Return DirectCast(name.Parent, MemberAccessExpressionSyntax).Expression Else Return DirectCast(name.Parent, QualifiedNameSyntax).Left End If End Function ' Returns true if this looks like a possible type name that is on it's own (i.e. not after a ' dot). This function is not exhaustive and additional checks may be added if they are ' believed to be valuable. <Extension()> Public Function LooksLikeStandaloneTypeName(simpleName As SimpleNameSyntax) As Boolean If simpleName Is Nothing Then Return False End If ' Isn't stand-alone if it's on the right of a dot/arrow If simpleName.IsRightSideOfDot() Then Return False End If ' type names can't be invoked. If simpleName.IsParentKind(SyntaxKind.InvocationExpression) Then Dim invocationExpression = DirectCast(simpleName.Parent, InvocationExpressionSyntax) If invocationExpression.Expression Is simpleName AndAlso invocationExpression.ArgumentList IsNot Nothing Then Return False End If End If ' Looks good. However, feel free to add additional checks if this function is too ' lenient in some circumstances. Return True End Function End Module End Namespace
-1
dotnet/roslyn
56,011
React to string comparison changing on .NET Core
The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
jaredpar
"2021-08-30T17:18:52Z"
"2021-08-30T20:20:04Z"
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
4d99cda6e446e77dbb302e26388c1093bd3ef569
React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/Extensions/ExpressionSyntaxExtensions.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Runtime.CompilerServices Imports System.Runtime.InteropServices Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Simplification Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.Extensions Friend Module ExpressionSyntaxExtensions Public ReadOnly typeNameFormatWithGenerics As New SymbolDisplayFormat( globalNamespaceStyle:=SymbolDisplayGlobalNamespaceStyle.Included, genericsOptions:=SymbolDisplayGenericsOptions.IncludeTypeParameters, memberOptions:=SymbolDisplayMemberOptions.IncludeContainingType, localOptions:=SymbolDisplayLocalOptions.IncludeType, miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers, typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces) Public ReadOnly typeNameFormatWithoutGenerics As New SymbolDisplayFormat( globalNamespaceStyle:=SymbolDisplayGlobalNamespaceStyle.Included, genericsOptions:=SymbolDisplayGenericsOptions.None, memberOptions:=SymbolDisplayMemberOptions.IncludeContainingType, localOptions:=SymbolDisplayLocalOptions.IncludeType, miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers, typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces) <Extension()> Public Function Parenthesize(expression As ExpressionSyntax, Optional addSimplifierAnnotation As Boolean = True) As ParenthesizedExpressionSyntax Dim result = SyntaxFactory.ParenthesizedExpression(expression.WithoutTrivia()) _ .WithTriviaFrom(expression) Return If(addSimplifierAnnotation, result.WithAdditionalAnnotations(Simplifier.Annotation), result) End Function <Extension()> Public Function TryGetNameParts(expression As ExpressionSyntax, ByRef parts As IList(Of String)) As Boolean Dim partsList = New List(Of String) If Not expression.TryGetNameParts(partsList) Then parts = Nothing Return False End If parts = partsList Return True End Function <Extension()> Public Function TryGetNameParts(expression As ExpressionSyntax, parts As List(Of String)) As Boolean If expression.IsKind(SyntaxKind.SimpleMemberAccessExpression) Then Dim memberAccess = DirectCast(expression, MemberAccessExpressionSyntax) If Not memberAccess.Name.TryGetNameParts(parts) Then Return False End If Return AddSimpleName(memberAccess.Name, parts) ElseIf expression.IsKind(SyntaxKind.QualifiedName) Then Dim qualifiedName = DirectCast(expression, QualifiedNameSyntax) If Not qualifiedName.Left.TryGetNameParts(parts) Then Return False End If Return AddSimpleName(qualifiedName.Right, parts) ElseIf TypeOf expression Is SimpleNameSyntax Then Return AddSimpleName(DirectCast(expression, SimpleNameSyntax), parts) Else Return False End If End Function Private Function AddSimpleName(simpleName As SimpleNameSyntax, parts As List(Of String)) As Boolean If Not simpleName.IsKind(SyntaxKind.IdentifierName) Then Return False End If parts.Add(simpleName.Identifier.ValueText) Return True End Function <Extension()> Public Function Cast( expression As ExpressionSyntax, targetType As ITypeSymbol, <Out> ByRef isResultPredefinedCast As Boolean) As ExpressionSyntax ' Parenthesize the expression, except for collection initializers and interpolated strings, ' where parenthesizing changes semantics. Dim newExpression = expression If Not expression.IsKind(SyntaxKind.CollectionInitializer, SyntaxKind.InterpolatedStringExpression) Then newExpression = expression.Parenthesize() End If Dim leadingTrivia = newExpression.GetLeadingTrivia() Dim trailingTrivia = newExpression.GetTrailingTrivia() Dim stripped = newExpression.WithoutLeadingTrivia().WithoutTrailingTrivia() Dim castKeyword = targetType.SpecialType.GetPredefinedCastKeyword() If castKeyword = SyntaxKind.None Then isResultPredefinedCast = False Return SyntaxFactory.CTypeExpression( expression:=stripped, type:=targetType.GenerateTypeSyntax()) _ .WithLeadingTrivia(leadingTrivia) _ .WithTrailingTrivia(trailingTrivia) _ .WithAdditionalAnnotations(Simplifier.Annotation) Else isResultPredefinedCast = True Return SyntaxFactory.PredefinedCastExpression( keyword:=SyntaxFactory.Token(castKeyword), expression:=stripped) _ .WithLeadingTrivia(leadingTrivia) _ .WithTrailingTrivia(trailingTrivia) _ .WithAdditionalAnnotations(Simplifier.Annotation) End If End Function <Extension()> Public Function CastIfPossible( expression As ExpressionSyntax, targetType As ITypeSymbol, position As Integer, semanticModel As SemanticModel, <Out> ByRef wasCastAdded As Boolean, cancellationToken As CancellationToken) As ExpressionSyntax wasCastAdded = False If targetType.ContainsAnonymousType() OrElse expression.IsParentKind(SyntaxKind.AsNewClause) Then Return expression End If Dim typeSyntax = targetType.GenerateTypeSyntax() Dim type = semanticModel.GetSpeculativeTypeInfo( position, typeSyntax, SpeculativeBindingOption.BindAsTypeOrNamespace).Type If Not targetType.Equals(type) Then Return expression End If Dim isResultPredefinedCast As Boolean = False Dim castExpression = expression.Cast(targetType, isResultPredefinedCast) ' Ensure that inserting the cast doesn't change the semantics. Dim specAnalyzer = New SpeculationAnalyzer(expression, castExpression, semanticModel, cancellationToken) Dim speculativeSemanticModel = specAnalyzer.SpeculativeSemanticModel If speculativeSemanticModel Is Nothing Then Return expression End If Dim speculatedCastExpression = specAnalyzer.ReplacedExpression Dim speculatedCastInnerExpression = If(isResultPredefinedCast, DirectCast(speculatedCastExpression, PredefinedCastExpressionSyntax).Expression, DirectCast(speculatedCastExpression, CastExpressionSyntax).Expression) If Not CastAnalyzer.IsUnnecessary(speculatedCastExpression, speculatedCastInnerExpression, speculativeSemanticModel, True, cancellationToken) Then Return expression End If wasCastAdded = True Return castExpression End Function <Extension()> Public Function IsObjectCreationWithoutArgumentList(expression As ExpressionSyntax) As Boolean Return _ TypeOf expression Is ObjectCreationExpressionSyntax AndAlso DirectCast(expression, ObjectCreationExpressionSyntax).ArgumentList Is Nothing End Function <Extension()> Public Function IsMeMyBaseOrMyClass(expression As ExpressionSyntax) As Boolean If expression Is Nothing Then Return False End If Return expression.Kind = SyntaxKind.MeExpression OrElse expression.Kind = SyntaxKind.MyBaseExpression OrElse expression.Kind = SyntaxKind.MyClassExpression End Function <Extension()> Public Function IsFirstStatementInCtor(expression As ExpressionSyntax) As Boolean Dim statement = expression.FirstAncestorOrSelf(Of StatementSyntax)() If statement Is Nothing Then Return False End If If Not statement.IsParentKind(SyntaxKind.ConstructorBlock) Then Return False End If Return DirectCast(statement.Parent, ConstructorBlockSyntax).Statements(0) Is statement End Function <Extension()> Public Function IsNamedArgumentIdentifier(expression As ExpressionSyntax) As Boolean Dim simpleArgument = TryCast(expression.Parent, SimpleArgumentSyntax) Return simpleArgument IsNot Nothing AndAlso simpleArgument.NameColonEquals.Name Is expression End Function <Extension> Public Function ContainsImplicitMemberAccess(expression As ExpressionSyntax) As Boolean Return ContainsImplicitMemberAccessWorker(expression) End Function <Extension> Public Function ContainsImplicitMemberAccess(statement As StatementSyntax) As Boolean Return ContainsImplicitMemberAccessWorker(statement) End Function <Extension> Public Function GetImplicitMemberAccessExpressions(expression As SyntaxNode, span As TextSpan) As IEnumerable(Of ExpressionSyntax) ' We don't want to allow a variable to be introduced if the expression contains an ' implicit member access. i.e. ".Blah.ToString()" as that .Blah refers to the containing ' object creation or anonymous type and we can't make a local for it. So we get all the ' descendants and we suppress ourselves. ' Note: if we hit a with block or an anonymous type, then we do not look deeper. Any ' implicit member accesses will refer to that thing and we *can* introduce a variable Dim descendentExpressions = expression.DescendantNodesAndSelf().OfType(Of ExpressionSyntax).Where(Function(e) span.Contains(e.Span)).ToSet() Return descendentExpressions.OfType(Of MemberAccessExpressionSyntax). Select(Function(m) m.GetExpressionOfMemberAccessExpression(allowImplicitTarget:=True)). Where(Function(e) Not descendentExpressions.Contains(e)) End Function <Extension> Public Function GetImplicitMemberAccessExpressions(expression As SyntaxNode) As IEnumerable(Of ExpressionSyntax) Return GetImplicitMemberAccessExpressions(expression, expression.FullSpan) End Function Private Function ContainsImplicitMemberAccessWorker(expression As SyntaxNode) As Boolean Return GetImplicitMemberAccessExpressions(expression).Any() End Function <Extension> Public Function InsideCrefReference(expression As ExpressionSyntax) As Boolean Dim crefAttribute = expression.FirstAncestorOrSelf(Of XmlCrefAttributeSyntax)() Return crefAttribute IsNot Nothing End Function <Extension> Public Function IsDirectChildOfMemberAccessExpression(expression As ExpressionSyntax) As Boolean Return TypeOf expression?.Parent Is MemberAccessExpressionSyntax End Function <Extension> Public Function GetRightmostName(node As ExpressionSyntax) As SimpleNameSyntax Dim memberAccess = TryCast(node, MemberAccessExpressionSyntax) If memberAccess IsNot Nothing AndAlso memberAccess.Name IsNot Nothing Then Return memberAccess.Name End If Dim qualified = TryCast(node, QualifiedNameSyntax) If qualified IsNot Nothing AndAlso qualified.Right IsNot Nothing Then Return qualified.Right End If Return TryCast(node, SimpleNameSyntax) End Function <Extension> Public Function IsNameOfArgumentExpression(expression As ExpressionSyntax) As Boolean Return expression.IsParentKind(SyntaxKind.NameOfExpression) End Function Public Function IsReservedNameInAttribute(originalName As NameSyntax, simplifiedNode As ExpressionSyntax) As Boolean Dim attribute = originalName.GetAncestorOrThis(Of AttributeSyntax)() If attribute Is Nothing Then Return False End If Dim identifier As SimpleNameSyntax If simplifiedNode.Kind = SyntaxKind.IdentifierName Then identifier = DirectCast(simplifiedNode, SimpleNameSyntax) ElseIf simplifiedNode.Kind = SyntaxKind.QualifiedName Then identifier = DirectCast(DirectCast(simplifiedNode, QualifiedNameSyntax).Left, SimpleNameSyntax) Else Return False End If If identifier.Identifier.IsBracketed Then Return False End If If attribute.Target Is Nothing Then Dim identifierValue = SyntaxFacts.MakeHalfWidthIdentifier(identifier.Identifier.ValueText) If CaseInsensitiveComparison.Equals(identifierValue, "Assembly") OrElse CaseInsensitiveComparison.Equals(identifierValue, "Module") Then Return True End If End If Return False End Function End Module End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Runtime.CompilerServices Imports System.Runtime.InteropServices Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Simplification Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.Extensions Friend Module ExpressionSyntaxExtensions Public ReadOnly typeNameFormatWithGenerics As New SymbolDisplayFormat( globalNamespaceStyle:=SymbolDisplayGlobalNamespaceStyle.Included, genericsOptions:=SymbolDisplayGenericsOptions.IncludeTypeParameters, memberOptions:=SymbolDisplayMemberOptions.IncludeContainingType, localOptions:=SymbolDisplayLocalOptions.IncludeType, miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers, typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces) Public ReadOnly typeNameFormatWithoutGenerics As New SymbolDisplayFormat( globalNamespaceStyle:=SymbolDisplayGlobalNamespaceStyle.Included, genericsOptions:=SymbolDisplayGenericsOptions.None, memberOptions:=SymbolDisplayMemberOptions.IncludeContainingType, localOptions:=SymbolDisplayLocalOptions.IncludeType, miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers, typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces) <Extension()> Public Function Parenthesize(expression As ExpressionSyntax, Optional addSimplifierAnnotation As Boolean = True) As ParenthesizedExpressionSyntax Dim result = SyntaxFactory.ParenthesizedExpression(expression.WithoutTrivia()) _ .WithTriviaFrom(expression) Return If(addSimplifierAnnotation, result.WithAdditionalAnnotations(Simplifier.Annotation), result) End Function <Extension()> Public Function TryGetNameParts(expression As ExpressionSyntax, ByRef parts As IList(Of String)) As Boolean Dim partsList = New List(Of String) If Not expression.TryGetNameParts(partsList) Then parts = Nothing Return False End If parts = partsList Return True End Function <Extension()> Public Function TryGetNameParts(expression As ExpressionSyntax, parts As List(Of String)) As Boolean If expression.IsKind(SyntaxKind.SimpleMemberAccessExpression) Then Dim memberAccess = DirectCast(expression, MemberAccessExpressionSyntax) If Not memberAccess.Name.TryGetNameParts(parts) Then Return False End If Return AddSimpleName(memberAccess.Name, parts) ElseIf expression.IsKind(SyntaxKind.QualifiedName) Then Dim qualifiedName = DirectCast(expression, QualifiedNameSyntax) If Not qualifiedName.Left.TryGetNameParts(parts) Then Return False End If Return AddSimpleName(qualifiedName.Right, parts) ElseIf TypeOf expression Is SimpleNameSyntax Then Return AddSimpleName(DirectCast(expression, SimpleNameSyntax), parts) Else Return False End If End Function Private Function AddSimpleName(simpleName As SimpleNameSyntax, parts As List(Of String)) As Boolean If Not simpleName.IsKind(SyntaxKind.IdentifierName) Then Return False End If parts.Add(simpleName.Identifier.ValueText) Return True End Function <Extension()> Public Function Cast( expression As ExpressionSyntax, targetType As ITypeSymbol, <Out> ByRef isResultPredefinedCast As Boolean) As ExpressionSyntax ' Parenthesize the expression, except for collection initializers and interpolated strings, ' where parenthesizing changes semantics. Dim newExpression = expression If Not expression.IsKind(SyntaxKind.CollectionInitializer, SyntaxKind.InterpolatedStringExpression) Then newExpression = expression.Parenthesize() End If Dim leadingTrivia = newExpression.GetLeadingTrivia() Dim trailingTrivia = newExpression.GetTrailingTrivia() Dim stripped = newExpression.WithoutLeadingTrivia().WithoutTrailingTrivia() Dim castKeyword = targetType.SpecialType.GetPredefinedCastKeyword() If castKeyword = SyntaxKind.None Then isResultPredefinedCast = False Return SyntaxFactory.CTypeExpression( expression:=stripped, type:=targetType.GenerateTypeSyntax()) _ .WithLeadingTrivia(leadingTrivia) _ .WithTrailingTrivia(trailingTrivia) _ .WithAdditionalAnnotations(Simplifier.Annotation) Else isResultPredefinedCast = True Return SyntaxFactory.PredefinedCastExpression( keyword:=SyntaxFactory.Token(castKeyword), expression:=stripped) _ .WithLeadingTrivia(leadingTrivia) _ .WithTrailingTrivia(trailingTrivia) _ .WithAdditionalAnnotations(Simplifier.Annotation) End If End Function <Extension()> Public Function CastIfPossible( expression As ExpressionSyntax, targetType As ITypeSymbol, position As Integer, semanticModel As SemanticModel, <Out> ByRef wasCastAdded As Boolean, cancellationToken As CancellationToken) As ExpressionSyntax wasCastAdded = False If targetType.ContainsAnonymousType() OrElse expression.IsParentKind(SyntaxKind.AsNewClause) Then Return expression End If Dim typeSyntax = targetType.GenerateTypeSyntax() Dim type = semanticModel.GetSpeculativeTypeInfo( position, typeSyntax, SpeculativeBindingOption.BindAsTypeOrNamespace).Type If Not targetType.Equals(type) Then Return expression End If Dim isResultPredefinedCast As Boolean = False Dim castExpression = expression.Cast(targetType, isResultPredefinedCast) ' Ensure that inserting the cast doesn't change the semantics. Dim specAnalyzer = New SpeculationAnalyzer(expression, castExpression, semanticModel, cancellationToken) Dim speculativeSemanticModel = specAnalyzer.SpeculativeSemanticModel If speculativeSemanticModel Is Nothing Then Return expression End If Dim speculatedCastExpression = specAnalyzer.ReplacedExpression Dim speculatedCastInnerExpression = If(isResultPredefinedCast, DirectCast(speculatedCastExpression, PredefinedCastExpressionSyntax).Expression, DirectCast(speculatedCastExpression, CastExpressionSyntax).Expression) If Not CastAnalyzer.IsUnnecessary(speculatedCastExpression, speculatedCastInnerExpression, speculativeSemanticModel, True, cancellationToken) Then Return expression End If wasCastAdded = True Return castExpression End Function <Extension()> Public Function IsObjectCreationWithoutArgumentList(expression As ExpressionSyntax) As Boolean Return _ TypeOf expression Is ObjectCreationExpressionSyntax AndAlso DirectCast(expression, ObjectCreationExpressionSyntax).ArgumentList Is Nothing End Function <Extension()> Public Function IsMeMyBaseOrMyClass(expression As ExpressionSyntax) As Boolean If expression Is Nothing Then Return False End If Return expression.Kind = SyntaxKind.MeExpression OrElse expression.Kind = SyntaxKind.MyBaseExpression OrElse expression.Kind = SyntaxKind.MyClassExpression End Function <Extension()> Public Function IsFirstStatementInCtor(expression As ExpressionSyntax) As Boolean Dim statement = expression.FirstAncestorOrSelf(Of StatementSyntax)() If statement Is Nothing Then Return False End If If Not statement.IsParentKind(SyntaxKind.ConstructorBlock) Then Return False End If Return DirectCast(statement.Parent, ConstructorBlockSyntax).Statements(0) Is statement End Function <Extension()> Public Function IsNamedArgumentIdentifier(expression As ExpressionSyntax) As Boolean Dim simpleArgument = TryCast(expression.Parent, SimpleArgumentSyntax) Return simpleArgument IsNot Nothing AndAlso simpleArgument.NameColonEquals.Name Is expression End Function <Extension> Public Function ContainsImplicitMemberAccess(expression As ExpressionSyntax) As Boolean Return ContainsImplicitMemberAccessWorker(expression) End Function <Extension> Public Function ContainsImplicitMemberAccess(statement As StatementSyntax) As Boolean Return ContainsImplicitMemberAccessWorker(statement) End Function <Extension> Public Function GetImplicitMemberAccessExpressions(expression As SyntaxNode, span As TextSpan) As IEnumerable(Of ExpressionSyntax) ' We don't want to allow a variable to be introduced if the expression contains an ' implicit member access. i.e. ".Blah.ToString()" as that .Blah refers to the containing ' object creation or anonymous type and we can't make a local for it. So we get all the ' descendants and we suppress ourselves. ' Note: if we hit a with block or an anonymous type, then we do not look deeper. Any ' implicit member accesses will refer to that thing and we *can* introduce a variable Dim descendentExpressions = expression.DescendantNodesAndSelf().OfType(Of ExpressionSyntax).Where(Function(e) span.Contains(e.Span)).ToSet() Return descendentExpressions.OfType(Of MemberAccessExpressionSyntax). Select(Function(m) m.GetExpressionOfMemberAccessExpression(allowImplicitTarget:=True)). Where(Function(e) Not descendentExpressions.Contains(e)) End Function <Extension> Public Function GetImplicitMemberAccessExpressions(expression As SyntaxNode) As IEnumerable(Of ExpressionSyntax) Return GetImplicitMemberAccessExpressions(expression, expression.FullSpan) End Function Private Function ContainsImplicitMemberAccessWorker(expression As SyntaxNode) As Boolean Return GetImplicitMemberAccessExpressions(expression).Any() End Function <Extension> Public Function InsideCrefReference(expression As ExpressionSyntax) As Boolean Dim crefAttribute = expression.FirstAncestorOrSelf(Of XmlCrefAttributeSyntax)() Return crefAttribute IsNot Nothing End Function <Extension> Public Function IsDirectChildOfMemberAccessExpression(expression As ExpressionSyntax) As Boolean Return TypeOf expression?.Parent Is MemberAccessExpressionSyntax End Function <Extension> Public Function GetRightmostName(node As ExpressionSyntax) As SimpleNameSyntax Dim memberAccess = TryCast(node, MemberAccessExpressionSyntax) If memberAccess IsNot Nothing AndAlso memberAccess.Name IsNot Nothing Then Return memberAccess.Name End If Dim qualified = TryCast(node, QualifiedNameSyntax) If qualified IsNot Nothing AndAlso qualified.Right IsNot Nothing Then Return qualified.Right End If Return TryCast(node, SimpleNameSyntax) End Function <Extension> Public Function IsNameOfArgumentExpression(expression As ExpressionSyntax) As Boolean Return expression.IsParentKind(SyntaxKind.NameOfExpression) End Function Public Function IsReservedNameInAttribute(originalName As NameSyntax, simplifiedNode As ExpressionSyntax) As Boolean Dim attribute = originalName.GetAncestorOrThis(Of AttributeSyntax)() If attribute Is Nothing Then Return False End If Dim identifier As SimpleNameSyntax If simplifiedNode.Kind = SyntaxKind.IdentifierName Then identifier = DirectCast(simplifiedNode, SimpleNameSyntax) ElseIf simplifiedNode.Kind = SyntaxKind.QualifiedName Then identifier = DirectCast(DirectCast(simplifiedNode, QualifiedNameSyntax).Left, SimpleNameSyntax) Else Return False End If If identifier.Identifier.IsBracketed Then Return False End If If attribute.Target Is Nothing Then Dim identifierValue = SyntaxFacts.MakeHalfWidthIdentifier(identifier.Identifier.ValueText) If CaseInsensitiveComparison.Equals(identifierValue, "Assembly") OrElse CaseInsensitiveComparison.Equals(identifierValue, "Module") Then Return True End If End If Return False End Function End Module End Namespace
-1
dotnet/roslyn
56,011
React to string comparison changing on .NET Core
The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
jaredpar
"2021-08-30T17:18:52Z"
"2021-08-30T20:20:04Z"
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
4d99cda6e446e77dbb302e26388c1093bd3ef569
React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
./src/Compilers/VisualBasic/Portable/Symbols/Source/LocalSymbol.vb
' 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.CodeGen Imports Microsoft.CodeAnalysis.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ''' <summary> ''' Represents a local variable (typically inside a method body). This could also be a local variable implicitly ''' declared by a For, Using, etc. When used as a temporary variable, its container can also be a Field or Property Symbol. ''' </summary> Friend MustInherit Class LocalSymbol Inherits Symbol Implements ILocalSymbol, ILocalSymbolInternal Friend Shared ReadOnly UseBeforeDeclarationResultType As ErrorTypeSymbol = New ErrorTypeSymbol() Private ReadOnly _container As Symbol ' the method, field or property that contains the declaration of this variable Private _lazyType As TypeSymbol ''' <summary> ''' Create a local symbol from a local variable declaration. ''' </summary> Friend Shared Function Create(container As Symbol, binder As Binder, declaringIdentifier As SyntaxToken, modifiedIdentifierOpt As ModifiedIdentifierSyntax, asClauseOpt As AsClauseSyntax, initializerOpt As EqualsValueSyntax, declarationKind As LocalDeclarationKind) As LocalSymbol Return New VariableLocalSymbol(container, binder, declaringIdentifier, modifiedIdentifierOpt, asClauseOpt, initializerOpt, declarationKind) End Function ''' <summary> ''' Create a local symbol associated with an identifier token. ''' </summary> Friend Shared Function Create(container As Symbol, binder As Binder, declaringIdentifier As SyntaxToken, declarationKind As LocalDeclarationKind, type As TypeSymbol) As LocalSymbol Return New SourceLocalSymbol(container, binder, declaringIdentifier, declarationKind, type) End Function ''' <summary> ''' Create a local symbol associated with an identifier token and a different name. ''' Used for WinRT event handler return value variable). ''' </summary> Friend Shared Function Create(container As Symbol, binder As Binder, declaringIdentifier As SyntaxToken, declarationKind As LocalDeclarationKind, type As TypeSymbol, name As String) As LocalSymbol Return New SourceLocalSymbolWithNonstandardName(container, binder, declaringIdentifier, declarationKind, type, name) End Function ''' <summary> ''' Create a local symbol with substituted type. ''' </summary> Friend Shared Function Create(originalVariable As LocalSymbol, type As TypeSymbol) As LocalSymbol Return New TypeSubstitutedLocalSymbol(originalVariable, type) End Function ''' <summary> ''' Create an inferred local symbol from a For from-to statement. ''' </summary> Friend Shared Function CreateInferredForFromTo(container As Symbol, binder As Binder, declaringIdentifier As SyntaxToken, fromValue As ExpressionSyntax, toValue As ExpressionSyntax, stepClauseOpt As ForStepClauseSyntax) As LocalSymbol Return New InferredForFromToLocalSymbol(container, binder, declaringIdentifier, fromValue, toValue, stepClauseOpt) End Function ''' <summary> ''' Create an inferred local symbol from a For-each statement. ''' </summary> Friend Shared Function CreateInferredForEach(container As Symbol, binder As Binder, declaringIdentifier As SyntaxToken, expression As ExpressionSyntax) As LocalSymbol Return New InferredForEachLocalSymbol(container, binder, declaringIdentifier, expression) End Function ''' <summary> ''' Create a local variable symbol. Note: this does not insert it automatically into a ''' local binder so that it can be found by lookup. ''' </summary> Friend Sub New(container As Symbol, type As TypeSymbol) Debug.Assert(container IsNot Nothing, "local must belong to a method, field or property") Debug.Assert(container.Kind = SymbolKind.Method OrElse container.Kind = SymbolKind.Field OrElse container.Kind = SymbolKind.Property, "Unsupported container. Must be method, field or property.") _container = container _lazyType = type End Sub Friend Overridable ReadOnly Property IsImportedFromMetadata As Boolean Get Return False End Get End Property Friend MustOverride ReadOnly Property DeclarationKind As LocalDeclarationKind Friend MustOverride ReadOnly Property SynthesizedKind As SynthesizedLocalKind Public Overridable ReadOnly Property Type As TypeSymbol Get If _lazyType Is Nothing Then Interlocked.CompareExchange(_lazyType, ComputeType(), Nothing) End If Return _lazyType End Get End Property Friend ReadOnly Property ConstHasType As Boolean Get Debug.Assert(Me.IsConst) Return Me._lazyType IsNot Nothing End Get End Property ''' <summary> ''' Returns true if this local is a ReadOnly local. Compiler has a concept of ReadOnly locals. ''' </summary> Friend Overridable ReadOnly Property IsReadOnly As Boolean Get ' locals declared in the resource list of a using statement are considered to be read only. Return IsUsing OrElse IsConst End Get End Property ' Set the type of this variable. This is used by the expression binder to set the type of the variable. ' If the type has already been computed, it should have been computed to be the same type. Public Sub SetType(type As TypeSymbol) If _lazyType Is Nothing Then Interlocked.CompareExchange(_lazyType, type, Nothing) Debug.Assert((Me.IsFunctionValue AndAlso _container.Kind = SymbolKind.Method AndAlso DirectCast(_container, MethodSymbol).MethodKind = MethodKind.LambdaMethod) OrElse type.Equals(ComputeType())) Else Debug.Assert(type.Equals(_lazyType), "Attempted to set a local variable with a different type") End If End Sub ' Compute the type of this variable. Friend Overridable Function ComputeType(Optional containingBinder As Binder = Nothing) As TypeSymbol Debug.Assert(_lazyType IsNot Nothing) Return _lazyType End Function Public MustOverride Overrides ReadOnly Property Name As String ' Get the identifier token that defined this local symbol. This is useful for robustly checking ' if a local symbol actually matches a particular definition, even in the presence of duplicates. Friend MustOverride ReadOnly Property IdentifierToken As SyntaxToken ''' <summary> ''' Returns the syntax node that declares the variable. ''' </summary> ''' <remarks> ''' All user-defined and long-lived synthesized variables must return a reference to a node that is ''' tracked by the EnC diffing algorithm. For example, for <see cref="LocalDeclarationKind.Catch"/> variable ''' the declarator is the <see cref="CatchStatementSyntax"/> node, not the <see cref="IdentifierNameSyntax"/> ''' that immediately contains the variable. ''' ''' The location of the declarator is used to calculate <see cref="LocalDebugId.SyntaxOffset"/> during emit. ''' </remarks> Friend MustOverride Function GetDeclaratorSyntax() As SyntaxNode Public NotOverridable Overrides ReadOnly Property Kind As SymbolKind Get Return SymbolKind.Local End Get End Property Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location) Get Return ImmutableArray.Create(Me.IdentifierLocation) End Get End Property Friend MustOverride ReadOnly Property IdentifierLocation As Location Public Overrides ReadOnly Property ContainingSymbol As Symbol Get Return _container End Get End Property Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility Get Return Accessibility.NotApplicable End Get End Property Public Overrides ReadOnly Property IsShared As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsOverridable As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsMustOverride As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsNotOverridable As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsOverrides As Boolean Get Return False End Get End Property Public ReadOnly Property IsUsing As Boolean Get Return Me.DeclarationKind = LocalDeclarationKind.Using End Get End Property Public ReadOnly Property IsCatch As Boolean Get Return Me.DeclarationKind = LocalDeclarationKind.Catch End Get End Property Public ReadOnly Property IsConst As Boolean Get Return Me.DeclarationKind = LocalDeclarationKind.Constant End Get End Property Private ReadOnly Property ILocalSymbol_IsFixed As Boolean Implements ILocalSymbol.IsFixed Get Return False End Get End Property Friend Overridable ReadOnly Property CanScheduleToStack As Boolean Get ' cannot schedule constants and catch variables ' in theory catch vars could be scheduled, but are not worth the trouble. Return Not IsConst AndAlso Not IsCatch End Get End Property Public ReadOnly Property IsStatic As Boolean Get Return Me.DeclarationKind = LocalDeclarationKind.Static End Get End Property Public ReadOnly Property IsFor As Boolean Get Return Me.DeclarationKind = LocalDeclarationKind.For End Get End Property Public ReadOnly Property IsForEach As Boolean Get Return Me.DeclarationKind = LocalDeclarationKind.ForEach End Get End Property Public ReadOnly Property IsRef As Boolean Implements ILocalSymbol.IsRef Get Return False End Get End Property Public ReadOnly Property RefKind As RefKind Implements ILocalSymbol.RefKind Get Return RefKind.None End Get End Property Public MustOverride ReadOnly Property IsFunctionValue As Boolean Implements ILocalSymbol.IsFunctionValue Friend ReadOnly Property IsCompilerGenerated As Boolean Get Return Me.DeclarationKind = LocalDeclarationKind.None End Get End Property ''' <summary> ''' Was this local variable implicitly declared, because Option Explicit Off ''' was in effect, and no other symbol was found with this name. ''' </summary> Public Overrides ReadOnly Property IsImplicitlyDeclared As Boolean Get Return Me.DeclarationKind = LocalDeclarationKind.ImplicitVariable End Get End Property Friend Overrides Function Accept(Of TArgument, TResult)(visitor As VisualBasicSymbolVisitor(Of TArgument, TResult), arg As TArgument) As TResult Return visitor.VisitLocal(Me, arg) End Function Friend Overridable ReadOnly Property IsByRef As Boolean Get Return False End Get End Property Friend Overridable ReadOnly Property IsPinned As Boolean Get Return False End Get End Property Public ReadOnly Property HasConstantValue As Boolean Implements ILocalSymbol.HasConstantValue Get If Not Me.IsConst Then Return Nothing End If Return GetConstantValue(Nothing) IsNot Nothing End Get End Property Public ReadOnly Property ConstantValue As Object Implements ILocalSymbol.ConstantValue Get If Not Me.IsConst Then Return Nothing End If Dim constant As ConstantValue = Me.GetConstantValue(Nothing) Return If(constant Is Nothing, Nothing, constant.Value) End Get End Property Friend Overridable Function GetConstantValueDiagnostics(binder As Binder) As BindingDiagnosticBag Throw ExceptionUtilities.Unreachable End Function Friend Overridable Function GetConstantExpression(binder As Binder) As BoundExpression Throw ExceptionUtilities.Unreachable End Function Friend Overridable Function GetConstantValue(binder As Binder) As ConstantValue Return Nothing End Function Friend Overridable ReadOnly Property HasInferredType As Boolean Get Return False 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 #Region "ILocalSymbol" Private ReadOnly Property ILocalSymbol_Type As ITypeSymbol Implements ILocalSymbol.Type Get Return Me.Type End Get End Property Private ReadOnly Property ILocalSymbol_NullableAnnotation As NullableAnnotation Implements ILocalSymbol.NullableAnnotation Get Return NullableAnnotation.None End Get End Property Private ReadOnly Property ILocalSymbol_IsConst As Boolean Implements ILocalSymbol.IsConst Get Return Me.IsConst End Get End Property #End Region #Region "ISymbol" Protected Overrides ReadOnly Property ISymbol_IsStatic As Boolean Get Return Me.IsStatic End Get End Property Public Overrides Sub Accept(visitor As SymbolVisitor) visitor.VisitLocal(Me) End Sub Public Overrides Function Accept(Of TResult)(visitor As SymbolVisitor(Of TResult)) As TResult Return visitor.VisitLocal(Me) End Function Public Overrides Sub Accept(visitor As VisualBasicSymbolVisitor) visitor.VisitLocal(Me) End Sub Public Overrides Function Accept(Of TResult)(visitor As VisualBasicSymbolVisitor(Of TResult)) As TResult Return visitor.VisitLocal(Me) End Function #End Region #Region "ILocalSymbolInternal" Private ReadOnly Property ILocalSymbolInternal_IsImportedFromMetadata As Boolean Implements ILocalSymbolInternal.IsImportedFromMetadata Get Return Me.IsImportedFromMetadata End Get End Property Private ReadOnly Property ILocalSymbolInternal_SynthesizedKind As SynthesizedLocalKind Implements ILocalSymbolInternal.SynthesizedKind Get Return Me.SynthesizedKind End Get End Property Private Function ILocalSymbolInternal_GetDeclaratorSyntax() As SyntaxNode Implements ILocalSymbolInternal.GetDeclaratorSyntax Return Me.GetDeclaratorSyntax() End Function #End Region #Region "SourceLocalSymbol" ''' <summary> ''' Base class for any local symbol that can be referenced in source, might be implicitly declared. ''' </summary> Private Class SourceLocalSymbol Inherits LocalSymbol Private ReadOnly _declarationKind As LocalDeclarationKind Protected ReadOnly _identifierToken As SyntaxToken Protected ReadOnly _binder As Binder Public Sub New(containingSymbol As Symbol, binder As Binder, identifierToken As SyntaxToken, declarationKind As LocalDeclarationKind, type As TypeSymbol) MyBase.New(containingSymbol, type) Debug.Assert(identifierToken.Kind <> SyntaxKind.None) Debug.Assert(declarationKind <> LocalDeclarationKind.None) Debug.Assert(binder IsNot Nothing) _identifierToken = identifierToken _declarationKind = declarationKind _binder = binder End Sub Friend Overrides ReadOnly Property DeclarationKind As LocalDeclarationKind Get Return _declarationKind End Get End Property Public Overrides ReadOnly Property IsFunctionValue As Boolean Get Return _declarationKind = LocalDeclarationKind.FunctionValue End Get End Property Friend Overrides ReadOnly Property SynthesizedKind As SynthesizedLocalKind Get Return SynthesizedLocalKind.UserDefined End Get End Property Public Overrides ReadOnly Property Name As String Get Return _identifierToken.GetIdentifierText() End Get End Property Friend Overrides Function GetDeclaratorSyntax() As SyntaxNode Dim node As SyntaxNode Select Case Me.DeclarationKind Case LocalDeclarationKind.Variable, LocalDeclarationKind.Constant, LocalDeclarationKind.Using, LocalDeclarationKind.Static node = _identifierToken.Parent Debug.Assert(TypeOf node Is ModifiedIdentifierSyntax) Case LocalDeclarationKind.ImplicitVariable node = _identifierToken.Parent Debug.Assert(TypeOf node Is IdentifierNameSyntax) Case LocalDeclarationKind.FunctionValue node = _identifierToken.Parent If node.IsKind(SyntaxKind.PropertyStatement) Then Dim propertyBlock = DirectCast(node.Parent, PropertyBlockSyntax) Return propertyBlock.Accessors.Where(Function(a) a.IsKind(SyntaxKind.GetAccessorBlock)).Single().BlockStatement ElseIf node.IsKind(SyntaxKind.EventStatement) Then Dim eventBlock = DirectCast(node.Parent, EventBlockSyntax) Return eventBlock.Accessors.Where(Function(a) a.IsKind(SyntaxKind.AddHandlerAccessorBlock)).Single().BlockStatement End If Debug.Assert(node.IsKind(SyntaxKind.FunctionStatement)) Case LocalDeclarationKind.Catch node = _identifierToken.Parent.Parent Debug.Assert(TypeOf node Is CatchStatementSyntax) Case LocalDeclarationKind.For node = _identifierToken.Parent If Not node.IsKind(SyntaxKind.ModifiedIdentifier) Then node = node.Parent Debug.Assert(node.IsKind(SyntaxKind.ForStatement)) End If Case LocalDeclarationKind.ForEach node = _identifierToken.Parent If Not node.IsKind(SyntaxKind.ModifiedIdentifier) Then node = node.Parent Debug.Assert(node.IsKind(SyntaxKind.ForEachStatement)) End If Case Else Throw ExceptionUtilities.UnexpectedValue(Me.DeclarationKind) End Select Return node End Function Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Get If Me.DeclarationKind = LocalDeclarationKind.FunctionValue Then Return ImmutableArray(Of SyntaxReference).Empty End If Return ImmutableArray.Create(_identifierToken.Parent.GetReference()) End Get End Property Friend NotOverridable Overrides ReadOnly Property IdentifierLocation As Location Get Return _identifierToken.GetLocation() End Get End Property Friend NotOverridable Overrides ReadOnly Property IdentifierToken As SyntaxToken Get Return _identifierToken End Get End Property Friend Overrides Function ComputeType(Optional containingBinder As Binder = Nothing) As TypeSymbol containingBinder = If(containingBinder, _binder) Dim type As TypeSymbol = ComputeTypeInternal(If(containingBinder, _binder)) Return type End Function Friend Overridable Function ComputeTypeInternal(containingBinder As Binder) As TypeSymbol Debug.Assert(_lazyType IsNot Nothing) Return _lazyType End Function Public Overrides Function Equals(obj As Object) As Boolean If Me Is obj Then Return True End If Dim other = TryCast(obj, SourceLocalSymbol) Return other IsNot Nothing AndAlso other._identifierToken.Equals(Me._identifierToken) AndAlso Equals(other._container, Me._container) AndAlso String.Equals(other.Name, Me.Name) End Function Public Overrides Function GetHashCode() As Integer Return Hash.Combine(_identifierToken.GetHashCode(), Me._container.GetHashCode()) End Function End Class #End Region #Region "SourceLocalSymbolWithNonstandardName" ''' <summary> ''' Class for a local symbol that has a different name than the identifier token. ''' In this case the real name is returned by the name property and the "VB User visible name" can be ''' obtained by accessing the IdentifierToken. ''' </summary> Private NotInheritable Class SourceLocalSymbolWithNonstandardName Inherits SourceLocalSymbol Private ReadOnly _name As String ''' <summary> ''' Create a local variable symbol. Note: this does not insert it automatically into a ''' local binder so that it can be found by lookup. ''' </summary> Public Sub New(container As Symbol, binder As Binder, declaringIdentifier As SyntaxToken, declarationKind As LocalDeclarationKind, type As TypeSymbol, name As String) MyBase.New(container, binder, declaringIdentifier, declarationKind, type) Debug.Assert(name IsNot Nothing) Debug.Assert(type IsNot Nothing) _name = name End Sub Public Overrides ReadOnly Property Name As String Get Return _name End Get End Property End Class #End Region #Region "InferredForEachLocalSymbol" ''' <summary> ''' A local symbol created by a for-each statement when Option Infer is on. ''' </summary> ''' <remarks></remarks> Private NotInheritable Class InferredForEachLocalSymbol Inherits SourceLocalSymbol Private ReadOnly _collectionExpressionSyntax As ExpressionSyntax ''' <summary> ''' Create a local variable symbol. Note: this does not insert it automatically into a ''' local binder so that it can be found by lookup. ''' </summary> Public Sub New(container As Symbol, binder As Binder, declaringIdentifier As SyntaxToken, collectionExpressionSyntax As ExpressionSyntax) MyBase.New(container, binder, declaringIdentifier, LocalDeclarationKind.ForEach, Nothing) Debug.Assert(collectionExpressionSyntax IsNot Nothing) _collectionExpressionSyntax = collectionExpressionSyntax End Sub ' Compute the type of this variable. Friend Overrides Function ComputeTypeInternal(localBinder As Binder) As TypeSymbol Dim type As TypeSymbol = Nothing type = localBinder.InferForEachVariableType(Me, _collectionExpressionSyntax, collectionExpression:=Nothing, currentType:=Nothing, elementType:=Nothing, isEnumerable:=Nothing, boundGetEnumeratorCall:=Nothing, boundEnumeratorPlaceholder:=Nothing, boundMoveNextCall:=Nothing, boundCurrentAccess:=Nothing, collectionPlaceholder:=Nothing, needToDispose:=Nothing, isOrInheritsFromOrImplementsIDisposable:=Nothing, BindingDiagnosticBag.Discarded) Return type End Function Friend Overrides ReadOnly Property HasInferredType As Boolean Get Return True End Get End Property Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Get Return GetDeclaringSyntaxReferenceHelper(Of ForEachStatementSyntax)(Me.Locations) End Get End Property End Class #End Region #Region "InferredForFromToLocalSymbol" ''' <summary> ''' A local symbol created by For from-to statement when Option Infer is on. ''' </summary> Private NotInheritable Class InferredForFromToLocalSymbol Inherits SourceLocalSymbol Private ReadOnly _fromValue As ExpressionSyntax Private ReadOnly _toValue As ExpressionSyntax Private ReadOnly _stepClauseOpt As ForStepClauseSyntax ''' <summary> ''' Create a local variable symbol. Note: this does not insert it automatically into a ''' local binder so that it can be found by lookup. ''' </summary> Public Sub New(container As Symbol, binder As Binder, declaringIdentifier As SyntaxToken, fromValue As ExpressionSyntax, toValue As ExpressionSyntax, stepClauseOpt As ForStepClauseSyntax) MyBase.New(container, binder, declaringIdentifier, LocalDeclarationKind.For, Nothing) Debug.Assert(fromValue IsNot Nothing AndAlso toValue IsNot Nothing) _fromValue = fromValue _toValue = toValue _stepClauseOpt = stepClauseOpt End Sub ' Compute the type of this variable. Friend Overrides Function ComputeType(Optional containingBinder As Binder = Nothing) As TypeSymbol Dim fromValueExpression As BoundExpression = Nothing Dim toValueExpression As BoundExpression = Nothing Dim stepValueExpression As BoundExpression = Nothing Dim type As TypeSymbol = Nothing Dim localBinder = If(containingBinder, _binder) type = localBinder.InferForFromToVariableType(Me, _fromValue, _toValue, _stepClauseOpt, fromValueExpression, toValueExpression, stepValueExpression, BindingDiagnosticBag.Discarded) Return type End Function Friend Overrides ReadOnly Property HasInferredType As Boolean Get Return True End Get End Property Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Get Return GetDeclaringSyntaxReferenceHelper(Of ForStatementSyntax)(Me.Locations) End Get End Property End Class #End Region #Region "VariableLocalSymbol" ''' <summary> ''' A local symbol created from a variable declaration or a for statement with an as clause. ''' </summary> Private NotInheritable Class VariableLocalSymbol Inherits SourceLocalSymbol Private ReadOnly _modifiedIdentifierOpt As ModifiedIdentifierSyntax ' either Nothing or a modifier identifier containing the type modifiers. Private ReadOnly _asClauseOpt As AsClauseSyntax ' can be Nothing if no AsClause Private ReadOnly _initializerOpt As EqualsValueSyntax ' can be Nothing if no initializer Private _evaluatedConstant As EvaluatedConstantInfo Private NotInheritable Class EvaluatedConstantInfo Inherits EvaluatedConstant Public Sub New(value As ConstantValue, type As TypeSymbol, expression As BoundExpression, diagnostics As BindingDiagnosticBag) MyBase.New(value, type) Debug.Assert(expression IsNot Nothing) Me.Expression = expression Me.Diagnostics = diagnostics End Sub Public ReadOnly Expression As BoundExpression Public ReadOnly Diagnostics As BindingDiagnosticBag End Class ''' <summary> ''' Create a local variable symbol. Note: this does not insert it automatically into a ''' local binder so that it can be found by lookup. ''' </summary> Public Sub New(container As Symbol, binder As Binder, declaringIdentifier As SyntaxToken, modifiedIdentifierOpt As ModifiedIdentifierSyntax, asClauseOpt As AsClauseSyntax, initializerOpt As EqualsValueSyntax, declarationKind As LocalDeclarationKind) MyBase.New(container, binder, declaringIdentifier, declarationKind, Nothing) _modifiedIdentifierOpt = modifiedIdentifierOpt _asClauseOpt = asClauseOpt _initializerOpt = initializerOpt End Sub ' Compute the type of this variable. Friend Overrides Function ComputeTypeInternal(localBinder As Binder) As TypeSymbol Dim declType As TypeSymbol = Nothing Dim type As TypeSymbol = Nothing Dim valueExpression As BoundExpression = Nothing type = localBinder.ComputeVariableType(Me, _modifiedIdentifierOpt, _asClauseOpt, _initializerOpt, valueExpression, declType, BindingDiagnosticBag.Discarded) Return type End Function Friend Overrides Function GetConstantExpression(localBinder As Binder) As BoundExpression Debug.Assert(localBinder IsNot Nothing) If IsConst Then If _evaluatedConstant Is Nothing Then Dim diagBag = New BindingDiagnosticBag() ' BindLocalConstantInitializer may be called before or after the constant's type has been set. ' It is called before when we are inferring the constant's type. In that case the constant has no explicit type ' or the explicit type is object. i.e. ' const x = 1 ' const y as object = 2.0 ' We do not use the Type property because that would cause the type to be computed. Dim constValue As ConstantValue = Nothing Dim valueExpression As BoundExpression = localBinder.BindLocalConstantInitializer(Me, _lazyType, _modifiedIdentifierOpt, _initializerOpt, diagBag, constValue) Debug.Assert(valueExpression IsNot Nothing) Debug.Assert(constValue Is Nothing OrElse Not valueExpression.HasErrors AndAlso (valueExpression.Type Is Nothing OrElse Not valueExpression.Type.IsErrorType)) SetConstantExpression(valueExpression.Type, constValue, valueExpression, diagBag) Return valueExpression End If Return _evaluatedConstant.Expression End If ' GetConstantExpression should not be called if this is not a constant. Throw ExceptionUtilities.Unreachable End Function Friend Overrides Function GetConstantValue(containingBinder As Binder) As ConstantValue If IsConst AndAlso _evaluatedConstant Is Nothing Then Dim localBinder = If(containingBinder, _binder) GetConstantExpression(localBinder) End If Return If(_evaluatedConstant IsNot Nothing, _evaluatedConstant.Value, Nothing) End Function Friend Overrides Function GetConstantValueDiagnostics(containingBinder As Binder) As BindingDiagnosticBag GetConstantValue(containingBinder) Return If(_evaluatedConstant IsNot Nothing, _evaluatedConstant.Diagnostics, Nothing) End Function Private Sub SetConstantExpression(type As TypeSymbol, constantValue As ConstantValue, expression As BoundExpression, diagnostics As BindingDiagnosticBag) If _evaluatedConstant Is Nothing Then Interlocked.CompareExchange(_evaluatedConstant, New EvaluatedConstantInfo(constantValue, type, expression, diagnostics), Nothing) End If End Sub Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Get Select Case DeclarationKind Case LocalDeclarationKind.None, LocalDeclarationKind.FunctionValue Return ImmutableArray(Of SyntaxReference).Empty Case Else If _modifiedIdentifierOpt IsNot Nothing Then Return ImmutableArray.Create(Of SyntaxReference)(_modifiedIdentifierOpt.GetReference()) Else Return ImmutableArray(Of SyntaxReference).Empty End If End Select End Get End Property End Class #End Region #Region "TypeSubstitutedLocalSymbol" ''' <summary> ''' Local symbol that is not associated with any source. ''' </summary> ''' <remarks>Generally used for temporary locals past the initial binding phase.</remarks> Private NotInheritable Class TypeSubstitutedLocalSymbol Inherits LocalSymbol Private ReadOnly _originalVariable As LocalSymbol Public Sub New(originalVariable As LocalSymbol, type As TypeSymbol) MyBase.New(originalVariable._container, type) Debug.Assert(originalVariable IsNot Nothing) Debug.Assert(type IsNot Nothing) _originalVariable = originalVariable End Sub Friend Overrides ReadOnly Property DeclarationKind As LocalDeclarationKind Get Return _originalVariable.DeclarationKind End Get End Property Friend Overrides ReadOnly Property SynthesizedKind As SynthesizedLocalKind Get Return _originalVariable.SynthesizedKind End Get End Property Public Overrides ReadOnly Property IsFunctionValue As Boolean Get Return _originalVariable.IsFunctionValue End Get End Property Public Overrides ReadOnly Property Name As String Get Return _originalVariable.Name End Get End Property Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Get Return _originalVariable.DeclaringSyntaxReferences End Get End Property Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location) Get Return _originalVariable.Locations End Get End Property Friend Overrides ReadOnly Property IdentifierToken As SyntaxToken Get Return _originalVariable.IdentifierToken End Get End Property Friend Overrides ReadOnly Property IdentifierLocation As Location Get Return _originalVariable.IdentifierLocation End Get End Property Friend Overrides ReadOnly Property IsByRef As Boolean Get Return _originalVariable.IsByRef End Get End Property Friend Overrides Function GetConstantValue(binder As Binder) As ConstantValue Return _originalVariable.GetConstantValue(binder) End Function Friend Overrides Function GetConstantValueDiagnostics(binder As Binder) As BindingDiagnosticBag Return _originalVariable.GetConstantValueDiagnostics(binder) End Function Friend Overrides Function GetDeclaratorSyntax() As SyntaxNode Return _originalVariable.GetDeclaratorSyntax() End Function End Class #End Region End Class End Namespace
' 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.CodeGen Imports Microsoft.CodeAnalysis.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ''' <summary> ''' Represents a local variable (typically inside a method body). This could also be a local variable implicitly ''' declared by a For, Using, etc. When used as a temporary variable, its container can also be a Field or Property Symbol. ''' </summary> Friend MustInherit Class LocalSymbol Inherits Symbol Implements ILocalSymbol, ILocalSymbolInternal Friend Shared ReadOnly UseBeforeDeclarationResultType As ErrorTypeSymbol = New ErrorTypeSymbol() Private ReadOnly _container As Symbol ' the method, field or property that contains the declaration of this variable Private _lazyType As TypeSymbol ''' <summary> ''' Create a local symbol from a local variable declaration. ''' </summary> Friend Shared Function Create(container As Symbol, binder As Binder, declaringIdentifier As SyntaxToken, modifiedIdentifierOpt As ModifiedIdentifierSyntax, asClauseOpt As AsClauseSyntax, initializerOpt As EqualsValueSyntax, declarationKind As LocalDeclarationKind) As LocalSymbol Return New VariableLocalSymbol(container, binder, declaringIdentifier, modifiedIdentifierOpt, asClauseOpt, initializerOpt, declarationKind) End Function ''' <summary> ''' Create a local symbol associated with an identifier token. ''' </summary> Friend Shared Function Create(container As Symbol, binder As Binder, declaringIdentifier As SyntaxToken, declarationKind As LocalDeclarationKind, type As TypeSymbol) As LocalSymbol Return New SourceLocalSymbol(container, binder, declaringIdentifier, declarationKind, type) End Function ''' <summary> ''' Create a local symbol associated with an identifier token and a different name. ''' Used for WinRT event handler return value variable). ''' </summary> Friend Shared Function Create(container As Symbol, binder As Binder, declaringIdentifier As SyntaxToken, declarationKind As LocalDeclarationKind, type As TypeSymbol, name As String) As LocalSymbol Return New SourceLocalSymbolWithNonstandardName(container, binder, declaringIdentifier, declarationKind, type, name) End Function ''' <summary> ''' Create a local symbol with substituted type. ''' </summary> Friend Shared Function Create(originalVariable As LocalSymbol, type As TypeSymbol) As LocalSymbol Return New TypeSubstitutedLocalSymbol(originalVariable, type) End Function ''' <summary> ''' Create an inferred local symbol from a For from-to statement. ''' </summary> Friend Shared Function CreateInferredForFromTo(container As Symbol, binder As Binder, declaringIdentifier As SyntaxToken, fromValue As ExpressionSyntax, toValue As ExpressionSyntax, stepClauseOpt As ForStepClauseSyntax) As LocalSymbol Return New InferredForFromToLocalSymbol(container, binder, declaringIdentifier, fromValue, toValue, stepClauseOpt) End Function ''' <summary> ''' Create an inferred local symbol from a For-each statement. ''' </summary> Friend Shared Function CreateInferredForEach(container As Symbol, binder As Binder, declaringIdentifier As SyntaxToken, expression As ExpressionSyntax) As LocalSymbol Return New InferredForEachLocalSymbol(container, binder, declaringIdentifier, expression) End Function ''' <summary> ''' Create a local variable symbol. Note: this does not insert it automatically into a ''' local binder so that it can be found by lookup. ''' </summary> Friend Sub New(container As Symbol, type As TypeSymbol) Debug.Assert(container IsNot Nothing, "local must belong to a method, field or property") Debug.Assert(container.Kind = SymbolKind.Method OrElse container.Kind = SymbolKind.Field OrElse container.Kind = SymbolKind.Property, "Unsupported container. Must be method, field or property.") _container = container _lazyType = type End Sub Friend Overridable ReadOnly Property IsImportedFromMetadata As Boolean Get Return False End Get End Property Friend MustOverride ReadOnly Property DeclarationKind As LocalDeclarationKind Friend MustOverride ReadOnly Property SynthesizedKind As SynthesizedLocalKind Public Overridable ReadOnly Property Type As TypeSymbol Get If _lazyType Is Nothing Then Interlocked.CompareExchange(_lazyType, ComputeType(), Nothing) End If Return _lazyType End Get End Property Friend ReadOnly Property ConstHasType As Boolean Get Debug.Assert(Me.IsConst) Return Me._lazyType IsNot Nothing End Get End Property ''' <summary> ''' Returns true if this local is a ReadOnly local. Compiler has a concept of ReadOnly locals. ''' </summary> Friend Overridable ReadOnly Property IsReadOnly As Boolean Get ' locals declared in the resource list of a using statement are considered to be read only. Return IsUsing OrElse IsConst End Get End Property ' Set the type of this variable. This is used by the expression binder to set the type of the variable. ' If the type has already been computed, it should have been computed to be the same type. Public Sub SetType(type As TypeSymbol) If _lazyType Is Nothing Then Interlocked.CompareExchange(_lazyType, type, Nothing) Debug.Assert((Me.IsFunctionValue AndAlso _container.Kind = SymbolKind.Method AndAlso DirectCast(_container, MethodSymbol).MethodKind = MethodKind.LambdaMethod) OrElse type.Equals(ComputeType())) Else Debug.Assert(type.Equals(_lazyType), "Attempted to set a local variable with a different type") End If End Sub ' Compute the type of this variable. Friend Overridable Function ComputeType(Optional containingBinder As Binder = Nothing) As TypeSymbol Debug.Assert(_lazyType IsNot Nothing) Return _lazyType End Function Public MustOverride Overrides ReadOnly Property Name As String ' Get the identifier token that defined this local symbol. This is useful for robustly checking ' if a local symbol actually matches a particular definition, even in the presence of duplicates. Friend MustOverride ReadOnly Property IdentifierToken As SyntaxToken ''' <summary> ''' Returns the syntax node that declares the variable. ''' </summary> ''' <remarks> ''' All user-defined and long-lived synthesized variables must return a reference to a node that is ''' tracked by the EnC diffing algorithm. For example, for <see cref="LocalDeclarationKind.Catch"/> variable ''' the declarator is the <see cref="CatchStatementSyntax"/> node, not the <see cref="IdentifierNameSyntax"/> ''' that immediately contains the variable. ''' ''' The location of the declarator is used to calculate <see cref="LocalDebugId.SyntaxOffset"/> during emit. ''' </remarks> Friend MustOverride Function GetDeclaratorSyntax() As SyntaxNode Public NotOverridable Overrides ReadOnly Property Kind As SymbolKind Get Return SymbolKind.Local End Get End Property Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location) Get Return ImmutableArray.Create(Me.IdentifierLocation) End Get End Property Friend MustOverride ReadOnly Property IdentifierLocation As Location Public Overrides ReadOnly Property ContainingSymbol As Symbol Get Return _container End Get End Property Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility Get Return Accessibility.NotApplicable End Get End Property Public Overrides ReadOnly Property IsShared As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsOverridable As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsMustOverride As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsNotOverridable As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsOverrides As Boolean Get Return False End Get End Property Public ReadOnly Property IsUsing As Boolean Get Return Me.DeclarationKind = LocalDeclarationKind.Using End Get End Property Public ReadOnly Property IsCatch As Boolean Get Return Me.DeclarationKind = LocalDeclarationKind.Catch End Get End Property Public ReadOnly Property IsConst As Boolean Get Return Me.DeclarationKind = LocalDeclarationKind.Constant End Get End Property Private ReadOnly Property ILocalSymbol_IsFixed As Boolean Implements ILocalSymbol.IsFixed Get Return False End Get End Property Friend Overridable ReadOnly Property CanScheduleToStack As Boolean Get ' cannot schedule constants and catch variables ' in theory catch vars could be scheduled, but are not worth the trouble. Return Not IsConst AndAlso Not IsCatch End Get End Property Public ReadOnly Property IsStatic As Boolean Get Return Me.DeclarationKind = LocalDeclarationKind.Static End Get End Property Public ReadOnly Property IsFor As Boolean Get Return Me.DeclarationKind = LocalDeclarationKind.For End Get End Property Public ReadOnly Property IsForEach As Boolean Get Return Me.DeclarationKind = LocalDeclarationKind.ForEach End Get End Property Public ReadOnly Property IsRef As Boolean Implements ILocalSymbol.IsRef Get Return False End Get End Property Public ReadOnly Property RefKind As RefKind Implements ILocalSymbol.RefKind Get Return RefKind.None End Get End Property Public MustOverride ReadOnly Property IsFunctionValue As Boolean Implements ILocalSymbol.IsFunctionValue Friend ReadOnly Property IsCompilerGenerated As Boolean Get Return Me.DeclarationKind = LocalDeclarationKind.None End Get End Property ''' <summary> ''' Was this local variable implicitly declared, because Option Explicit Off ''' was in effect, and no other symbol was found with this name. ''' </summary> Public Overrides ReadOnly Property IsImplicitlyDeclared As Boolean Get Return Me.DeclarationKind = LocalDeclarationKind.ImplicitVariable End Get End Property Friend Overrides Function Accept(Of TArgument, TResult)(visitor As VisualBasicSymbolVisitor(Of TArgument, TResult), arg As TArgument) As TResult Return visitor.VisitLocal(Me, arg) End Function Friend Overridable ReadOnly Property IsByRef As Boolean Get Return False End Get End Property Friend Overridable ReadOnly Property IsPinned As Boolean Get Return False End Get End Property Public ReadOnly Property HasConstantValue As Boolean Implements ILocalSymbol.HasConstantValue Get If Not Me.IsConst Then Return Nothing End If Return GetConstantValue(Nothing) IsNot Nothing End Get End Property Public ReadOnly Property ConstantValue As Object Implements ILocalSymbol.ConstantValue Get If Not Me.IsConst Then Return Nothing End If Dim constant As ConstantValue = Me.GetConstantValue(Nothing) Return If(constant Is Nothing, Nothing, constant.Value) End Get End Property Friend Overridable Function GetConstantValueDiagnostics(binder As Binder) As BindingDiagnosticBag Throw ExceptionUtilities.Unreachable End Function Friend Overridable Function GetConstantExpression(binder As Binder) As BoundExpression Throw ExceptionUtilities.Unreachable End Function Friend Overridable Function GetConstantValue(binder As Binder) As ConstantValue Return Nothing End Function Friend Overridable ReadOnly Property HasInferredType As Boolean Get Return False 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 #Region "ILocalSymbol" Private ReadOnly Property ILocalSymbol_Type As ITypeSymbol Implements ILocalSymbol.Type Get Return Me.Type End Get End Property Private ReadOnly Property ILocalSymbol_NullableAnnotation As NullableAnnotation Implements ILocalSymbol.NullableAnnotation Get Return NullableAnnotation.None End Get End Property Private ReadOnly Property ILocalSymbol_IsConst As Boolean Implements ILocalSymbol.IsConst Get Return Me.IsConst End Get End Property #End Region #Region "ISymbol" Protected Overrides ReadOnly Property ISymbol_IsStatic As Boolean Get Return Me.IsStatic End Get End Property Public Overrides Sub Accept(visitor As SymbolVisitor) visitor.VisitLocal(Me) End Sub Public Overrides Function Accept(Of TResult)(visitor As SymbolVisitor(Of TResult)) As TResult Return visitor.VisitLocal(Me) End Function Public Overrides Sub Accept(visitor As VisualBasicSymbolVisitor) visitor.VisitLocal(Me) End Sub Public Overrides Function Accept(Of TResult)(visitor As VisualBasicSymbolVisitor(Of TResult)) As TResult Return visitor.VisitLocal(Me) End Function #End Region #Region "ILocalSymbolInternal" Private ReadOnly Property ILocalSymbolInternal_IsImportedFromMetadata As Boolean Implements ILocalSymbolInternal.IsImportedFromMetadata Get Return Me.IsImportedFromMetadata End Get End Property Private ReadOnly Property ILocalSymbolInternal_SynthesizedKind As SynthesizedLocalKind Implements ILocalSymbolInternal.SynthesizedKind Get Return Me.SynthesizedKind End Get End Property Private Function ILocalSymbolInternal_GetDeclaratorSyntax() As SyntaxNode Implements ILocalSymbolInternal.GetDeclaratorSyntax Return Me.GetDeclaratorSyntax() End Function #End Region #Region "SourceLocalSymbol" ''' <summary> ''' Base class for any local symbol that can be referenced in source, might be implicitly declared. ''' </summary> Private Class SourceLocalSymbol Inherits LocalSymbol Private ReadOnly _declarationKind As LocalDeclarationKind Protected ReadOnly _identifierToken As SyntaxToken Protected ReadOnly _binder As Binder Public Sub New(containingSymbol As Symbol, binder As Binder, identifierToken As SyntaxToken, declarationKind As LocalDeclarationKind, type As TypeSymbol) MyBase.New(containingSymbol, type) Debug.Assert(identifierToken.Kind <> SyntaxKind.None) Debug.Assert(declarationKind <> LocalDeclarationKind.None) Debug.Assert(binder IsNot Nothing) _identifierToken = identifierToken _declarationKind = declarationKind _binder = binder End Sub Friend Overrides ReadOnly Property DeclarationKind As LocalDeclarationKind Get Return _declarationKind End Get End Property Public Overrides ReadOnly Property IsFunctionValue As Boolean Get Return _declarationKind = LocalDeclarationKind.FunctionValue End Get End Property Friend Overrides ReadOnly Property SynthesizedKind As SynthesizedLocalKind Get Return SynthesizedLocalKind.UserDefined End Get End Property Public Overrides ReadOnly Property Name As String Get Return _identifierToken.GetIdentifierText() End Get End Property Friend Overrides Function GetDeclaratorSyntax() As SyntaxNode Dim node As SyntaxNode Select Case Me.DeclarationKind Case LocalDeclarationKind.Variable, LocalDeclarationKind.Constant, LocalDeclarationKind.Using, LocalDeclarationKind.Static node = _identifierToken.Parent Debug.Assert(TypeOf node Is ModifiedIdentifierSyntax) Case LocalDeclarationKind.ImplicitVariable node = _identifierToken.Parent Debug.Assert(TypeOf node Is IdentifierNameSyntax) Case LocalDeclarationKind.FunctionValue node = _identifierToken.Parent If node.IsKind(SyntaxKind.PropertyStatement) Then Dim propertyBlock = DirectCast(node.Parent, PropertyBlockSyntax) Return propertyBlock.Accessors.Where(Function(a) a.IsKind(SyntaxKind.GetAccessorBlock)).Single().BlockStatement ElseIf node.IsKind(SyntaxKind.EventStatement) Then Dim eventBlock = DirectCast(node.Parent, EventBlockSyntax) Return eventBlock.Accessors.Where(Function(a) a.IsKind(SyntaxKind.AddHandlerAccessorBlock)).Single().BlockStatement End If Debug.Assert(node.IsKind(SyntaxKind.FunctionStatement)) Case LocalDeclarationKind.Catch node = _identifierToken.Parent.Parent Debug.Assert(TypeOf node Is CatchStatementSyntax) Case LocalDeclarationKind.For node = _identifierToken.Parent If Not node.IsKind(SyntaxKind.ModifiedIdentifier) Then node = node.Parent Debug.Assert(node.IsKind(SyntaxKind.ForStatement)) End If Case LocalDeclarationKind.ForEach node = _identifierToken.Parent If Not node.IsKind(SyntaxKind.ModifiedIdentifier) Then node = node.Parent Debug.Assert(node.IsKind(SyntaxKind.ForEachStatement)) End If Case Else Throw ExceptionUtilities.UnexpectedValue(Me.DeclarationKind) End Select Return node End Function Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Get If Me.DeclarationKind = LocalDeclarationKind.FunctionValue Then Return ImmutableArray(Of SyntaxReference).Empty End If Return ImmutableArray.Create(_identifierToken.Parent.GetReference()) End Get End Property Friend NotOverridable Overrides ReadOnly Property IdentifierLocation As Location Get Return _identifierToken.GetLocation() End Get End Property Friend NotOverridable Overrides ReadOnly Property IdentifierToken As SyntaxToken Get Return _identifierToken End Get End Property Friend Overrides Function ComputeType(Optional containingBinder As Binder = Nothing) As TypeSymbol containingBinder = If(containingBinder, _binder) Dim type As TypeSymbol = ComputeTypeInternal(If(containingBinder, _binder)) Return type End Function Friend Overridable Function ComputeTypeInternal(containingBinder As Binder) As TypeSymbol Debug.Assert(_lazyType IsNot Nothing) Return _lazyType End Function Public Overrides Function Equals(obj As Object) As Boolean If Me Is obj Then Return True End If Dim other = TryCast(obj, SourceLocalSymbol) Return other IsNot Nothing AndAlso other._identifierToken.Equals(Me._identifierToken) AndAlso Equals(other._container, Me._container) AndAlso String.Equals(other.Name, Me.Name) End Function Public Overrides Function GetHashCode() As Integer Return Hash.Combine(_identifierToken.GetHashCode(), Me._container.GetHashCode()) End Function End Class #End Region #Region "SourceLocalSymbolWithNonstandardName" ''' <summary> ''' Class for a local symbol that has a different name than the identifier token. ''' In this case the real name is returned by the name property and the "VB User visible name" can be ''' obtained by accessing the IdentifierToken. ''' </summary> Private NotInheritable Class SourceLocalSymbolWithNonstandardName Inherits SourceLocalSymbol Private ReadOnly _name As String ''' <summary> ''' Create a local variable symbol. Note: this does not insert it automatically into a ''' local binder so that it can be found by lookup. ''' </summary> Public Sub New(container As Symbol, binder As Binder, declaringIdentifier As SyntaxToken, declarationKind As LocalDeclarationKind, type As TypeSymbol, name As String) MyBase.New(container, binder, declaringIdentifier, declarationKind, type) Debug.Assert(name IsNot Nothing) Debug.Assert(type IsNot Nothing) _name = name End Sub Public Overrides ReadOnly Property Name As String Get Return _name End Get End Property End Class #End Region #Region "InferredForEachLocalSymbol" ''' <summary> ''' A local symbol created by a for-each statement when Option Infer is on. ''' </summary> ''' <remarks></remarks> Private NotInheritable Class InferredForEachLocalSymbol Inherits SourceLocalSymbol Private ReadOnly _collectionExpressionSyntax As ExpressionSyntax ''' <summary> ''' Create a local variable symbol. Note: this does not insert it automatically into a ''' local binder so that it can be found by lookup. ''' </summary> Public Sub New(container As Symbol, binder As Binder, declaringIdentifier As SyntaxToken, collectionExpressionSyntax As ExpressionSyntax) MyBase.New(container, binder, declaringIdentifier, LocalDeclarationKind.ForEach, Nothing) Debug.Assert(collectionExpressionSyntax IsNot Nothing) _collectionExpressionSyntax = collectionExpressionSyntax End Sub ' Compute the type of this variable. Friend Overrides Function ComputeTypeInternal(localBinder As Binder) As TypeSymbol Dim type As TypeSymbol = Nothing type = localBinder.InferForEachVariableType(Me, _collectionExpressionSyntax, collectionExpression:=Nothing, currentType:=Nothing, elementType:=Nothing, isEnumerable:=Nothing, boundGetEnumeratorCall:=Nothing, boundEnumeratorPlaceholder:=Nothing, boundMoveNextCall:=Nothing, boundCurrentAccess:=Nothing, collectionPlaceholder:=Nothing, needToDispose:=Nothing, isOrInheritsFromOrImplementsIDisposable:=Nothing, BindingDiagnosticBag.Discarded) Return type End Function Friend Overrides ReadOnly Property HasInferredType As Boolean Get Return True End Get End Property Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Get Return GetDeclaringSyntaxReferenceHelper(Of ForEachStatementSyntax)(Me.Locations) End Get End Property End Class #End Region #Region "InferredForFromToLocalSymbol" ''' <summary> ''' A local symbol created by For from-to statement when Option Infer is on. ''' </summary> Private NotInheritable Class InferredForFromToLocalSymbol Inherits SourceLocalSymbol Private ReadOnly _fromValue As ExpressionSyntax Private ReadOnly _toValue As ExpressionSyntax Private ReadOnly _stepClauseOpt As ForStepClauseSyntax ''' <summary> ''' Create a local variable symbol. Note: this does not insert it automatically into a ''' local binder so that it can be found by lookup. ''' </summary> Public Sub New(container As Symbol, binder As Binder, declaringIdentifier As SyntaxToken, fromValue As ExpressionSyntax, toValue As ExpressionSyntax, stepClauseOpt As ForStepClauseSyntax) MyBase.New(container, binder, declaringIdentifier, LocalDeclarationKind.For, Nothing) Debug.Assert(fromValue IsNot Nothing AndAlso toValue IsNot Nothing) _fromValue = fromValue _toValue = toValue _stepClauseOpt = stepClauseOpt End Sub ' Compute the type of this variable. Friend Overrides Function ComputeType(Optional containingBinder As Binder = Nothing) As TypeSymbol Dim fromValueExpression As BoundExpression = Nothing Dim toValueExpression As BoundExpression = Nothing Dim stepValueExpression As BoundExpression = Nothing Dim type As TypeSymbol = Nothing Dim localBinder = If(containingBinder, _binder) type = localBinder.InferForFromToVariableType(Me, _fromValue, _toValue, _stepClauseOpt, fromValueExpression, toValueExpression, stepValueExpression, BindingDiagnosticBag.Discarded) Return type End Function Friend Overrides ReadOnly Property HasInferredType As Boolean Get Return True End Get End Property Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Get Return GetDeclaringSyntaxReferenceHelper(Of ForStatementSyntax)(Me.Locations) End Get End Property End Class #End Region #Region "VariableLocalSymbol" ''' <summary> ''' A local symbol created from a variable declaration or a for statement with an as clause. ''' </summary> Private NotInheritable Class VariableLocalSymbol Inherits SourceLocalSymbol Private ReadOnly _modifiedIdentifierOpt As ModifiedIdentifierSyntax ' either Nothing or a modifier identifier containing the type modifiers. Private ReadOnly _asClauseOpt As AsClauseSyntax ' can be Nothing if no AsClause Private ReadOnly _initializerOpt As EqualsValueSyntax ' can be Nothing if no initializer Private _evaluatedConstant As EvaluatedConstantInfo Private NotInheritable Class EvaluatedConstantInfo Inherits EvaluatedConstant Public Sub New(value As ConstantValue, type As TypeSymbol, expression As BoundExpression, diagnostics As BindingDiagnosticBag) MyBase.New(value, type) Debug.Assert(expression IsNot Nothing) Me.Expression = expression Me.Diagnostics = diagnostics End Sub Public ReadOnly Expression As BoundExpression Public ReadOnly Diagnostics As BindingDiagnosticBag End Class ''' <summary> ''' Create a local variable symbol. Note: this does not insert it automatically into a ''' local binder so that it can be found by lookup. ''' </summary> Public Sub New(container As Symbol, binder As Binder, declaringIdentifier As SyntaxToken, modifiedIdentifierOpt As ModifiedIdentifierSyntax, asClauseOpt As AsClauseSyntax, initializerOpt As EqualsValueSyntax, declarationKind As LocalDeclarationKind) MyBase.New(container, binder, declaringIdentifier, declarationKind, Nothing) _modifiedIdentifierOpt = modifiedIdentifierOpt _asClauseOpt = asClauseOpt _initializerOpt = initializerOpt End Sub ' Compute the type of this variable. Friend Overrides Function ComputeTypeInternal(localBinder As Binder) As TypeSymbol Dim declType As TypeSymbol = Nothing Dim type As TypeSymbol = Nothing Dim valueExpression As BoundExpression = Nothing type = localBinder.ComputeVariableType(Me, _modifiedIdentifierOpt, _asClauseOpt, _initializerOpt, valueExpression, declType, BindingDiagnosticBag.Discarded) Return type End Function Friend Overrides Function GetConstantExpression(localBinder As Binder) As BoundExpression Debug.Assert(localBinder IsNot Nothing) If IsConst Then If _evaluatedConstant Is Nothing Then Dim diagBag = New BindingDiagnosticBag() ' BindLocalConstantInitializer may be called before or after the constant's type has been set. ' It is called before when we are inferring the constant's type. In that case the constant has no explicit type ' or the explicit type is object. i.e. ' const x = 1 ' const y as object = 2.0 ' We do not use the Type property because that would cause the type to be computed. Dim constValue As ConstantValue = Nothing Dim valueExpression As BoundExpression = localBinder.BindLocalConstantInitializer(Me, _lazyType, _modifiedIdentifierOpt, _initializerOpt, diagBag, constValue) Debug.Assert(valueExpression IsNot Nothing) Debug.Assert(constValue Is Nothing OrElse Not valueExpression.HasErrors AndAlso (valueExpression.Type Is Nothing OrElse Not valueExpression.Type.IsErrorType)) SetConstantExpression(valueExpression.Type, constValue, valueExpression, diagBag) Return valueExpression End If Return _evaluatedConstant.Expression End If ' GetConstantExpression should not be called if this is not a constant. Throw ExceptionUtilities.Unreachable End Function Friend Overrides Function GetConstantValue(containingBinder As Binder) As ConstantValue If IsConst AndAlso _evaluatedConstant Is Nothing Then Dim localBinder = If(containingBinder, _binder) GetConstantExpression(localBinder) End If Return If(_evaluatedConstant IsNot Nothing, _evaluatedConstant.Value, Nothing) End Function Friend Overrides Function GetConstantValueDiagnostics(containingBinder As Binder) As BindingDiagnosticBag GetConstantValue(containingBinder) Return If(_evaluatedConstant IsNot Nothing, _evaluatedConstant.Diagnostics, Nothing) End Function Private Sub SetConstantExpression(type As TypeSymbol, constantValue As ConstantValue, expression As BoundExpression, diagnostics As BindingDiagnosticBag) If _evaluatedConstant Is Nothing Then Interlocked.CompareExchange(_evaluatedConstant, New EvaluatedConstantInfo(constantValue, type, expression, diagnostics), Nothing) End If End Sub Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Get Select Case DeclarationKind Case LocalDeclarationKind.None, LocalDeclarationKind.FunctionValue Return ImmutableArray(Of SyntaxReference).Empty Case Else If _modifiedIdentifierOpt IsNot Nothing Then Return ImmutableArray.Create(Of SyntaxReference)(_modifiedIdentifierOpt.GetReference()) Else Return ImmutableArray(Of SyntaxReference).Empty End If End Select End Get End Property End Class #End Region #Region "TypeSubstitutedLocalSymbol" ''' <summary> ''' Local symbol that is not associated with any source. ''' </summary> ''' <remarks>Generally used for temporary locals past the initial binding phase.</remarks> Private NotInheritable Class TypeSubstitutedLocalSymbol Inherits LocalSymbol Private ReadOnly _originalVariable As LocalSymbol Public Sub New(originalVariable As LocalSymbol, type As TypeSymbol) MyBase.New(originalVariable._container, type) Debug.Assert(originalVariable IsNot Nothing) Debug.Assert(type IsNot Nothing) _originalVariable = originalVariable End Sub Friend Overrides ReadOnly Property DeclarationKind As LocalDeclarationKind Get Return _originalVariable.DeclarationKind End Get End Property Friend Overrides ReadOnly Property SynthesizedKind As SynthesizedLocalKind Get Return _originalVariable.SynthesizedKind End Get End Property Public Overrides ReadOnly Property IsFunctionValue As Boolean Get Return _originalVariable.IsFunctionValue End Get End Property Public Overrides ReadOnly Property Name As String Get Return _originalVariable.Name End Get End Property Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Get Return _originalVariable.DeclaringSyntaxReferences End Get End Property Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location) Get Return _originalVariable.Locations End Get End Property Friend Overrides ReadOnly Property IdentifierToken As SyntaxToken Get Return _originalVariable.IdentifierToken End Get End Property Friend Overrides ReadOnly Property IdentifierLocation As Location Get Return _originalVariable.IdentifierLocation End Get End Property Friend Overrides ReadOnly Property IsByRef As Boolean Get Return _originalVariable.IsByRef End Get End Property Friend Overrides Function GetConstantValue(binder As Binder) As ConstantValue Return _originalVariable.GetConstantValue(binder) End Function Friend Overrides Function GetConstantValueDiagnostics(binder As Binder) As BindingDiagnosticBag Return _originalVariable.GetConstantValueDiagnostics(binder) End Function Friend Overrides Function GetDeclaratorSyntax() As SyntaxNode Return _originalVariable.GetDeclaratorSyntax() End Function End Class #End Region End Class End Namespace
-1
dotnet/roslyn
56,011
React to string comparison changing on .NET Core
The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
jaredpar
"2021-08-30T17:18:52Z"
"2021-08-30T20:20:04Z"
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
4d99cda6e446e77dbb302e26388c1093bd3ef569
React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
./src/EditorFeatures/Test2/Rename/VisualBasic/ImplicitReferenceConflictTests.vb
' 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.Remote.Testing Imports Microsoft.CodeAnalysis.Rename.ConflictEngine Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Rename.VisualBasic <[UseExportProvider]> Public Class ImplicitReferenceConflictTests Private ReadOnly _outputHelper As Abstractions.ITestOutputHelper Public Sub New(outputHelper As Abstractions.ITestOutputHelper) _outputHelper = outputHelper End Sub <Theory> <WorkItem(528966, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528966")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameMoveNextCausesConflictInForEach(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Option Infer On Imports System Class B Public Property Current As Integer Public Function [|$$MoveNext|]() As Boolean Return False End Function End Class Class C Shared Sub Main() For Each x In {|foreachconflict:New C()|} Next End Sub Public Function GetEnumerator() As B Return Nothing End Function End Class </Document> </Project> </Workspace>, host:=host, renameTo:="MovNext") result.AssertLabeledSpansAre("foreachconflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <WorkItem(528966, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528966")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameMoveNextToChangeCasingDoesntCauseConflictInForEach(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Option Infer On Imports System Class B Public Property Current As Integer Public Function [|$$MoveNext|]() As Boolean Return False End Function End Class Class C Shared Sub Main() For Each x In {|foreachconflict:New C()|} Next End Sub Public Function GetEnumerator() As B Return Nothing End Function End Class </Document> </Project> </Workspace>, host:=host, renameTo:="MOVENEXT") End Using End Sub <Theory> <WorkItem(528966, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528966")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameMoveNextToChangeCasingInCSDoesntCauseConflictInForEach(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" AssemblyName="Project1" CommonReferences="true"> <Document> public class B { public int Current { get; set; } public bool [|$$MoveNext|]() { return false; } } public class C { public B GetEnumerator() { return null; } } </Document> </Project> <Project Language="Visual Basic" AssemblyName="Project2" CommonReferences="true"> <ProjectReference>Project1</ProjectReference> <Document> Option Infer On Imports System Class X Shared Sub Main() For Each x In {|foreachconflict:New C()|} Next End Sub End Class </Document> </Project> </Workspace>, host:=host, renameTo:="MOVENEXT") End Using End Sub <Theory> <WorkItem(528966, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528966")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameMoveNextInCSCauseConflictInForEach(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" AssemblyName="Project1" CommonReferences="true"> <Document> public class B { public int Current { get; set; } public bool [|$$MoveNext|]() { return false; } } public class C { public B GetEnumerator() { return null; } } </Document> </Project> <Project Language="Visual Basic" AssemblyName="Project2" CommonReferences="true"> <ProjectReference>Project1</ProjectReference> <Document> Option Infer On Imports System Class X Shared Sub Main() For Each x In {|foreachconflict:New C()|} Next End Sub End Class </Document> </Project> </Workspace>, host:=host, renameTo:="Move") result.AssertLabeledSpansAre("foreachconflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub End Class End Namespace
' 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.Remote.Testing Imports Microsoft.CodeAnalysis.Rename.ConflictEngine Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Rename.VisualBasic <[UseExportProvider]> Public Class ImplicitReferenceConflictTests Private ReadOnly _outputHelper As Abstractions.ITestOutputHelper Public Sub New(outputHelper As Abstractions.ITestOutputHelper) _outputHelper = outputHelper End Sub <Theory> <WorkItem(528966, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528966")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameMoveNextCausesConflictInForEach(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Option Infer On Imports System Class B Public Property Current As Integer Public Function [|$$MoveNext|]() As Boolean Return False End Function End Class Class C Shared Sub Main() For Each x In {|foreachconflict:New C()|} Next End Sub Public Function GetEnumerator() As B Return Nothing End Function End Class </Document> </Project> </Workspace>, host:=host, renameTo:="MovNext") result.AssertLabeledSpansAre("foreachconflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <WorkItem(528966, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528966")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameMoveNextToChangeCasingDoesntCauseConflictInForEach(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Option Infer On Imports System Class B Public Property Current As Integer Public Function [|$$MoveNext|]() As Boolean Return False End Function End Class Class C Shared Sub Main() For Each x In {|foreachconflict:New C()|} Next End Sub Public Function GetEnumerator() As B Return Nothing End Function End Class </Document> </Project> </Workspace>, host:=host, renameTo:="MOVENEXT") End Using End Sub <Theory> <WorkItem(528966, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528966")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameMoveNextToChangeCasingInCSDoesntCauseConflictInForEach(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" AssemblyName="Project1" CommonReferences="true"> <Document> public class B { public int Current { get; set; } public bool [|$$MoveNext|]() { return false; } } public class C { public B GetEnumerator() { return null; } } </Document> </Project> <Project Language="Visual Basic" AssemblyName="Project2" CommonReferences="true"> <ProjectReference>Project1</ProjectReference> <Document> Option Infer On Imports System Class X Shared Sub Main() For Each x In {|foreachconflict:New C()|} Next End Sub End Class </Document> </Project> </Workspace>, host:=host, renameTo:="MOVENEXT") End Using End Sub <Theory> <WorkItem(528966, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528966")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameMoveNextInCSCauseConflictInForEach(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" AssemblyName="Project1" CommonReferences="true"> <Document> public class B { public int Current { get; set; } public bool [|$$MoveNext|]() { return false; } } public class C { public B GetEnumerator() { return null; } } </Document> </Project> <Project Language="Visual Basic" AssemblyName="Project2" CommonReferences="true"> <ProjectReference>Project1</ProjectReference> <Document> Option Infer On Imports System Class X Shared Sub Main() For Each x In {|foreachconflict:New C()|} Next End Sub End Class </Document> </Project> </Workspace>, host:=host, renameTo:="Move") result.AssertLabeledSpansAre("foreachconflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub End Class End Namespace
-1
dotnet/roslyn
56,011
React to string comparison changing on .NET Core
The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
jaredpar
"2021-08-30T17:18:52Z"
"2021-08-30T20:20:04Z"
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
4d99cda6e446e77dbb302e26388c1093bd3ef569
React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
./src/Compilers/VisualBasic/Portable/Syntax/NamespaceDeclarationSyntaxReference.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading Imports Microsoft.CodeAnalysis.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' this is a SyntaxReference implementation that lazily translates the result (SyntaxNode) of the original syntax reference ''' to other one. ''' </summary> Friend Class NamespaceDeclarationSyntaxReference Inherits TranslationSyntaxReference Public Sub New(reference As SyntaxReference) MyBase.New(reference) End Sub Protected Overrides Function Translate(reference As SyntaxReference, cancellationToken As CancellationToken) As SyntaxNode Dim node = reference.GetSyntax(cancellationToken) ' If the node is a name syntax, it's something like "X" or "X.Y" in : ' Namespace X.Y.Z ' We want to return the full NamespaceStatementSyntax. While TypeOf node Is NameSyntax node = node.Parent End While Debug.Assert(TypeOf node Is CompilationUnitSyntax OrElse TypeOf node Is NamespaceStatementSyntax) Return node End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading Imports Microsoft.CodeAnalysis.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' this is a SyntaxReference implementation that lazily translates the result (SyntaxNode) of the original syntax reference ''' to other one. ''' </summary> Friend Class NamespaceDeclarationSyntaxReference Inherits TranslationSyntaxReference Public Sub New(reference As SyntaxReference) MyBase.New(reference) End Sub Protected Overrides Function Translate(reference As SyntaxReference, cancellationToken As CancellationToken) As SyntaxNode Dim node = reference.GetSyntax(cancellationToken) ' If the node is a name syntax, it's something like "X" or "X.Y" in : ' Namespace X.Y.Z ' We want to return the full NamespaceStatementSyntax. While TypeOf node Is NameSyntax node = node.Parent End While Debug.Assert(TypeOf node Is CompilationUnitSyntax OrElse TypeOf node Is NamespaceStatementSyntax) Return node End Function End Class End Namespace
-1
dotnet/roslyn
56,011
React to string comparison changing on .NET Core
The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
jaredpar
"2021-08-30T17:18:52Z"
"2021-08-30T20:20:04Z"
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
4d99cda6e446e77dbb302e26388c1093bd3ef569
React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
./src/Compilers/VisualBasic/Portable/Declarations/DeclarationTable.Cache.vb
' 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 Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Partial Friend Class DeclarationTable ' The structure of the DeclarationTable provides us with a set of 'old' declarations that ' stay relatively unchanged and a 'new' declaration that is repeatedly added and removed. ' This mimics the expected usage pattern of a user repeatedly typing in a single file. ' Because of this usage pattern, we can cache information about these 'old' declarations and ' keep that around as long as they do not change. For example, we keep a single 'merged ' declaration' for all those root declarations as well as sets of interesting information ' (like the type names in those decls). Private Class Cache ' The merged root declaration for all the 'old' declarations. Friend ReadOnly MergedRoot As Lazy(Of MergedNamespaceDeclaration) ' All the simple type names for all the types in the 'old' declarations. Friend ReadOnly TypeNames As Lazy(Of ICollection(Of String)) Friend ReadOnly NamespaceNames As Lazy(Of ICollection(Of String)) Friend ReadOnly ReferenceDirectives As Lazy(Of ImmutableArray(Of ReferenceDirective)) Public Sub New(table As DeclarationTable) Me.MergedRoot = New Lazy(Of MergedNamespaceDeclaration)(AddressOf table.MergeOlderNamespaces) Me.TypeNames = New Lazy(Of ICollection(Of String))(Function() GetTypeNames(Me.MergedRoot.Value)) Me.NamespaceNames = New Lazy(Of ICollection(Of String))(Function() GetNamespaceNames(Me.MergedRoot.Value)) Me.ReferenceDirectives = New Lazy(Of ImmutableArray(Of ReferenceDirective))( Function() table.SelectManyFromOlderDeclarationsNoEmbedded(Function(r) r.ReferenceDirectives)) End Sub End Class End Class End Namespace
' 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 Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Partial Friend Class DeclarationTable ' The structure of the DeclarationTable provides us with a set of 'old' declarations that ' stay relatively unchanged and a 'new' declaration that is repeatedly added and removed. ' This mimics the expected usage pattern of a user repeatedly typing in a single file. ' Because of this usage pattern, we can cache information about these 'old' declarations and ' keep that around as long as they do not change. For example, we keep a single 'merged ' declaration' for all those root declarations as well as sets of interesting information ' (like the type names in those decls). Private Class Cache ' The merged root declaration for all the 'old' declarations. Friend ReadOnly MergedRoot As Lazy(Of MergedNamespaceDeclaration) ' All the simple type names for all the types in the 'old' declarations. Friend ReadOnly TypeNames As Lazy(Of ICollection(Of String)) Friend ReadOnly NamespaceNames As Lazy(Of ICollection(Of String)) Friend ReadOnly ReferenceDirectives As Lazy(Of ImmutableArray(Of ReferenceDirective)) Public Sub New(table As DeclarationTable) Me.MergedRoot = New Lazy(Of MergedNamespaceDeclaration)(AddressOf table.MergeOlderNamespaces) Me.TypeNames = New Lazy(Of ICollection(Of String))(Function() GetTypeNames(Me.MergedRoot.Value)) Me.NamespaceNames = New Lazy(Of ICollection(Of String))(Function() GetNamespaceNames(Me.MergedRoot.Value)) Me.ReferenceDirectives = New Lazy(Of ImmutableArray(Of ReferenceDirective))( Function() table.SelectManyFromOlderDeclarationsNoEmbedded(Function(r) r.ReferenceDirectives)) End Sub End Class End Class End Namespace
-1
dotnet/roslyn
56,011
React to string comparison changing on .NET Core
The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
jaredpar
"2021-08-30T17:18:52Z"
"2021-08-30T20:20:04Z"
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
4d99cda6e446e77dbb302e26388c1093bd3ef569
React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
./src/Compilers/VisualBasic/Test/Semantic/FlowAnalysis/RegionAnalysisTestsWithStaticLocals.vb
' 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.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Partial Public Class FlowAnalysisTestsWithStaticLocals Inherits FlowTestBase 'All the scenarios have had local declarations changed to Static Local Declarations to Ensure that the 'flow analysis for static locals is exactly the same as for normal local declarations. ' 'The scenarios here should be the same as those in RegionAnalysisTest.vb with the exception of 'a. scenarios that did not involve any locals or 'b. scenarios with locals declared in lambda's only 'c. scenarios using IL ' 'The method names should be the same as those in RegionAnalysisTest.vb and the tests should result in the same 'flow analysis despite the fact that the implementation for static locals is different because of the implementation 'required to preserve state across multiple invocations. ' 'Multiple calls are NOT required to verify the flow analysis for static locals. <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Bug11067() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="Bug11067"> <file name="a.b"> Class Test Public Shared Sub Main() Static y(,) = New Integer(,) {{[|From|]}} End Sub End Class </file> </compilation>) Assert.True(analysis.Succeeded) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Bug13053a() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="Bug13053a"> <file name="a.b"> Class Test Public Shared Sub Main() Static i As Integer = 1 Static o = New MyObject With { .A = [| i |] } End Sub End Class </file> </compilation>) Assert.True(analysis.Succeeded) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub XmlNameInsideEndTag() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="XmlNameInsideEndTag"> <file name="a.b"> Module Module1 Sub S(par As Integer) Static a = &lt;tag&gt; &lt;/ [| tag |] &gt; End Sub End Module </file> </compilation>) Assert.False(analysis.Succeeded) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub ExpressionsInAttributeValues2() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="ExpressionsInAttributeValues2"> <file name="a.b"> Imports System Imports System.Reflection Public Class MyAttribute Public Sub New(p As Object) End Sub End Class &lt;MyAttribute(p:=Sub() [|Static a As Integer = 1 While a &lt; 110 a += 1 End While|] End Sub)&gt; Module Program Sub Main(args As String()) End Sub End Module </file> </compilation>) Assert.False(analysis.Succeeded) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub LowerBoundOfArrayDefinitionSize() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="LowerBoundOfArrayDefinitionSize"> <file name="a.b"> Class Test Public Shared Sub S(x As Integer) Static newTypeArguments([|0|] To x - 1) As String End Sub End Class </file> </compilation>) Assert.False(analysis.Succeeded) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Bug11440b() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="Bug11440"> <file name="a.b"> Imports System Module Program Sub Main(args As String()) GoTo Label Static arg2 As Integer = 2 Label: Static y = [| arg2 |] End Sub End Module </file> </compilation>) Assert.True(analysis.Succeeded) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.Captured)) Assert.Equal("arg2", GetSymbolNamesJoined(analysis.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.DataFlowsOut)) Assert.Equal("args", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)) Assert.Equal("args", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)) Assert.Equal("arg2", GetSymbolNamesJoined(analysis.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.WrittenInside)) Assert.Equal("args, arg2, y", GetSymbolNamesJoined(analysis.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Bug12423a() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="Bug12423a"> <file name="a.b"> Class A Sub Goo() Static x = { [| New B (abc) |] } End Sub End Class Class B Public Sub New(i As Integer) End Sub End Class </file> </compilation>) Assert.True(analysis.Succeeded) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Bug12423b() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="Bug12423b"> <file name="a.b"> Class A Sub Goo(i As Integer) Static x = New B([| i |] ) { New B (abc) } End Sub End Class Class B Public Sub New(i As Integer) End Sub End Class </file> </compilation>) Assert.True(analysis.Succeeded) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestDataFlowForValueTypes() ' WARNING: test matches the same test in C# (TestDataFlowForValueTypes) ' Keep the two tests in sync Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="TestDataFlowForValueTypes"> <file name="a.b"> Imports System Class Tst Shared Sub Tst() Static a As S0 Static b As S1 Static c As S2 Static d As S3 Static e As E0 Static f As E1 [| Console.WriteLine(a) Console.WriteLine(b) Console.WriteLine(c) Console.WriteLine(d) Console.WriteLine(e) Console.WriteLine(f) |] End Sub End Class Structure S0 End Structure Structure S1 Public s0 As S0 End Structure Structure S2 Public s0 As S0 Public s1 As Integer End Structure Structure S3 Public s0 As S0 Public s1 As Object End Structure Enum E0 End Enum Enum E1 V1 End Enum </file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.Captured)) Assert.Equal("c, d, e, f", GetSymbolNamesJoined(analysis.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.DataFlowsOut)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)) Assert.Equal("a, b, c, d, e, f", GetSymbolNamesJoined(analysis.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.WrittenInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Bug10987() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="Bug10987"> <file name="a.b"> Class Test Public Shared Sub Main() Static y(1, 2) = [|New Integer|] End Sub End Class </file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.DataFlowsOut)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.WrittenInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.ReadOutside)) Assert.Equal("y", GetSymbolNamesJoined(analysis.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestExpressionInIfStatement() Dim dataFlowAnalysis = CompileAndAnalyzeDataFlow( <compilation name="TestExpressionInIfStatement"> <file name="a.b"> Module Program Sub Main() Static x = 1 If 1 = [|x|] Then End If End Sub End Module </file> </compilation>) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsIn)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.DefinitelyAssignedOnEntry)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.DefinitelyAssignedOnExit)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub CallingMethodsOnUninitializedStructs() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="CallingMethodsOnUninitializedStructs2"> <file name="a.b"> Public Structure XXX Public x As S(Of Object) Public y As S(Of String) End Structure Public Structure S(Of T) Public x As String Public Property y As T End Structure Public Class Test Public Shared Sub Main(args As String()) Static s As XXX s.x = New S(Of Object)() [|s.x.y.ToString()|] Static t As Object = s End Sub Public Shared Sub S1(ByRef arg As XXX) arg.x.x = "" arg.x.y = arg.x.x End Sub End Class </file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.Captured)) Assert.Equal("s", GetSymbolNamesJoined(analysis.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.DataFlowsOut)) Assert.Equal("args", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)) Assert.Equal("args", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)) Assert.Equal("s", GetSymbolNamesJoined(analysis.ReadInside)) Assert.Equal("s", GetSymbolNamesJoined(analysis.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.WrittenInside)) Assert.Equal("args, s, t", GetSymbolNamesJoined(analysis.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Bug10172() Dim analysis = CompileAndAnalyzeControlAndDataFlow( <compilation name="Bug10172"> <file name="a.b"> Imports System Imports System.Collections.Generic Imports System.Linq Module Module1 Sub Main() Static list = New Integer() {1, 2, 3, 4, 5, 6, 7, 8} Static b = From i In list Where i > Function(i) As String [|Return i|] End Function.Invoke End Sub End Module </file> </compilation>) Assert.True(analysis.Item1.Succeeded) Assert.True(analysis.Item2.Succeeded) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Bug11526() Dim analysis = CompileAndAnalyzeControlAndDataFlow( <compilation name="Bug10172"> <file name="a.b"> Imports System Imports System.Collections.Generic Imports System.Linq Module Module1 Sub Main() Static x = True Static y = DateTime.Now [| Try Catch ex as Exception when x orelse y = #12:00:00 AM# End Try |] End Sub End Module </file> </compilation>) Assert.True(analysis.Item1.Succeeded) Assert.True(analysis.Item2.Succeeded) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Bug10683a() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="Bug10683a"> <file name="a.b"> Imports System Imports System.Collections.Generic Imports System.Linq Module Module1 Sub Main() Static x = New Integer() {} x.First([|Function(i As Integer, r As Integer) As Boolean Return True End Function|]) End Sub End Module </file> </compilation>) Assert.True(analysis.Succeeded) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestArrayDeclaration01() Dim analysis = CompileAndAnalyzeControlAndDataFlow( <compilation name="TestArrayDeclaration01"> <file name="a.b"> Module Program Sub Main(args As String()) [| Static x(5), y As Integer |] End Sub End Module </file> </compilation>) Dim controlFlowAnalysis = analysis.Item1 Dim dataFlowAnalysis = analysis.Item2 Assert.Equal(0, controlFlowAnalysis.ExitPoints.Count()) Assert.Equal(0, controlFlowAnalysis.EntryPoints.Count()) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.AlwaysAssigned)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.WrittenInside)) Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysis.VariablesDeclared)) Assert.True(controlFlowAnalysis.EndPointIsReachable) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestArrayDeclaration02() Dim analysis = CompileAndAnalyzeControlAndDataFlow( <compilation name="TestArrayDeclaration02"> <file name="a.b"> Module Program Sub Main(args As String()) [|If True Then Static x(5), y As Integer |] End Sub End Module </file> </compilation>) Dim controlFlowAnalysis = analysis.Item1 Dim dataFlowAnalysis = analysis.Item2 Assert.Equal(0, controlFlowAnalysis.ExitPoints.Count()) Assert.Equal(0, controlFlowAnalysis.EntryPoints.Count()) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.AlwaysAssigned)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.WrittenInside)) Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysis.VariablesDeclared)) Assert.True(controlFlowAnalysis.EndPointIsReachable) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestArrayDeclaration02_() Dim analysis = CompileAndAnalyzeControlAndDataFlow( <compilation name="TestArrayDeclaration02"> <file name="a.b"> Module Program Sub Main(args As String()) Static b As Boolean = True [|If b Then Static x(5), y As Integer |] End Sub End Module </file> </compilation>) Dim controlFlowAnalysis = analysis.Item1 Dim dataFlowAnalysis = analysis.Item2 Assert.Equal(0, controlFlowAnalysis.ExitPoints.Count()) Assert.Equal(0, controlFlowAnalysis.EntryPoints.Count()) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.AlwaysAssigned)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.WrittenInside)) Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysis.VariablesDeclared)) Assert.True(controlFlowAnalysis.EndPointIsReachable) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestVariablesWithSameName() Dim analysis = CompileAndAnalyzeControlAndDataFlow( <compilation name="TestVariablesWithSameName"> <file name="a.b"> Module Program Sub Main(args As String()) [|If True Then Static x = 1 Else Static x = 1 |] End Sub End Module </file> </compilation>) Dim controlFlowAnalysis = analysis.Item1 Dim dataFlowAnalysis = analysis.Item2 Assert.Equal(0, controlFlowAnalysis.ExitPoints.Count()) Assert.Equal(0, controlFlowAnalysis.EntryPoints.Count()) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.AlwaysAssigned)) Assert.Equal("x, x", GetSymbolNamesJoined(dataFlowAnalysis.WrittenInside)) Assert.Equal("x, x", GetSymbolNamesJoined(dataFlowAnalysis.VariablesDeclared)) Assert.True(controlFlowAnalysis.EndPointIsReachable) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestVariablesWithSameName2() Dim analysis = CompileAndAnalyzeControlAndDataFlow( <compilation name="TestVariablesWithSameName2"> <file name="a.b"> Module Program Sub Main(args As String()) Dim b As Boolean = false [|If b Then Static x = 1 Else Static x = 1 |] End Sub End Module </file> </compilation>) Dim controlFlowAnalysis = analysis.Item1 Dim dataFlowAnalysis = analysis.Item2 Assert.Equal(0, controlFlowAnalysis.ExitPoints.Count()) Assert.Equal(0, controlFlowAnalysis.EntryPoints.Count()) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.AlwaysAssigned)) Assert.Equal("x, x", GetSymbolNamesJoined(dataFlowAnalysis.WrittenInside)) Assert.Equal("x, x", GetSymbolNamesJoined(dataFlowAnalysis.VariablesDeclared)) Assert.True(controlFlowAnalysis.EndPointIsReachable) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestVariablesDeclared01() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="TestVariablesDeclared01"> <file name="a.b"> class C public sub F(x as integer) Static a as integer [| Static b as integer Static x as integer, y = 1 if true then Static z = "a" end if |] Static c as integer end sub end class</file> </compilation>) Assert.Equal("b, x, y, z", GetSymbolNamesJoined(analysis.VariablesDeclared)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestIfElseBranch() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="TestIfElseBranch"> <file name="a.b"> Imports System Module Program Function Goo() As Integer Static x, y, z [| If True x = 1 ElseIf True y = 1 Else z = 1 End If |] Console.WriteLine(x + y + z) End Function End Module </file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.VariablesDeclared)) Assert.Equal("x", GetSymbolNamesJoined(analysis.AlwaysAssigned)) Assert.Equal("x", GetSymbolNamesJoined(analysis.DataFlowsOut)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestIfElseBranch_() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="TestIfElseBranch"> <file name="a.b"> Imports System Module Program Function Goo() As Integer Static x, y, z Static b As Boolean = True [| If b x = 1 ElseIf b y = 1 Else z = 1 End If |] Console.WriteLine(x + y + z) End Function End Module </file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.AlwaysAssigned)) Assert.Equal("x, y, z", GetSymbolNamesJoined(analysis.DataFlowsOut)) Assert.Equal("b", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)) Assert.Equal("b", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestIfElseBranchReachability01() Dim analysis = CompileAndAnalyzeControlFlow( <compilation name="TestIfElseBranchReachability01"> <file name="a.b"> Imports System Module Program Function Goo() As Integer Static x, y If True Then x = 1 Else If True Then Return 1 Else [|Return 1|] Return x + y End Function End Module </file> </compilation>) Assert.Equal(1, analysis.ExitPoints.Count()) Assert.Equal(0, analysis.EntryPoints.Count()) Assert.False(analysis.StartPointIsReachable()) Assert.False(analysis.EndPointIsReachable()) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestIfElseBranchReachability02() Dim analysis = CompileAndAnalyzeControlFlow( <compilation name="TestIfElseBranchReachability02"> <file name="a.b"> Imports System Module Program Function Goo() As Integer Static x, y If True Then x = 1 Else [|If True Then Return 1 Else Return 1|] Return x + y End Function End Module </file> </compilation>) Assert.Equal(2, analysis.ExitPoints.Count()) Assert.Equal(0, analysis.EntryPoints.Count()) Assert.False(analysis.StartPointIsReachable()) Assert.False(analysis.EndPointIsReachable()) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestIfElseBranchReachability03() Dim analysis = CompileAndAnalyzeControlFlow( <compilation name="TestIfElseBranchReachability03"> <file name="a.b"> Imports System Module Program Function Goo() As Integer Static x, y [|If True Then x = 1 Else If True Then Return 1 Else Return 1|] Return x + y End Function End Module </file> </compilation>) Assert.Equal(2, analysis.ExitPoints.Count()) Assert.Equal(0, analysis.EntryPoints.Count()) Assert.True(analysis.StartPointIsReachable()) Assert.True(analysis.EndPointIsReachable()) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestIfElseBranch01() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="TestIfElseBranch01"> <file name="a.b"> Imports System Module Program Function Goo() As Integer Static x, y [|If True Then x = 1 Else y = 1|] Dim z = x + y End Function End Module </file> </compilation>) Assert.Equal("x", GetSymbolNamesJoined(analysis.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.DataFlowsIn)) Assert.Equal("x", GetSymbolNamesJoined(analysis.DataFlowsOut)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)) Assert.Equal("x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.ReadInside)) Assert.Equal("x, y", GetSymbolNamesJoined(analysis.WrittenInside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestIfElseBranch01_() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="TestIfElseBranch01"> <file name="a.b"> Imports System Module Program Function Goo() As Integer Static b As Boolean = True Static x, y [|If b Then x = 1 Else y = 1|] Static z = x + y End Function End Module </file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.AlwaysAssigned)) Assert.Equal("b", GetSymbolNamesJoined(analysis.DataFlowsIn)) Assert.Equal("x, y", GetSymbolNamesJoined(analysis.DataFlowsOut)) Assert.Equal("b", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)) Assert.Equal("b", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)) Assert.Equal("b", GetSymbolNamesJoined(analysis.ReadInside)) Assert.Equal("x, y", GetSymbolNamesJoined(analysis.WrittenInside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestIfElseBranch02() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="TestIfElseBranch02"> <file name="a.b"> Imports System Module Program Function Goo() As Integer Static x, y If True Then [|x = 1|] Else y = 1 Static z = x + y End Function End Module </file> </compilation>) Assert.Equal("x", GetSymbolNamesJoined(analysis.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.DataFlowsIn)) Assert.Equal("x", GetSymbolNamesJoined(analysis.DataFlowsOut)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)) Assert.Equal("x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.ReadInside)) Assert.Equal("x", GetSymbolNamesJoined(analysis.WrittenInside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestIfElseBranch03() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="TestIfElseBranch03"> <file name="a.b"> Imports System Module Program Function Goo() As Integer Static x, y, z If True Then x = 1 Else [|y = 1|] Static z = x + y End Function End Module </file> </compilation>) Assert.Equal("y", GetSymbolNamesJoined(analysis.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.DataFlowsOut)) '' else clause is unreachable Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.ReadInside)) Assert.Equal("y", GetSymbolNamesJoined(analysis.WrittenInside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestIfElseBranch03_() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="TestIfElseBranch03"> <file name="a.b"> Imports System Module Program Function Goo() As Integer Static b As Boolean = True Static x, y, z If b Then x = 1 Else [|y = 1|] Static z = x + y End Function End Module </file> </compilation>) Assert.Equal("y", GetSymbolNamesJoined(analysis.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.DataFlowsIn)) Assert.Equal("y", GetSymbolNamesJoined(analysis.DataFlowsOut)) Assert.Equal("b", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)) Assert.Equal("b, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.ReadInside)) Assert.Equal("y", GetSymbolNamesJoined(analysis.WrittenInside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestIfElseBranch04() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="TestIfElseBranch04"> <file name="a.b"> Imports System Module Program Function Goo() As Integer Static x, y, z If True Then x = 1 Else If True Then y = 1 Else [|z = 1|] Static zz = z + x + y End Function End Module </file> </compilation>) Assert.Equal("z", GetSymbolNamesJoined(analysis.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.DataFlowsOut)) '' else clause is unreachable Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.ReadInside)) Assert.Equal("z", GetSymbolNamesJoined(analysis.WrittenInside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestIfElseBranch04_() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="TestIfElseBranch04"> <file name="a.b"> Imports System Module Program Function Goo() As Integer Static b As Boolean = True Static x, y, z If b Then x = 1 Else If b Then y = 1 Else [|z = 1|] Static zz = z + x + y End Function End Module </file> </compilation>) Assert.Equal("z", GetSymbolNamesJoined(analysis.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.DataFlowsIn)) Assert.Equal("z", GetSymbolNamesJoined(analysis.DataFlowsOut)) Assert.Equal("b", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)) Assert.Equal("b, z", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.ReadInside)) Assert.Equal("z", GetSymbolNamesJoined(analysis.WrittenInside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestIfElseBranch05() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="TestIfElseBranch05"> <file name="a.b"> Imports System Module Program Function Goo() As Integer Static x, y, z If True Then x = 1 Else [|If True Then y = 1 Else y = 1|] Static zz = z + x + y End Function End Module </file> </compilation>) Assert.Equal("y", GetSymbolNamesJoined(analysis.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.DataFlowsOut)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.ReadInside)) Assert.Equal("y", GetSymbolNamesJoined(analysis.WrittenInside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestIfElseBranch05_() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="TestIfElseBranch05"> <file name="a.b"> Imports System Module Program Function Goo() As Integer Static b As Boolean = True Static x, y, z If b Then x = 1 Else [|If b Then y = 1 Else y = 1|] Static zz = z + x + y End Function End Module </file> </compilation>) Assert.Equal("y", GetSymbolNamesJoined(analysis.AlwaysAssigned)) Assert.Equal("b", GetSymbolNamesJoined(analysis.DataFlowsIn)) Assert.Equal("y", GetSymbolNamesJoined(analysis.DataFlowsOut)) Assert.Equal("b", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)) Assert.Equal("b, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)) Assert.Equal("b", GetSymbolNamesJoined(analysis.ReadInside)) Assert.Equal("y", GetSymbolNamesJoined(analysis.WrittenInside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestVariablesInitializedWithSelfReference() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="TestVariablesInitializedWithSelfReference"> <file name="a.b"> class C public sub F(x as integer) [| Static x as integer = x Static y as integer, z as integer = 1 |] end sub end class</file> </compilation>) Assert.Equal("x, y, z", GetSymbolNamesJoined(analysis.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.DataFlowsOut)) Assert.Equal("x", GetSymbolNamesJoined(analysis.DataFlowsIn)) Assert.Equal("Me, x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)) Assert.Equal("Me, x, x, z", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)) Assert.Equal("x, z", GetSymbolNamesJoined(analysis.AlwaysAssigned)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestVariablesDeclared02() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="TestVariablesDeclared02"> <file name="a.b"> class C public sub F(x as integer) [| Static a as integer Static b as integer Static x as integer, y as integer = 1 if true then Static z as string = "a" end if Static c as integer |] end sub end class</file> </compilation>) Assert.Equal("a, b, x, y, z, c", GetSymbolNamesJoined(analysis.VariablesDeclared)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub AlwaysAssignedUnreachable() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="AlwaysAssignedUnreachable"> <file name="a.b"> class C Public Sub F(x As Integer) [| Static y As Integer If x = 1 Then y = 2 Return Else y = 3 Throw New Exception End If Static c As Integer |] End Sub end class</file> </compilation>) Assert.Equal("y", GetSymbolNamesJoined(analysis.AlwaysAssigned)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestDataFlowLateCall() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="TestDataFlowLateCall"> <file name="a.b"> Option Strict Off Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Static o as object = 1 [| goo(o) |] End Sub Sub goo(x As String) End Sub Sub goo(Byref x As Integer) End Sub End Module </file> </compilation>) Assert.Equal("o", GetSymbolNamesJoined(analysis.DataFlowsIn)) Assert.Equal("o", GetSymbolNamesJoined(analysis.DataFlowsOut)) Assert.Equal("args, o", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)) Assert.Equal("args, o", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)) Assert.Equal("o", GetSymbolNamesJoined(analysis.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.ReadOutside)) Assert.Equal("o", GetSymbolNamesJoined(analysis.WrittenInside)) Assert.Equal("args, o", GetSymbolNamesJoined(analysis.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestDataFlowLateCall001() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="TestDataFlowLateCall001"> <file name="a.b"> Option Strict Off Imports System Imports System.Collections.Generic Imports System.Linq Class Program shared Sub Main(args As String()) Static o as object = 1 Static oo as object = new Program [| oo.goo(o) |] End Sub Sub goo(x As String) End Sub Sub goo(Byref x As Integer) End Sub End Class </file> </compilation>) Assert.Equal("o, oo", GetSymbolNamesJoined(analysis.DataFlowsIn)) Assert.Equal("o", GetSymbolNamesJoined(analysis.DataFlowsOut)) Assert.Equal("args, o, oo", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)) Assert.Equal("args, o, oo", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)) Assert.Equal("o, oo", GetSymbolNamesJoined(analysis.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.ReadOutside)) Assert.Equal("o", GetSymbolNamesJoined(analysis.WrittenInside)) Assert.Equal("args, o, oo", GetSymbolNamesJoined(analysis.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestDataFlowIndex() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="TestDataFlowsOut01"> <file name="a.b"> Option Strict Off Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Static o as object = 1 [| Static oo = o(o) |] End Sub Sub goo(x As String) End Sub Sub goo(Byref x As Integer) End Sub End Module </file> </compilation>) Assert.Equal("o", GetSymbolNamesJoined(analysis.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.DataFlowsOut)) Assert.Equal("args, o", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)) Assert.Equal("args, o, oo", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)) Assert.Equal("o", GetSymbolNamesJoined(analysis.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.ReadOutside)) Assert.Equal("oo", GetSymbolNamesJoined(analysis.WrittenInside)) Assert.Equal("args, o", GetSymbolNamesJoined(analysis.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub UnassignedVariableFlowsOut01() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="UnassignedVariableFlowsOut01"> <file name="a.b"> class C public sub F() Static i as Integer = 10 [| Static j as Integer = j + i |] Console.Write(i) Console.Write(j) end sub end class</file> </compilation>) Assert.Equal("j", GetSymbolNamesJoined(analysis.VariablesDeclared)) Assert.Equal("i, j", GetSymbolNamesJoined(analysis.DataFlowsIn)) Assert.Equal("j", GetSymbolNamesJoined(analysis.DataFlowsOut)) Assert.Equal("Me, i", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)) Assert.Equal("Me, i, j", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)) Assert.Equal("i, j", GetSymbolNamesJoined(analysis.ReadInside)) Assert.Equal("i, j", GetSymbolNamesJoined(analysis.ReadOutside)) Assert.Equal("j", GetSymbolNamesJoined(analysis.WrittenInside)) Assert.Equal("Me, i", GetSymbolNamesJoined(analysis.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestDataFlowsIn01() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="TestDataFlowsIn01"> <file name="a.b"> class C public sub F(x as integer) Static a as integer = 1, y as integer = 2 [| Static b as integer = a + x + 3 |] Static c as integer = a + 4 + y end sub end class</file> </compilation>) Assert.Equal("x, a", GetSymbolNamesJoined(analysis.DataFlowsIn)) Assert.Equal("Me, x, a, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)) Assert.Equal("Me, x, a, y, b", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestDataFlowsIn02() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="TestDataFlowsIn02"> <file name="a.b"> class Program sub Test(of T as class, new)(byref t as T) [| Static t1 as T Test(t1) t = t1 |] System.Console.WriteLine(t1.ToString()) end sub end class </file> </compilation>) Assert.Equal("Me, t1", GetSymbolNamesJoined(analysis.DataFlowsIn)) Assert.Equal("Me, t", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)) Assert.Equal("Me, t", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestDataFlowsIn03() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="TestDataFlowsIn03"> <file name="a.b"> class Program shared sub Main(args() as string) Static x as integer = 1 Static y as integer = 2 [| Static z as integer = x + y |] end sub end class </file> </compilation>) Assert.Equal("x, y", GetSymbolNamesJoined(analysis.DataFlowsIn)) Assert.Equal("args, x, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)) Assert.Equal("args, x, y, z", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestDataFlowsOut01() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="TestDataFlowsOut01"> <file name="a.b"> class C public sub F(x as integer) Static a as integer = 1, y as integer [| if x = 1 then x = 2 y = x end if |] Static c as integer = a + 4 + x + y end sub end class</file> </compilation>) Assert.Equal("x, y", GetSymbolNamesJoined(analysis.DataFlowsOut)) Assert.Equal("Me, x, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)) Assert.Equal("Me, x, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestDataFlowsOut02() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="TestDataFlowsOut02"> <file name="a.b"> class Program public sub Test(args() as string) [| Static s as integer = 10, i as integer = 1 Static b as integer = s + i |] System.Console.WriteLine(s) System.Console.WriteLine(i) end sub end class</file> </compilation>) Assert.Equal("s, i", GetSymbolNamesJoined(analysis.DataFlowsOut)) Assert.Equal("Me, args", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)) Assert.Equal("Me, args, s, i, b", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestDataFlowsOut03() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="TestDataFlowsOut03"> <file name="a.b"> imports System.Text module Program sub Main() as string Static builder as StringBuilder = new StringBuilder() [| builder.Append("Hello") builder.Append("From") builder.Append("Roslyn") |] return builder.ToString() end sub end module</file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.DataFlowsOut)) Assert.Equal("builder", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)) Assert.Equal("builder", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestDataFlowsOut06() Dim analysisResults = CompileAndAnalyzeControlAndDataFlow( <compilation> <file name="a.b"><![CDATA[ Class C Sub F(b As Boolean) Static i As Integer = 1 While b [|i = i + 1|] End While End Sub End Class ]]></file> </compilation>) Dim controlFlowAnalysisResults = analysisResults.Item1 Dim dataFlowAnalysisResults = analysisResults.Item2 Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()) Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()) Assert.Equal(True, controlFlowAnalysisResults.StartPointIsReachable) Assert.Equal(True, controlFlowAnalysisResults.EndPointIsReachable) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("Me, b, i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("Me, b, i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("b", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("Me, b, i", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestDataFlowsOut07() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="TestDataFlowsOut07"> <file name="a.b"> class Program sub F(b as boolean) Static i as integer [| i = 2 goto [next] |] [next]: Static j as integer = i end sub end class</file> </compilation>) Assert.Equal("i", GetSymbolNamesJoined(analysis.DataFlowsOut)) Assert.Equal("Me, b", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestDataFlowsOut08() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="TestDataFlowsOut08"> <file name="a.b"> Class Program Sub F() Static i As Integer = 2 Try [| i = 1 |] Finally Static j As Integer = i End Try End Sub End Class </file> </compilation>) Assert.Equal("i", GetSymbolNamesJoined(analysis.DataFlowsOut)) Assert.Equal("Me, i", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)) Assert.Equal("Me, i", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestDataFlowsOut09() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="TestDataFlowsOut09"> <file name="a.b"> class Program sub Test(args() as string) Static i as integer Static s as string [|i = 10 s = args(0) + i.ToString()|] end sub end class</file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.DataFlowsOut)) Assert.Equal("Me, args", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)) Assert.Equal("Me, args, i, s", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestDataFlowsOutExpression01() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="TestDataFlowsOutExpression01"> <file name="a.b"> class C public sub F(x as integer) Static a as integer = 1, y as integer Static tmp as integer = x [| x = 2 y = x |] temp += (a = 2) Static c as integer = a + 4 + x + y end sub end class</file> </compilation>) Assert.Equal("x, y", GetSymbolNamesJoined(analysis.DataFlowsOut)) Assert.Equal("Me, x, a, tmp", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)) Assert.Equal("Me, x, a, y, tmp", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestAlwaysAssigned01() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="TestAlwaysAssigned01"> <file name="a.b"> class C public sub F(x as integer) Static a as integer = 1, y as integer= 1 [| if x = 2 then a = 3 else a = 4 end if x = 4 if x = 3 then y = 12 end if |] Static c as integer = a + 4 + y end sub end class</file> </compilation>) Assert.Equal("x, a", GetSymbolNamesJoined(analysis.AlwaysAssigned)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestAlwaysAssigned03() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="TestAlwaysAssigned03"> <file name="a.b"> module C sub Main(args() as string) Static i as integer = [| int.Parse(args(0).ToString()) |] end sub end module</file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.AlwaysAssigned)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestWrittenInside02() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="TestWrittenInside02"> <file name="a.b"> module C sub Main(args() as string) Static i as integer = [| int.Parse(args(0).ToString()) |] end sub end module</file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.WrittenInside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestWrittenInside03() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="TestWrittenInside03"> <file name="a.b"> module C sub Main(args() as string) Static i as integer i = [| int.Parse(args(0).ToString()) |] end sub end module</file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.WrittenInside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestAlwaysAssigned04() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="TestAlwaysAssigned04"> <file name="a.b"> module C sub Main(args() as string) Static i as integer i = [| int.Parse(args(0).ToString()) |] end sub end module</file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.AlwaysAssigned)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestAlwaysAssignedDuplicateVariables() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="TestAlwaysAssignedDuplicateVariables"> <file name="a.b"> class C public sub F(x as integer) [| Static a, a, b, b as integer b = 1 |] end sub end class</file> </compilation>) Assert.Equal("b", GetSymbolNamesJoined(analysis.AlwaysAssigned)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestAccessedInsideOutside() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="TestAccessedInsideOutside"> <file name="a.b"> class C public sub F(x as integer) Static a, b, c, d, e, f, g, h, i as integer a = 1 b = a + x c = a + x [| d = c f = d e = d |] g = e i = g h = g end sub end class</file> </compilation>) Assert.Equal("c, d", GetSymbolNamesJoined(analysis.ReadInside)) Assert.Equal("d, e, f", GetSymbolNamesJoined(analysis.WrittenInside)) Assert.Equal("x, a, e, g", GetSymbolNamesJoined(analysis.ReadOutside)) Assert.Equal("Me, x, a, b, c, g, h, i", GetSymbolNamesJoined(analysis.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestAlwaysAssignedViaPassingAsByRefParameter() Dim analysisResults = CompileAndAnalyzeControlAndDataFlow( <compilation> <file name="a.b"><![CDATA[ Class C Public Sub F(x As Integer) [| Static a As Integer G(a)|] End Sub Sub G(ByRef x As Integer) x = 1 End Sub End Class ]]></file> </compilation>) Dim controlFlowAnalysisResults = analysisResults.Item1 Dim dataFlowAnalysisResults = analysisResults.Item2 Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()) Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()) Assert.Equal(True, controlFlowAnalysisResults.StartPointIsReachable) Assert.Equal(True, controlFlowAnalysisResults.EndPointIsReachable) Assert.Equal("a", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("Me, a", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal("a", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("Me, x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("Me, x, a", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal("Me, a", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal("a", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("Me, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestDeclarationWithSelfReferenceAndTernaryOperator() Dim analysisResults = CompileAndAnalyzeControlAndDataFlow( <compilation name="TestDeclarationWithSelfReferenceAndTernaryOperator"> <file name="a.b"> class C shared sub Main() [| Static x as integer = if(true, 1, x) |] end sub end class </file> </compilation>) Dim controlFlowAnalysisResults = analysisResults.Item1 Dim dataFlowAnalysisResults = analysisResults.Item2 Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()) Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()) Assert.True(controlFlowAnalysisResults.StartPointIsReachable) Assert.True(controlFlowAnalysisResults.EndPointIsReachable) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestTernaryExpressionWithAssignments() Dim analysisResults = CompileAndAnalyzeControlAndDataFlow( <compilation name="TestTernaryExpressionWithAssignments"> <file name="a.b"> class C shared sub Main() Static x as boolean = true Static y as integer [| Static z as integer y = if(x, 1, 2) z = y |] y.ToString() end sub end class </file> </compilation>) Dim dataFlowAnalysisResults = analysisResults.Item2 Assert.Equal("z", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal("y, z", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("x, y, z", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal("y, z", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestBranchOfTernaryOperator() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation name="TestBranchOfTernaryOperator"> <file name="a.b"> class C shared sub Main() Static x as boolean = true Static y as boolean = if(x,[|x|],true) end sub end class </file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestDeclarationWithSelfReference() Dim analysisResults = CompileAndAnalyzeControlAndDataFlow( <compilation name="TestDeclarationWithSelfReference"> <file name="a.b"> class C shared sub Main() [| Static x as integer = x |] end sub end class </file> </compilation>) Dim controlFlowAnalysisResults = analysisResults.Item1 Dim dataFlowAnalysisResults = analysisResults.Item2 Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()) Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()) Assert.True(controlFlowAnalysisResults.StartPointIsReachable) Assert.True(controlFlowAnalysisResults.EndPointIsReachable) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestIfStatementWithAssignments() Dim analysisResults = CompileAndAnalyzeControlAndDataFlow( <compilation name="TestIfStatementWithAssignments"> <file name="a.b"> class C shared sub Main() Static x as boolean = true Static y as integer [| if x then y = 1 else y = 2 end if |] y.ToString() end sub end class </file> </compilation>) Dim controlFlowAnalysisResults = analysisResults.Item1 Dim dataFlowAnalysisResults = analysisResults.Item2 Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()) Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()) Assert.True(controlFlowAnalysisResults.StartPointIsReachable) Assert.True(controlFlowAnalysisResults.EndPointIsReachable) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestIfStatementWithConstantCondition() Dim analysisResults = CompileAndAnalyzeControlAndDataFlow( <compilation name="TestIfStatementWithConstantCondition"> <file name="a.b"> class C shared sub Main() Static x as boolean = true Static y as integer [| if true then y = x end if |] y.ToString() end sub end class </file> </compilation>) Dim controlFlowAnalysisResults = analysisResults.Item1 Dim dataFlowAnalysisResults = analysisResults.Item2 Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()) Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()) Assert.True(controlFlowAnalysisResults.StartPointIsReachable) Assert.True(controlFlowAnalysisResults.EndPointIsReachable) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestIfStatementWithNonConstantCondition() Dim analysisResults = CompileAndAnalyzeControlAndDataFlow( <compilation name="TestIfStatementWithNonConstantCondition"> <file name="a.b"> class C shared sub Main() Static x as boolean = true Static y as integer [| if true or x then y = x end if |] y.ToString() end sub end class </file> </compilation>) Dim controlFlowAnalysisResults = analysisResults.Item1 Dim dataFlowAnalysisResults = analysisResults.Item2 Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()) Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()) Assert.True(controlFlowAnalysisResults.StartPointIsReachable) Assert.True(controlFlowAnalysisResults.EndPointIsReachable) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestSingleVariableSelection() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation name="TestSingleVariableSelection"> <file name="a.b"> class C shared sub Main() Static x as boolean = true Static y as boolean = x or [| x |] end sub end class </file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestParenthesizedExpressionSelection() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation name="TestParenthesizedExpressionSelection"> <file name="a.b"> class C shared sub Main() Static x as boolean = true Static y as boolean = x or [|(x = x) |] orelse x end sub end class </file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) ' In C# '=' is an assignment while in VB it is a comparison. Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) 'C# flows out because this is an assignment expression. In VB this is an equality test. Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) 'C# this is an assignment. In VB, this is a comparison so no assignment. Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestRefArgumentSelection() Dim analysisResults = CompileAndAnalyzeControlAndDataFlow( <compilation name="TestRefArgumentSelection"> <file name="a.b"> class C shared sub Main() Static x as integer = 0 [| Goo( x ) |] System.Console.WriteLine(x) end sub shared sub Goo(byref x as integer) end sub end class </file> </compilation>) Dim controlFlowAnalysisResults = analysisResults.Item1 Dim dataFlowAnalysisResults = analysisResults.Item2 Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()) Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()) Assert.True(controlFlowAnalysisResults.StartPointIsReachable) Assert.True(controlFlowAnalysisResults.EndPointIsReachable) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <WorkItem(541891, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541891")> <Fact()> Public Sub TestRefArgumentSelection02() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation name="TestRefArgumentSelection02"> <file name="a.b"> class C Sub Main() Static x As UInteger System.Console.WriteLine([|Goo(x)|]) End Sub Function Goo(ByRef x As ULong) x = 123 Return x + 1 End Function end class </file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("Me, x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("Me, x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal("Me, x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <WorkItem(541891, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541891")> <Fact()> Public Sub TestRefArgumentSelection02a() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation name="TestRefArgumentSelection02"> <file name="a.b"> class C Sub Main() Static x As UInteger System.Console.WriteLine(Goo([|x|])) End Sub Function Goo(ByRef x As ULong) x = 123 Return x + 1 End Function end class </file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal("Me, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestCompoundAssignmentTargetSelection01() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation name="TestCompoundAssignmentTargetSelection01"> <file name="a.b"> class C Sub Main() Static x As String = "" [|x|]+=1 End Sub end class </file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("Me, x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("Me, x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal("Me, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestCompoundAssignmentTargetSelection02() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation name="TestCompoundAssignmentTargetSelection02"> <file name="a.b"> class C Sub Main() Static x As String = "" [|x+=1|] End Sub end class </file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("Me, x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("Me, x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal("Me, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestCompoundAssignmentTargetSelection03() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation name="TestCompoundAssignmentTargetSelection03"> <file name="a.b"> Imports System Module M1 Sub M(ParamArray ary As Long()) Static local01 As Integer = 1 Static local02 As Short = 2 [| local01 ^= local02 Try local02 &lt;&lt;= ary(0) ary(1) *= local01 Static flocal As Single = 0 flocal /= ary(0) ary(1) \= ary(0) Catch ex As Exception Finally Dim slocal = Nothing slocal &amp;= Nothing End Try |] End Sub End Module </file> </compilation>) Assert.Equal("flocal, ex, slocal", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal("local01, slocal", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("ary, local01, local02, flocal", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal("local01, local02, flocal", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("ary, local01, local02", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("ary, local01, local02, slocal", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal("ary, local01, local02, flocal, slocal", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("local01, local02, flocal, ex, slocal", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal("ary, local01, local02", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestRefArgumentSelection03() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation name="TestRefArgumentSelection03"> <file name="a.b"> class C Sub Main() Static x As ULong System.Console.WriteLine([|Goo(x)|]) End Sub Function Goo(ByRef x As ULong) x = 123 Return x + 1 End Function end class </file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("Me, x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("Me, x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal("Me, x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestInvocation() Dim analysisResults = CompileAndAnalyzeControlAndDataFlow( <compilation name="TestInvocation"> <file name="a.b"> class C shared sub Main() Static x as integer = 1, y as integer = 1 [| Goo(x) |] end sub shared sub Goo(int x) end sub end class </file> </compilation>) Dim controlFlowAnalysisResults = analysisResults.Item1 Dim dataFlowAnalysisResults = analysisResults.Item2 Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()) Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()) Assert.True(controlFlowAnalysisResults.StartPointIsReachable) Assert.True(controlFlowAnalysisResults.EndPointIsReachable) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) ' Sees Me beng read Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestInvocationWithAssignmentInArguments() Dim analysisResults = CompileAndAnalyzeControlAndDataFlow( <compilation name="TestInvocationWithAssignmentInArguments"> <file name="a.b"> class C shared sub Main() Static x as integer = 1, y as integer = 1 [| x = y y = 2 Goo(y, 2) ' VB does not support expression assignment F(x = y, y = 2) |] Static z as integer = x + y } shared sub Goo(int x, int y) end sub } </file> </compilation>) Dim controlFlowAnalysisResults = analysisResults.Item1 Dim dataFlowAnalysisResults = analysisResults.Item2 Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()) Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()) Assert.True(controlFlowAnalysisResults.StartPointIsReachable) Assert.True(controlFlowAnalysisResults.EndPointIsReachable) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) ' Sees Me being read Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("x, y, z", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestArrayInitializer() Dim analysisResults = CompileAndAnalyzeControlAndDataFlow( <compilation> <file name="a.b"><![CDATA[ Class C Sub Main(args As String()) Static y As Integer = 1 Static x(,) As Integer x = { { [|y|] } } End Sub End Class ]]></file> </compilation>) Dim controlFlowAnalysisResults = analysisResults.Item1 Dim dataFlowAnalysisResults = analysisResults.Item2 Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()) Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()) Assert.Equal(True, controlFlowAnalysisResults.StartPointIsReachable) Assert.Equal(True, controlFlowAnalysisResults.EndPointIsReachable) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("Me, args, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("Me, args, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("Me, args, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub ByRefParameterNotInAppropriateCollections1() ' ByRef parameters are not considered assigned Dim analysisResults = CompileAndAnalyzeControlAndDataFlow( <compilation name="AssertFromInvalidKeywordAsExpr"> <file name="a.b"> Imports System Imports System.Collections.Generic Class Program Sub Test(of T)(ByRef t As T) [| Static t1 As T Test(t1) t = t1 |] System.Console.WriteLine(t1.ToString()) End Sub End Class </file> </compilation>) Dim controlFlowAnalysisResults = analysisResults.Item1 Dim dataFlowAnalysisResults = analysisResults.Item2 Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()) Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()) Assert.True(controlFlowAnalysisResults.StartPointIsReachable) Assert.True(controlFlowAnalysisResults.EndPointIsReachable) Assert.Equal("t1", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal("t", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("Me, t1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal("t, t1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("Me, t", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("Me, t, t1", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal("Me, t1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("t, t1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal("t, t1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("Me, t, t1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub ByRefParameterNotInAppropriateCollections2() ' ByRef parameters are not considered assigned Dim analysisResults = CompileAndAnalyzeControlAndDataFlow( <compilation name="AssertFromInvalidKeywordAsExpr"> <file name="a.b"> Imports System Imports System.Collections.Generic Class Program Sub Test(Of T)(ByRef t As T) [| Static t1 As T = GetValue(of T)(t) |] System.Console.WriteLine(t1.ToString()) End Sub Private Function GetValue(Of T)(ByRef t As T) As T Return t End Function End Class </file> </compilation>) Dim controlFlowAnalysisResults = analysisResults.Item1 Dim dataFlowAnalysisResults = analysisResults.Item2 Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()) Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()) Assert.True(controlFlowAnalysisResults.StartPointIsReachable) Assert.True(controlFlowAnalysisResults.EndPointIsReachable) Assert.Equal("t1", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal("t1", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("Me, t", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal("t, t1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("Me, t", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("Me, t, t1", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal("Me, t", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("t, t1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal("t, t1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("Me, t, t1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub BinaryAndAlso01() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation name="BinaryAndAlso01"> <file name="a.b"> Class A Function F(ByRef p As Boolean) As Boolean Return Nothing End Function Sub Test1() Static x As Boolean = True Static y As Boolean = False Static z As Boolean = IF(Nothing, [|F(x)|]) AndAlso IF(Nothing, F(y)) AndAlso False End Sub End Class </file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("Me, x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("Me, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("Me, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal("Me, x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("Me, y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("Me, x, y, z", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub BinaryAndAlso02() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation name="BinaryAndAlso02"> <file name="a.b"> Class A Function F(ByRef p As Boolean) As Boolean Return Nothing End Function Sub Test1() Static x As Boolean Static y As Boolean = False Static z As Boolean = x AndAlso [|y|] AndAlso False End Sub End Class </file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("Me, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("Me, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("Me, y, z", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub BinaryOrElse01() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation name="BinaryOrElse01"> <file name="a.b"> Class A Function F(ByRef p As Boolean) As Boolean Return Nothing End Function Sub Test1() Static x As Boolean = True Static y As Boolean = False Static z As Boolean = IF(Nothing, [|F(x)|]) OrElse IF(Nothing, F(y)) OrElse False End Sub End Class </file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("Me, x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal("Me, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("Me, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal("Me, x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub BinaryOrElse02() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation name="BinaryOrElse02"> <file name="a.b"> Class A Function F(ByRef p As Boolean) As Boolean Return Nothing End Function Sub Test1() Static x As Boolean Static y As Boolean = False Static z As Boolean = x OrElse [|y|] OrElse False End Sub End Class </file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal("Me, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("Me, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestMultipleLocalsInitializedByAsNew1() Dim dataFlowAnalysis = CompileAndAnalyzeDataFlow( <compilation name="TestMultipleLocalsInitializedByAsNew"> <file name="a.b"> Module Program Class c Sub New(i As Integer) End Sub End Class Sub Main(args As String()) Static a As Integer = 1 Static x, y, z As New c([|a|]+1) End Sub End Module </file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.WrittenInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.VariablesDeclared)) Assert.Equal("args, a, x, y, z", GetSymbolNamesJoined(dataFlowAnalysis.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestMultipleLocalsInitializedByAsNew2() Dim analysis = CompileAndAnalyzeControlAndDataFlow( <compilation name="TestMultipleLocalsInitializedByAsNew"> <file name="a.b"> Module Program Class c Sub New(i As Integer) End Sub End Class Sub Main(args As String()) Static a As Integer = 1 [|Static x, y, z As New c(a)|] End Sub End Module </file> </compilation>) Dim controlFlowAnalysis = analysis.Item1 Dim dataFlowAnalysis = analysis.Item2 Assert.Equal(0, controlFlowAnalysis.ExitPoints.Count()) Assert.Equal(0, controlFlowAnalysis.EntryPoints.Count()) Assert.Equal("x, y, z", GetSymbolNamesJoined(dataFlowAnalysis.AlwaysAssigned)) Assert.Equal("x, y, z", GetSymbolNamesJoined(dataFlowAnalysis.WrittenInside)) Assert.Equal("x, y, z", GetSymbolNamesJoined(dataFlowAnalysis.VariablesDeclared)) Assert.Equal("args, a", GetSymbolNamesJoined(dataFlowAnalysis.WrittenOutside)) Assert.True(controlFlowAnalysis.StartPointIsReachable) Assert.True(controlFlowAnalysis.EndPointIsReachable) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestElementAccess01() Dim analysis = CompileAndAnalyzeControlAndDataFlow( <compilation name="TestElementAccess"> <file name="elem.b"> Imports System Public Class Test Sub F(p as Long()) Static v() As Long = new Long() { 1, 2, 3 } [| v(0) = p(0) p(0) = v(1) |] v(1) = v(0) ' p(2) = p(0) End Sub End Class </file> </compilation>) Dim dataFlowAnalysis = analysis.Item2 Assert.True(dataFlowAnalysis.Succeeded) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.AlwaysAssigned)) Assert.Equal("p, v", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsOut)) Assert.Equal("Me, p, v", GetSymbolNamesJoined(dataFlowAnalysis.DefinitelyAssignedOnEntry)) Assert.Equal("Me, p, v", GetSymbolNamesJoined(dataFlowAnalysis.DefinitelyAssignedOnExit)) Assert.Equal("p, v", GetSymbolNamesJoined(dataFlowAnalysis.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.WrittenInside)) Assert.Equal("v", GetSymbolNamesJoined(dataFlowAnalysis.ReadOutside)) Assert.Equal("Me, p, v", GetSymbolNamesJoined(dataFlowAnalysis.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub DataFlowForDeclarationOfEnumTypedVariable() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Class C Sub Main(args As String()) [|Static s As color|] Try Catch ex As Exception When s = color.black Console.Write("Exception") End Try End Sub End Class Enum color black End Enum ]]></file> </compilation>) Assert.Equal("s", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal("s", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("Me, args", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("Me, args", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("s", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("Me, args, ex", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub IdentifierNameInMemberAccessExpr() Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Public Class Goo Sub M() Static c As C = New C() Static n1 = c.[|M|] End Sub End Class </file> </compilation>) Assert.False(dataFlowResults.Succeeded) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub IdentifierNameInMemberAccessExpr2() Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Public Class C Sub M() Static c As C = New C() Static n1 = c.[|M|] End Sub End Class </file> </compilation>) Assert.False(dataFlowResults.Succeeded) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub IdentifierNameSyntax() Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports Microsoft.VisualBasic Public Class C Sub M() Static n1 = [|ChrW|](85) End Sub End Class </file> </compilation>) Assert.True(dataFlowResults.Succeeded) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub IdentifierNameSyntax2() Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports Microsoft.VisualBasic Public Class C Sub M() Static n1 = [|Goo|](85) End Sub Function Goo(i As Integer) As Integer Return i End Function End Class </file> </compilation>) Assert.True(dataFlowResults.Succeeded) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub IdentifierNameSyntax3() Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports Microsoft.VisualBasic Public Class C Sub M() Static n1 = [|Goo|](85) End Sub ReadOnly Property Goo(i As Integer) As Integer Get Return i End Get End Property End Class </file> </compilation>) Assert.True(dataFlowResults.Succeeded) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub PredefinedTypeIncompleteSub() Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Friend Module AcceptVB7_12mod Sub AcceptVB7_12() Static lng As [|Integer|] Static int1 As Short </file> </compilation>) Assert.False(dataFlowResults.Succeeded) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub PredefinedType2() Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Friend Module AcceptVB7_12mod Sub AcceptVB7_12() Static lng As [|Integer|] Static int1 As Short End Sub And Module </file> </compilation>) Assert.False(dataFlowResults.Succeeded) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub CollectionInitSyntax() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module Program Sub Main(args As String()) Static i1 = New Integer() {4, 5} End Sub End Module </file> </compilation>) Dim tree = compilation.SyntaxTrees.First() Dim model = compilation.GetSemanticModel(tree) Dim exprSyntaxNode = DirectCast(tree.GetCompilationUnitRoot().FindToken(tree.GetRoot.ToFullString().IndexOf("{4, 5}", StringComparison.Ordinal)).Parent, CollectionInitializerSyntax) Dim analysis = model.AnalyzeDataFlow(exprSyntaxNode) Assert.False(analysis.Succeeded) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub CollectionInitSyntax2() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System.Collections.Generic Module Program Sub Main(args As String()) Static i1 = New List(Of Integer) From {4, 5} End Sub End Module </file> </compilation>) Dim tree = compilation.SyntaxTrees.First() Dim model = compilation.GetSemanticModel(tree) Dim exprSyntaxNode = DirectCast(tree.GetCompilationUnitRoot().FindToken(tree.GetRoot.ToFullString().IndexOf("{4, 5}", StringComparison.Ordinal)).Parent, CollectionInitializerSyntax) Dim analysis = model.AnalyzeDataFlow(exprSyntaxNode) Assert.False(analysis.Succeeded) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub CollectionInitSyntax3() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System.Collections.Generic Module Program Sub Main(args As String()) Static i1 = {4, 5} End Sub End Module </file> </compilation>) Dim tree = compilation.SyntaxTrees.First() Dim model = compilation.GetSemanticModel(tree) Dim exprSyntaxNode = DirectCast(tree.GetCompilationUnitRoot().FindToken(tree.GetRoot.ToFullString().IndexOf("{4, 5}", StringComparison.Ordinal)).Parent, CollectionInitializerSyntax) Dim analysis = model.AnalyzeDataFlow(exprSyntaxNode) Assert.True(analysis.Succeeded) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub IfStatementSyntax() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module Program Sub Main(args As String()) Static x = 10 If False x = x + 1 End If End Sub End Module </file> </compilation>) Dim tree = compilation.SyntaxTrees.First() Dim model = compilation.GetSemanticModel(tree) Dim stmtSyntaxNode = DirectCast(tree.GetCompilationUnitRoot().FindToken(tree.GetRoot.ToFullString().IndexOf("If False", StringComparison.Ordinal)).Parent, IfStatementSyntax) Dim analysis = model.AnalyzeControlFlow(stmtSyntaxNode, stmtSyntaxNode) Assert.False(analysis.Succeeded) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub ElseStatementSyntax() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module Program Sub Main(args As String()) Static x = 10 If False x = x + 1 Else x = x - 1 End If End Sub End Module </file> </compilation>) Dim tree = compilation.SyntaxTrees.First() Dim model = compilation.GetSemanticModel(tree) Dim stmtSyntaxNode = DirectCast(tree.GetCompilationUnitRoot().FindToken(tree.GetRoot.ToFullString().IndexOf("Else", StringComparison.Ordinal)).Parent, ElseStatementSyntax) Dim analysis = model.AnalyzeControlFlow(stmtSyntaxNode, stmtSyntaxNode) Assert.False(analysis.Succeeded) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub NamespaceIdentifierNameInMemberAccess3() Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Namespace STForEach01 Friend Module STForEach01mod ReadOnly Property STForEach01 As Integer Get Return 1 End Get End Property End Module End Namespace Friend Module MainModule Sub Main() Static a As Integer = [|STForEach01|].STForEach01 End Sub End Module </file> </compilation>) Assert.False(dataFlowResults.Succeeded) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub NamespaceIdentifierNameInMemberAccess4() Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Namespace STForEach01 Friend Module STForEach01mod ReadOnly Property STForEach01 As Integer Get Return 1 End Get End Property End Module End Namespace Friend Module MainModule Sub Main() Static a As Integer = [|STForEach01.STForEach01mod|].STForEach01 End Sub End Module </file> </compilation>) Assert.False(dataFlowResults.Succeeded) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub NamespaceIdentifierNameInMemberAccess5() Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Module Program Sub Main() Static d1 = Sub(x As Integer) [|System|].Console.WriteLine(x) End Sub End Sub End Module </file> </compilation>) Assert.False(dataFlowResults.Succeeded) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub NamespaceIdentifierNameInMemberAccess9() Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Public Class Compilation Public Class B Public Shared Function M(a As Integer) As Boolean Return False End Function End Class End Class Friend Class Program Public Shared Sub Main() Static x = [| Compilation |].B.M(a:=123) End Sub Public ReadOnly Property Compilation As Compilation Get Return Nothing End Get End Property End Class </file> </compilation>) Assert.False(dataFlowResults.Succeeded) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub NamespaceIdentifierNameInMemberAccess10() Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Public Class Compilation Public Shared Function M(a As Integer) As Boolean Return False End Function End Class Friend Class Program Public Shared Sub Main() Static x = [| Compilation |].M(a:=123) End Sub Public ReadOnly Property Compilation As Compilation Get Return Nothing End Get End Property End Class </file> </compilation>) Assert.False(dataFlowResults.Succeeded) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub ConstLocalUsedInLambda01() Dim analysisResult = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Module M1 Sub Main() Static local = 1 Const constLocal = 2 Static f = [| Function(p as sbyte) As Short Return local + constlocal + p End Function |] Console.Write(f) End Sub End Module </file> </compilation>) Assert.Equal("p", GetSymbolNamesJoined(analysisResult.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysisResult.AlwaysAssigned)) Assert.Equal("local", GetSymbolNamesJoined(analysisResult.Captured)) Assert.Equal("local, constLocal", GetSymbolNamesJoined(analysisResult.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysisResult.DataFlowsOut)) Assert.Equal("local, constLocal, f", GetSymbolNamesJoined(analysisResult.DefinitelyAssignedOnEntry)) Assert.Equal("local, constLocal, f", GetSymbolNamesJoined(analysisResult.DefinitelyAssignedOnExit)) Assert.Equal("local, constLocal, p", GetSymbolNamesJoined(analysisResult.ReadInside)) ' WHY Assert.Equal("p", GetSymbolNamesJoined(analysisResult.WrittenInside)) Assert.Equal("f", GetSymbolNamesJoined(analysisResult.ReadOutside)) Assert.Equal("local, constLocal, f", GetSymbolNamesJoined(analysisResult.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub ConstLocalUsedInLambda02() Dim analysisResult = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Class C Function F(mp As Short) As Integer Try Static local = 1 Const constLocal = 2 Static lf = [| Sub() local = constlocal + mp End Sub |] lf() Return local Finally End Try End Function End Class </file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(analysisResult.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysisResult.AlwaysAssigned)) Assert.Equal("mp, local", GetSymbolNamesJoined(analysisResult.Captured)) Assert.Equal("mp, constLocal", GetSymbolNamesJoined(analysisResult.DataFlowsIn)) Assert.Equal("local", GetSymbolNamesJoined(analysisResult.DataFlowsOut)) Assert.Equal("Me, mp, local, constLocal, lf", GetSymbolNamesJoined(analysisResult.DefinitelyAssignedOnEntry)) Assert.Equal("Me, mp, local, constLocal, lf", GetSymbolNamesJoined(analysisResult.DefinitelyAssignedOnExit)) Assert.Equal("mp, constLocal", GetSymbolNamesJoined(analysisResult.ReadInside)) Assert.Equal("local", GetSymbolNamesJoined(analysisResult.WrittenInside)) Assert.Equal("local, lf", GetSymbolNamesJoined(analysisResult.ReadOutside)) Assert.Equal("Me, mp, local, constLocal, lf", GetSymbolNamesJoined(analysisResult.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub LiteralExprInVarDeclInsideSingleLineLambda() Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Module Test Sub Sub1() Static x = Sub() Dim y = [|10|] End Sub End Module </file> </compilation>) Assert.True(dataFlowResults.Succeeded) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub ObjectCreationExpr() Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Module Program Sub Main(args As String()) Static x As [|New C|] End Sub End Module </file> </compilation>) Assert.True(dataFlowResults.Succeeded) End Sub #Region "ObjectInitializer" <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub ObjectInitializersNoStaticLocalsAccessed() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Public Class C1 Public FieldInt As Long Public FieldStr As String Public Property PropInt As Integer End Class Public Class C2 Public Shared Sub Main() Static intlocal As Integer Static x = New C1() With {.FieldStr = [|.FieldInt.ToString()|]} End Sub End Class </file> </compilation>) Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub ObjectInitializersStaticLocalsAccessed1_OnlyImplicitReceiverRegion1() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Public Structure S1 Public FieldInt As Long Public FieldStr As String Public Property PropInt As Integer End Structure Public Class S2 Public Shared Sub Main() Static x, y As New S1() With {.FieldStr = [|.FieldInt.ToString()|]} End Sub End Class </file> </compilation>) Assert.False(dataFlowAnalysisResults.Succeeded) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub ObjectInitializersStaticLocalsAccessed1_OnlyImplicitReceiverRegion2() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Public Structure S1 Public FieldInt As Long Public FieldStr As String Public Property PropInt As Integer End Structure Public Class S2 Public Shared Sub Main() Static x, y As New S1() With {.FieldInt = [|.FieldStr.Length|]} End Sub End Class </file> </compilation>) Assert.False(dataFlowAnalysisResults.Succeeded) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub ObjectInitializersStaticLocalsAccessed1_DeclAndImplicitReceiverRegion() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Public Structure S1 Public FieldInt As Long Public FieldStr As String Public Property PropInt As Integer End Structure Public Class S2 Public Shared Sub Main() [| Static x, y As New S1() With {.FieldInt = .FieldStr.Length} |] End Sub End Class </file> </compilation>) Assert.True(dataFlowAnalysisResults.Succeeded) Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub ObjectInitializersStaticLocalsAccessed1_ValidRegion1() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Public Structure S1 Public FieldInt As Long Public FieldStr As String Default Public Property PropInt(i As String) As String Get Return 0 End Get Set(value As String) End Set End Property End Structure Public Class S2 Public Shared Sub Main() Static x, y As New S1() With {.FieldInt = !A.Length } x.FieldInt = [| x!A.Length |] End Sub End Class </file> </compilation>) Assert.True(dataFlowAnalysisResults.Succeeded) Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub ObjectInitializersStaticLocalsAccessed1_ValidRegion2() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Public Structure S1 Public FieldInt As Long Public FieldStr As String Default Public Property PropInt(i As String) As String Get Return 0 End Get Set(value As String) End Set End Property End Structure Public Class S2 Public Shared Sub Main() Static x, y As New S1() With {.FieldInt = [| x!A.Length |] } End Sub End Class </file> </compilation>) Assert.True(dataFlowAnalysisResults.Succeeded) Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub ObjectInitializersStaticLocalsAccessed1_InvalidRegion3() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Public Structure S1 Public FieldInt As Long Public FieldStr As String Default Public Property PropInt(i As String) As String Get Return 0 End Get Set(value As String) End Set End Property End Structure Public Class S2 Public Shared Sub Main() Static x, y As New S1() With {.FieldStr = [| !A |] } End Sub End Class </file> </compilation>) Assert.False(dataFlowAnalysisResults.Succeeded) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub ObjectInitializersStaticLocalsAccessed1a_ObjectInitializer() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Public Structure S1 Public FieldInt As Long Public FieldStr As String Public Property PropInt As Integer End Structure Public Class S2 Public Shared Sub Main() Static o As New S1() With o [|Console.WriteLine(New S1() With {.FieldStr = .FieldInt.ToString()})|] End With End Sub End Class </file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("o", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("o", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("o", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub ObjectInitializersStaticLocalsAccessed1a_ObjectInitializer2() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Public Structure S1 Public FieldInt As Long Public FieldStr As String Public Property PropInt As Integer End Structure Public Class S2 Public Shared Sub Main() Static o As New S1() With o Console.WriteLine(New S1() With {.FieldStr = [|.FieldInt.ToString()|] }) End With End Sub End Class </file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("o", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("o", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("o", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub ObjectInitializersStaticLocalsAccessed1b() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Public Structure S1 Public FieldInt As Long Public FieldStr As String Public Property PropInt As Integer End Structure Public Class S2 Public Shared Sub Main() Static o As New S1() With o [|Console.WriteLine(New List(Of String) From {.FieldStr, "Brian", "Tim"})|] End With End Sub End Class </file> </compilation>) Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) Assert.Equal("o", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("o", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("o", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal("o", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("o", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub ObjectInitializersStaticLocalsAccessed1bb() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Public Structure S1 Public FieldInt As Long Public FieldStr As String Public Property PropInt As Integer End Structure Public Class S2 Public Shared Sub Main() Static o As New S1() [|Console.WriteLine(New List(Of String) From {o.FieldStr, "Brian", "Tim"})|] End Sub End Class </file> </compilation>) Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) Assert.Equal("o", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("o", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("o", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal("o", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("o", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub ObjectInitializers_StructWithFieldAccessesInLambda1() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Structure SS1 Public A As String Public B As String End Structure Structure SS2 Public X As SS1 Public Y As SS1 End Structure Structure Clazz Shared Sub TEST() Static a, b As New SS2() With {.X = Function() As SS1 With .Y [| .A = "1" |] '.B = "2" End With Return .Y End Function.Invoke()} End Sub End Structure </file> </compilation>) Assert.False(dataFlowAnalysisResults.Succeeded) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub ObjectInitializers_StructWithFieldAccessesInLambda2() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Structure SS1 Public A As String Public B As String End Structure Structure SS2 Public X As SS1 Public Y As SS1 End Structure Structure Clazz Shared Sub TEST() Static a, b As New SS2() With {.X = Function() As SS1 With .Y [| b.Y.B = a.Y.A a.Y.A = "1" |] End With Return .Y End Function.Invoke()} End Sub End Structure </file> </compilation>) Assert.True(dataFlowAnalysisResults.Succeeded) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("a, b", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) Assert.Equal("a", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("a", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("a", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal("a", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("a, b", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal("a, b", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("a, b", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub ObjectInitializers_StructWithFieldAccessesInLambda3() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Structure SS1 Public A As String Public B As String End Structure Structure SS2 Public X As SS1 Public Y As SS1 End Structure Structure Clazz Sub New(i As Integer) Static l = Sub() Dim a, b As New SS2() With {.X = Function() As SS1 With .Y [| b.Y.B = a.Y.A a.Y.A = "1" |] End With Return .Y End Function.Invoke()} End Sub End Sub End Structure </file> </compilation>) Assert.True(dataFlowAnalysisResults.Succeeded) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("a, b", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) Assert.Equal("a", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("i, l, a", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("i, l, a", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal("a", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("Me, a, b", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal("a, b", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("Me, i, l, a, b", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub ObjectInitializers_StructWithFieldAccessesInLambda4() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Structure SS1 Public A As String Public B As String End Structure Structure SS2 Public X As SS1 Public Y As SS1 End Structure Structure Clazz Sub New(i As Integer) Static a, b As New SS2() With {.X = Function() As SS1 [| a.Y = New SS1() b.Y = New SS1() |] Return .Y End Function.Invoke()} Console.WriteLine(a.ToString()) End Sub End Structure </file> </compilation>) Assert.True(dataFlowAnalysisResults.Succeeded) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("a, b", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("i, a", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("i, a", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("Me, a, b", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal("a, b", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("Me, i, a, b", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub ObjectInitializers_StructWithFieldAccessesInLambda5() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Structure SS1 Public A As String Public B As String End Structure Structure SS2 Public X As SS1 Public Y As SS1 End Structure Structure Clazz Sub New(i As Integer) Static a, b As New SS2() With {.X = Function() As SS1 [| b.Y = New SS1() |] Return a.Y End Function.Invoke()} Console.WriteLine(a.ToString()) End Sub End Structure </file> </compilation>) Assert.True(dataFlowAnalysisResults.Succeeded) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("a, b", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("i, a", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("i, a", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("Me, a", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal("b", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("Me, i, a, b", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub ObjectInitializers_StructWithFieldAccessesInLambda6() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Structure SS1 Public A As String Public B As String End Structure Structure SS2 Public X As SS1 Public Y As SS1 End Structure Structure Clazz Sub New(i As Integer) Static a, b As New SS2() With {.X = Function() As SS1 [| b.Y = New SS1() |] Return b.Y End Function.Invoke()} Console.WriteLine(a.ToString()) End Sub End Structure </file> </compilation>) Assert.True(dataFlowAnalysisResults.Succeeded) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("b", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal("b", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("i, a", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("i, a", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("Me, a, b", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal("b", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("Me, i, a, b", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub ObjectInitializers_PassingFieldByRef() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Structure SS1 Public A As String Public B As String End Structure Structure SS2 Public X As SS1 Public Y As SS1 End Structure Structure Clazz Shared Function Transform(ByRef p As SS1) As SS1 Return p End Function Sub New(i As Integer) Static a, b As New SS2() With {.X = [| Transform(b.Y) |] } End Sub End Structure </file> </compilation>) Assert.True(dataFlowAnalysisResults.Succeeded) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) Assert.Equal("b", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("i, a", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("i, a", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal("b", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal("b", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("Me, i, a, b", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub ObjectInitializersLocalsAccessed2() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Public Structure S1 Public FieldInt As Long Public FieldStr As String Public Property PropInt As Integer End Structure Public Class S2 Public Shared Sub Main() Static x As New S1() With {.FieldStr = [|.FieldInt.ToString()|]} End Sub End Class </file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub ObjectInitializersWithLocalsAccessed() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Public Class C1 Public FieldStr As String End Class Public Class C2 Public Shared Function GetStr(p as string) return p end Function Public Shared Sub Main() Static strlocal As String Static x = New C1() With {.FieldStr = [|GetStr(strLocal)|]} End Sub End Class </file> </compilation>) Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("strlocal", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal("strlocal", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub ObjectInitializersWithLocalCaptured() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Class C1 Public Field As Integer = 42 Public Field2 As Func(Of Integer) End Class Class C1(Of T) Public Field As T End Class Class C2 Public Shared Sub Main() Static localint as integer = 23 Static x As New C1 With {.Field2 = [|Function() As Integer Return localint End Function|]} x.Field = 42 Console.WriteLine(x.Field2.Invoke()) End Sub End Class </file> </compilation>) Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("localint", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("localint", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("localint", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal("localint", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("localint, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal("localint", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub ObjectInitializersWholeStatement() Dim analysisResults = CompileAndAnalyzeControlAndDataFlow( <compilation> <file name="a.vb"> Imports System Class C1 Public Field As Integer = 42 Public Field2 As Func(Of Integer) End Class Class C1(Of T) Public Field As T End Class Class C2 Public Shared Sub Main() Static localint as integer [|Static x As New C1 With {.Field2 = Function() As Integer localInt = 23 Return localint End Function}|] x.Field = 42 Console.WriteLine(x.Field2.Invoke()) End Sub End Class </file> </compilation>) Dim dataFlowAnalysisResults = analysisResults.Item2 Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal("localint", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal("localint, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal("localint", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) Dim controlFlowAnalysisResults = analysisResults.Item1 Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count) Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count) Assert.True(controlFlowAnalysisResults.EndPointIsReachable) Assert.True(controlFlowAnalysisResults.StartPointIsReachable) End Sub #End Region #Region "CollectionInitializer" <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub CollectionInitializersCompleteObjectCreationExpression() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Public Class C2 Public Shared Sub Main() Static goo as string = "Hello World" Static x as [|New List(Of String) From {goo, "!"}|] End Sub End Class </file> </compilation>) Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("goo", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("goo", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("goo", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal("goo", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("goo, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub CollectionInitializersOutermostInitializerAreNoVBExpressions() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Public Class C2 Public Shared Sub Main() Static goo as string = "Hello World" Static x as New List(Of String) From [|{goo, "!"}|] End Sub End Class </file> </compilation>) Assert.False(dataFlowAnalysisResults.Succeeded) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub CollectionInitializersTopLevelInitializerAreNoVBExpressions() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Public Class C2 Public Shared Sub Main() Static goo as string = "Hello World" Static x as New Dictionary(Of String, Integer) From {[|{goo, 1}|], {"bar", 42}} End Sub End Class </file> </compilation>) Assert.False(dataFlowAnalysisResults.Succeeded) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub CollectionInitializersLiftedLocals() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Public Class C2 Public Shared Sub Main() Static goo As String = "Hello World" Static x As [|New List(Of Action) From { Sub() Console.WriteLine(goo) End Sub, Sub() Console.WriteLine(x.Item(0)) x = nothing End Sub }|] End Sub End Class </file> </compilation>) Assert.True(dataFlowAnalysisResults.Succeeded) Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("goo, x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("goo", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("goo", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal("goo, x", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) Assert.Equal("goo, x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("goo, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub CollectionInitUndeclaredIdentifier() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Static f1() As String = {[|X|]} End Sub End Module </file> </compilation>) Assert.True(dataFlowAnalysisResults.Succeeded) End Sub #End Region <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub UserDefinedOperatorBody() Dim analysisResults = CompileAndAnalyzeControlAndDataFlow( <compilation> <file name="a.vb"> Imports System Module Module1 Class B2 Public f As Integer Public Sub New(x As Integer) f = x End Sub Shared Widening Operator CType(x As Integer) As B2 [| Return New B2(x) |] End Operator End Class Sub Main() Static x As Integer = 11 Static b2 As B2 = x End Sub End Module </file> </compilation>) Dim ctrlFlowResults = analysisResults.Item1 Assert.True(ctrlFlowResults.Succeeded) Assert.Equal(1, ctrlFlowResults.ExitPoints.Count()) Assert.Equal(0, ctrlFlowResults.EntryPoints.Count()) Assert.True(ctrlFlowResults.StartPointIsReachable) Assert.False(ctrlFlowResults.EndPointIsReachable) Dim dataFlowResults = analysisResults.Item2 Assert.True(dataFlowResults.Succeeded) Assert.Empty(dataFlowResults.VariablesDeclared) Assert.Empty(dataFlowResults.AlwaysAssigned) Assert.Empty(dataFlowResults.Captured) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Empty((dataFlowResults.DataFlowsOut)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnEntry)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnExit)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Empty(dataFlowResults.WrittenInside) Assert.Empty(dataFlowResults.ReadOutside) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub UserDefinedOperatorInExpression() Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Module Module1 Class B2 Public f As Integer Public Sub New(x As Integer) f = x End Sub Shared Operator -(x As Integer, y As B2) As B2 Return New B2(x) End Operator End Class Sub Main(args As String()) Static x As Short = 123 Static bb = New B2(x) Static ret = [| Function(y) Return args.Length - (y - (x - bb)) End Function |] End Sub End Module </file> </compilation>) Assert.True(dataFlowResults.Succeeded) Assert.Equal("y", GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Empty(dataFlowResults.AlwaysAssigned) Assert.Equal("args, x, bb", GetSymbolNamesJoined(dataFlowResults.Captured)) Assert.Equal("args, x, bb", GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Empty(dataFlowResults.DataFlowsOut) Assert.Equal("args, x, bb, ret", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnEntry)) Assert.Equal("args, x, bb, ret", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnExit)) Assert.Equal("args, x, bb, y", GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal("y", GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("args, x, bb, ret", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub UserDefinedLiftedOperatorInExpr() Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Class A Structure S Shared Narrowing Operator CType(x As S?) As Integer System.Console.WriteLine("Operator Conv") Return 123 'Nothing End Operator Shared Operator *(x As S?, y As Integer?) As Integer? System.Console.WriteLine("Operator *") Return y End Operator End Structure End Class Module Program Sub M(Optional p As Integer? = Nothing) Static local As A.S? = New A.S() Static f As Func(Of A.S, Integer?) = [| Function(x) Return x * local * p End Function |] Console.Write(f(local)) End Sub End Module </file> </compilation>) Assert.True(dataFlowResults.Succeeded) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Empty(dataFlowResults.AlwaysAssigned) Assert.Equal("p, local", GetSymbolNamesJoined(dataFlowResults.Captured)) Assert.Equal("p, local", GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Empty(dataFlowResults.DataFlowsOut) Assert.Equal("f", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnEntry)) Assert.Equal("f", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnExit)) Assert.Equal("p, local, x", GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal("local, f", GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("p, local, f", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub DataFlowsInAndNullable() ' WARNING: if this test is edited, the test with the ' test with the same name in C# must be modified too Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Structure S Public F As Integer Public Sub New(_f As Integer) Me.F = _f End Sub End Structure Module Program Sub Main(args As String()) Static i As Integer? = 1 Static s As New S(1) [| Console.Write(i.Value) Console.Write(s.F) |] End Sub End Module </file> </compilation>) Assert.True(dataFlowResults.Succeeded) Assert.Empty(dataFlowResults.VariablesDeclared) Assert.Empty(dataFlowResults.AlwaysAssigned) Assert.Empty(dataFlowResults.Captured) Assert.Equal("i, s", GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Empty(dataFlowResults.DataFlowsOut) Assert.Equal("args", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnEntry)) Assert.Equal("args", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnExit)) Assert.Equal("i, s", GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Empty(dataFlowResults.WrittenInside) Assert.Empty(dataFlowResults.ReadOutside) Assert.Equal("args, i, s", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestWithEventsInitializer() Dim comp = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Class C1 WithEvents e As C1 = [|Me|] End Class </file> </compilation>) Debug.Assert(comp.Succeeded) End Sub <WorkItem(546820, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546820")> <Fact()> Public Sub TestDataFlowsInAndOut() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="TestDataFlowsInAndOut"> <file name="a.b"> class Program shared sub Main(args() as string) Static x as integer Static y as integer = 2 [| If x = y Then x = 2 y = 3 End If |] end sub end class </file> </compilation>) Assert.Equal("x, y", GetSymbolNamesJoined(analysis.DataFlowsIn)) Assert.Equal("x, y", GetSymbolNamesJoined(analysis.DataFlowsOut)) Assert.Equal("args, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)) Assert.Equal("args, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)) End Sub <WorkItem(546820, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546820")> <Fact()> Public Sub TestDataFlowsInAndOut2() Dim analysis = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"> class Program shared sub Main(args() as string) Static x as integer = 1 Static y as integer = 1 [| y = x x = 2 |] x = 3 y = 3 end sub end class </file> </compilation>) Assert.Equal("x", GetSymbolNamesJoined(analysis.DataFlowsIn)) Assert.Equal("x", GetSymbolNamesJoined(analysis.DataFlowsOut)) Assert.Equal("args, x, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)) Assert.Equal("args, x, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)) End Sub <WorkItem(546820, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546820")> <Fact()> Public Sub TestDataFlowsInAndOut3() Dim analysis = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"> class Program shared sub Main(args() as string) Static x as integer = 1 if x = 1 then [| x = 2 |] x = 3 end if end sub end class </file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.DataFlowsIn)) Assert.Equal("x", GetSymbolNamesJoined(analysis.DataFlowsOut)) Assert.Equal("args, x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)) Assert.Equal("args, x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)) End Sub <WorkItem(546820, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546820")> <Fact()> Public Sub TestDataFlowsInAndOut4() Dim analysis = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"> Imports System class Program shared sub Main(args() as string) [| Static x as integer = 1 Console.WriteLine(x) |] end sub end class </file> </compilation>) Assert.Equal("x", GetSymbolNamesJoined(analysis.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.DataFlowsOut)) Assert.Equal("args", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)) Assert.Equal("args, x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)) End Sub <WorkItem(546820, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546820")> <Fact()> Public Sub TestDataFlowsInAndOut5() Dim analysis = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"> Imports System class Program shared sub Main(args() as string) Static x as integer = 1 dim y = x [| x = 1 |] end sub end class </file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.DataFlowsIn)) Assert.Equal("x", GetSymbolNamesJoined(analysis.DataFlowsOut)) Assert.Equal("args, x, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)) Assert.Equal("args, x, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)) End Sub <WorkItem(546820, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546820")> <Fact()> Public Sub TestDataFlowsInAndOut6() Dim analysis = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"> Imports System class Program shared sub Main(args() as string) Static x as integer = 1 [| x = 1 |] dim y = x end sub end class </file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.DataFlowsIn)) Assert.Equal("x", GetSymbolNamesJoined(analysis.DataFlowsOut)) Assert.Equal("args, x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)) Assert.Equal("args, x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)) End Sub #Region "Anonymous Type, Lambda" <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestCaptured() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="TestLifted"> <file name="a.b"> class C Dim field = 123 public sub F(x as integer) Static a as integer = 1, y as integer = 1 [| Static l1 = function() x+y+field |] Static c as integer = a + 4 + y end sub end class</file> </compilation>) Assert.Equal("l1", GetSymbolNamesJoined(analysis.VariablesDeclared)) Assert.Equal("l1", GetSymbolNamesJoined(analysis.AlwaysAssigned)) Assert.Equal("Me, x, y", GetSymbolNamesJoined(analysis.Captured)) Assert.Equal("Me, x, y", GetSymbolNamesJoined(analysis.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.DataFlowsOut)) Assert.Equal("Me, x, a, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)) Assert.Equal("Me, x, a, y, l1", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)) Assert.Equal("Me, x, y", GetSymbolNamesJoined(analysis.ReadInside)) Assert.Equal("l1", GetSymbolNamesJoined(analysis.WrittenInside)) Assert.Equal("a, y", GetSymbolNamesJoined(analysis.ReadOutside)) Assert.Equal("Me, x, a, y, c", GetSymbolNamesJoined(analysis.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestRegionControlFlowAnalysisInsideLambda() Dim controlFlowAnalysis = CompileAndAnalyzeControlFlow( <compilation name="TestRegionControlFlowAnalysisInsideLambda"> <file name="a.b"> Imports System Module Module1 Sub Main() Static f1 As Func(Of Integer, Integer) = Function(lambdaParam As Integer) [| Return lambdaParam + 1 |] End Function End Sub End Module </file> </compilation>) Assert.Equal(1, controlFlowAnalysis.ExitPoints.Count()) Assert.Equal(0, controlFlowAnalysis.EntryPoints.Count()) Assert.True(controlFlowAnalysis.StartPointIsReachable) Assert.False(controlFlowAnalysis.EndPointIsReachable) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestRegionControlFlowAnalysisInsideLambda2() Dim controlFlowAnalysis = CompileAndAnalyzeControlFlow( <compilation name="TestRegionControlFlowAnalysisInsideLambda2"> <file name="a.b"> Imports System Module Module1 Sub Main() Static f1 As Object = Function(lambdaParam As Integer) [| Return lambdaParam + 1 |] End Function End Sub End Module </file> </compilation>) Assert.Equal(1, controlFlowAnalysis.ExitPoints.Count()) Assert.Equal(0, controlFlowAnalysis.EntryPoints.Count()) Assert.True(controlFlowAnalysis.StartPointIsReachable) Assert.False(controlFlowAnalysis.EndPointIsReachable) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestRegionControlFlowAnalysisInsideLambda3() Dim controlFlowAnalysis = CompileAndAnalyzeControlFlow( <compilation name="TestRegionControlFlowAnalysisInsideLambda3"> <file name="a.b"> Imports System Module Module1 Sub Main() Static f1 As Object = Nothing f1 = Function(lambdaParam As Integer) [| Return lambdaParam + 1 |] End Function End Sub End Module </file> </compilation>) Assert.Equal(1, controlFlowAnalysis.ExitPoints.Count()) Assert.Equal(0, controlFlowAnalysis.EntryPoints.Count()) Assert.True(controlFlowAnalysis.StartPointIsReachable) Assert.False(controlFlowAnalysis.EndPointIsReachable) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub DoLoopInLambdaBody() Dim analysisResults = CompileAndAnalyzeControlAndDataFlow( <compilation name="DoLoopWithContinue"> <file name="a.b"> Class A Function Test1() As Integer Static x As Integer = 5 Console.Write(x) Static x as System.Action(of Integer) = Sub(i) [| Do Console.Write(i) i = i + 1 Continue Do 'Blah Loop Until i > 5 |] end sub Return x End Function End Class </file> </compilation>) Dim controlFlowAnalysisResults = analysisResults.Item1 Dim dataFlowAnalysisResults = analysisResults.Item2 Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()) Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()) Assert.True(controlFlowAnalysisResults.StartPointIsReachable) Assert.True(controlFlowAnalysisResults.EndPointIsReachable) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("Me, x, x, i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("Me, x, x, i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("Me, x, x, i", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub AnonymousTypeAsLambdaLocal() Dim analysisResults = CompileAndAnalyzeControlAndDataFlow( <compilation> <file name="a.vb"> Option Infer On Imports System Public Class Test delegate R Func(OfT, R)(ref T t); Public Shared Sub Main() Dim local(3) As String [| Static lambda As Func(Of Integer, Integer) = Function(ByRef p As Integer) As Integer p = p * 2 Dim at = New With {New C(Of Integer)().F, C(Of String).SF, .L = local.Length + p} Console.Write("{0}, {1}, {2}", at.F, at.SF) Return at.L End Function |] End Sub Class C(Of T) Public Function F() As T Return Nothing End Function Shared Public Function SF() As T Return Nothing End Function End Class End Class </file> </compilation>) Dim controlFlowResults = analysisResults.Item1 Dim dataFlowResults = analysisResults.Item2 Assert.True(controlFlowResults.Succeeded) Assert.True(dataFlowResults.Succeeded) Assert.Equal("lambda", GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal("local", GetSymbolNamesJoined(dataFlowResults.Captured)) Assert.Equal("lambda, p, at", GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal("local", GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Equal("p", GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("local", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnEntry)) Assert.Equal("local, lambda", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnExit)) Assert.Equal("local, p, at", GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal("lambda, p, at", GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("local", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub AnonymousTypeAsNewInLocalContext() Dim analysisResults = CompileAndAnalyzeControlAndDataFlow( <compilation> <file name="a.vb"> Imports System Interface IGoo Delegate Sub DS(ByRef p As Char) End Interface Class CGoo Implements IGoo End Class Friend Module AM Sub Main(args As String()) Static igoo As IGoo = New CGoo() Static at1 As New With {.if = igoo} [| Static at2 As New With {.if = at1, igoo, .friend = New With {Key args, .lambda = DirectCast(Sub(ByRef p As Char) args(0) = p &amp; p p = "Q"c End Sub, IGoo.DS)}} |] Console.Write(args(0)) End Sub End Module </file> </compilation>) Dim controlFlowResults = analysisResults.Item1 Dim dataFlowResults = analysisResults.Item2 Assert.True(controlFlowResults.Succeeded) Assert.True(dataFlowResults.Succeeded) Assert.Equal("at2", GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal("args", GetSymbolNamesJoined(dataFlowResults.Captured)) Assert.Equal("at2, p", GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal("args, igoo, at1", GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Equal("p", GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("args, igoo, at1", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnEntry)) Assert.Equal("args, igoo, at1, at2", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnExit)) Assert.Equal("args, igoo, at1, p", GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal("at2, p", GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal("args, igoo", GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("args, igoo, at1", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub AnonymousTypeAsExpression() Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Interface IGoo Delegate Sub DS(ByRef p As Char) End Interface Friend Module AM Sub Main(args As String()) Static at1 As New With {.friend = New With {args, Key.lambda = DirectCast(Sub(ByRef p As Char) args(0) = p &amp; p p = "Q"c End Sub, IGoo.DS) } } Dim at2 As New With { Key .a= at1, .friend = New With { [| at1 |] }} Console.Write(args(0)) End Sub End Module </file> </compilation>) Assert.True(dataFlowResults.Succeeded) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal("args", GetSymbolNamesJoined(dataFlowResults.Captured)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal("at1", GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("args, at1", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnEntry)) Assert.Equal("args, at1", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnExit)) Assert.Equal("at1", GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal("args, at1, p", GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("args, at1, p, at2", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub AnonymousTypeAccessInstanceMember() Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Class AM Dim field = 123 Sub M(args As String()) Static at1 As New With {.friend = [| New With {args, Key.lambda = Sub(ByRef ary As Char()) Field = ary.Length End Sub } |] } End Sub End Class </file> </compilation>) Assert.True(dataFlowResults.Succeeded) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.Captured)) Assert.Equal("ary", GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal("Me, args", GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Equal("ary", GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("Me, args", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnEntry)) Assert.Equal("Me, args", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnExit)) Assert.Equal("Me, args, ary", GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal("ary", GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("Me, args, at1", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub AnonymousTypeFieldInitializerWithLeftOmitted() Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Class AM Dim field = 123 Sub M(args As String()) Static var1 As New AM Static at1 As New With { var1, .friend = [| .var1 |] } End Sub End Class </file> </compilation>) Assert.True(dataFlowResults.Succeeded) Assert.Null(GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Null(GetSymbolNamesJoined(dataFlowResults.Captured)) Assert.Null(GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Null(GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Null(GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("Me, args, var1", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnEntry)) Assert.Equal("Me, args, var1", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnExit)) Assert.Null(GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Null(GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal("var1", GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("Me, args, var1, at1", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub AnonymousTypeUsingMe() Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Class Base Protected Function F1() As Long Return 123 End Function Friend Overridable Function F2(n As Integer) As Integer Return 456 End Function End Class Class Derived Inherits Base Friend Overrides Function F2(n As Integer) As Integer Return 789 End Function Sub M() Dim func = Function(x) Dim at = [| New With {.dim = New With {Key .nested = Me.F2(x * x)}} |] Return at.dim.nested End Function End Sub End Class </file> </compilation>) Assert.True(dataFlowResults.Succeeded) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.Captured)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal("Me, x", GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("Me, func, x", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnEntry)) Assert.Equal("Me, func, x", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnExit)) Assert.Equal("Me, x", GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal("at", GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("Me, func, x, at", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub AnonymousTypeAccessMyBase() Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Class Base Protected Overridable Function F1() As Long Return 123 End Function End Class Class Derived Inherits Base Protected Overrides Function F1() As Long Return 789 End Function Sub M() Static func = Function(x) Dim at = [| New With {Key .dim = New With {MyBase.F1()}} |] Return at.dim.F1 End Function End Sub End Class </file> </compilation>) Assert.True(dataFlowResults.Succeeded) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.Captured)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("Me, func, x", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnEntry)) Assert.Equal("Me, func, x", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnExit)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal("at", GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("Me, func, x, at", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub AnonymousTypeAccessMyClass() Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Module M1 Class B1 Public Overridable Function F() As String Return "B1::F_" End Function End Class Class B2 Inherits B1 Public Overrides Function F() As String Return "B2::F_" End Function Public Sub TestMMM() Static an = [| New With {.an = Function(s) As String Return s + Me.F() + MyBase.F() + MyClass.F() End Function } |] Console.WriteLine(an.an("R=")) End Sub End Class Class D Inherits B2 Public Overrides Function F() As String Return "D::F_" End Function End Class Public Sub Main() Call (New D()).TestMMM() End Sub End Module </file> </compilation>) Assert.True(dataFlowResults.Succeeded) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.Captured)) Assert.Equal("s", GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnEntry)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnExit)) Assert.Equal("Me, s", GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal("s", GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal("an", GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("Me, an", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub AddressOfExpr() Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Module Program Sub Main() Static x5 = Function() AddressOf [|Main|] End Sub End Module </file> </compilation>) Assert.True(dataFlowResults.Succeeded) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub XmlEmbeddedExpression() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports System.Xml.Linq Module M Function F() As Object Static v0 = "v0" Static v1 = XName.Get("v1", "") Static v2 = XName.Get("v2", "") Static v3 = "v3" Static v4 = New XAttribute(XName.Get("v4", ""), "v4") Static v5 = "v5" Return <?xml version="1.0"?><<%= v1 %> <%= v2 %>="v2" v3=<%= v3 %> <%= v4 %>><%= v5 %></> End Function End Module ]]></file> </compilation>, references:=XmlReferences) Dim tree = compilation.SyntaxTrees.First() Dim model = compilation.GetSemanticModel(tree) Dim root = tree.GetCompilationUnitRoot() Dim node = DirectCast(root.FindToken(root.ToFullString().IndexOf("Return", StringComparison.Ordinal)).Parent, StatementSyntax) Dim dataFlowAnalysis = model.AnalyzeDataFlow(node, node) Assert.True(dataFlowAnalysis.Succeeded) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.AlwaysAssigned)) Assert.Equal("v1, v2, v3, v4, v5", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsOut)) Assert.Equal("v0, v1, v2, v3, v4, v5", GetSymbolNamesJoined(dataFlowAnalysis.DefinitelyAssignedOnEntry)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.DefinitelyAssignedOnExit)) Assert.Equal("v1, v2, v3, v4, v5", GetSymbolNamesJoined(dataFlowAnalysis.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.WrittenInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.ReadOutside)) Assert.Equal("v0, v1, v2, v3, v4, v5", GetSymbolNamesJoined(dataFlowAnalysis.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub XmlMemberAccess() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports System.Xml.Linq Module M Function F() As Object Static x = <a><b><c d="e"/></b></a> Return x.<b>...<c>.@<d> End Function End Module ]]></file> </compilation>, references:=XmlReferences) Dim tree = compilation.SyntaxTrees.First() Dim model = compilation.GetSemanticModel(tree) Dim root = tree.GetCompilationUnitRoot() Dim node = DirectCast(root.FindToken(root.ToFullString().IndexOf("Return", StringComparison.Ordinal)).Parent, StatementSyntax) Dim dataFlowAnalysis = model.AnalyzeDataFlow(node, node) Assert.True(dataFlowAnalysis.Succeeded) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.AlwaysAssigned)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsOut)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.DefinitelyAssignedOnEntry)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.DefinitelyAssignedOnExit)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.WrittenInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.ReadOutside)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub GenericStructureCycle() Dim source = <compilation> <file name="c.vb"><![CDATA[ Structure S(Of T) Public F As S(Of S(Of T)) End Structure Module M Sub M() Static o As S(Of Object) End Sub End Module ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source) Dim tree = compilation.SyntaxTrees.First() Dim model = compilation.GetSemanticModel(tree) Dim root = tree.GetCompilationUnitRoot() Dim node = DirectCast(root.FindToken(root.ToFullString().IndexOf("Static", StringComparison.Ordinal)).Parent, StatementSyntax) Dim dataFlowAnalysis = model.AnalyzeDataFlow(node, node) Assert.True(dataFlowAnalysis.Succeeded) Assert.Equal("o", GetSymbolNamesJoined(dataFlowAnalysis.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsOut)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.DefinitelyAssignedOnEntry)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.DefinitelyAssignedOnExit)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.WrittenInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.WrittenOutside)) End Sub #End Region #Region "With Statement" <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub WithStatement_Expression_RValue_3() Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Structure SSS Public A As String Public B As Integer Public Sub New(_a As String, _b As Integer) End Sub End Structure Class Clazz Sub TEST(i As Integer) With [| New SSS(Me.ToString(), i) |] Static s As Action = Sub() .A = "" End Sub End With End Sub End Class </file> </compilation>) Assert.True(dataFlowResults.Succeeded) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.Captured)) Assert.Equal("Me, i", GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("Me, i", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnEntry)) Assert.Equal("Me, i", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnExit)) Assert.Equal("Me, i", GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("Me, i, s", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub WithStatement_Expression_LValue_1() Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Structure SSS Public A As String Public B As Integer Public Sub New(_a As String, _b As Integer) End Sub End Structure Class Clazz Sub TEST(i As Integer) Static x As New SSS(Me.ToString(), i) With [| x |] End With End Sub End Class </file> </compilation>) Assert.False(dataFlowResults.Succeeded) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub WithStatement_Expression_LValue_2() Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Structure SSS Public A As String Public B As Integer Public Sub New(_a As String, _b As Integer) End Sub End Structure Class Clazz Sub TEST(i As Integer) Static x As New SSS(Me.ToString(), i) With [| x |] .A = "" End With End Sub End Class </file> </compilation>) Assert.True(dataFlowResults.Succeeded) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.Captured)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("Me, i, x", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnEntry)) Assert.Equal("Me, i, x", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnExit)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal("Me, i", GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("Me, i, x", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub WithStatement_Expression_LValue_2_() Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Structure SSS Public A As String Public B As Integer Public Sub New(_a As String, _b As Integer) End Sub End Structure Class Clazz Sub TEST(i As Integer) Static x As New SSS(Me.ToString(), i) With [| x |] .A = "" Dim a = .A Dim b = .B .B = 1 End With End Sub End Class </file> </compilation>) Assert.True(dataFlowResults.Succeeded) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.Captured)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("Me, i, x", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnEntry)) Assert.Equal("Me, i, x", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnExit)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal("Me, i, x", GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("Me, i, x, a, b", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub WithStatement_Expression_LValue_2a() Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Structure SSS Public A As String Public B As Integer Public Sub New(_a As String, _b As Integer) End Sub End Structure Class Clazz Sub TEST(i As Integer) Static x As New SSS(Me.ToString(), i) With x [| .A = "" |] End With End Sub End Class </file> </compilation>) Assert.True(dataFlowResults.Succeeded) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.Captured)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("Me, i, x", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnEntry)) Assert.Equal("Me, i, x", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnExit)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal("Me, i", GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("Me, i, x", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub WithStatement_Expression_LValue_2b() Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Structure SSS Public A As String Public B As Integer Public Sub New(_a As String, _b As Integer) End Sub End Structure Class Clazz Sub TEST(i As Integer) Static x As New SSS(Me.ToString(), i) With x [| .B = "" |] End With End Sub End Class </file> </compilation>) Assert.True(dataFlowResults.Succeeded) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.Captured)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("Me, i, x", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnEntry)) Assert.Equal("Me, i, x", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnExit)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal("Me, i", GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("Me, i, x", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub WithStatement_Expression_LValue_3() Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Structure SSS Public A As String Public B As Integer Public Sub New(_a As String, _b As Integer) End Sub End Structure Class Clazz Sub TEST(i As Integer) Static x As New SSS(Me.ToString(), i) With [| x |] Dim s As Action = Sub() .A = "" End Sub End With End Sub End Class </file> </compilation>) Assert.True(dataFlowResults.Succeeded) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.Captured)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("Me, i, x, s", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnEntry)) Assert.Equal("Me, i, x, s", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnExit)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal("Me, i", GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("Me, i, x, s", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub WithStatement_Expression_LValue_4() Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Structure SSSS Public A As String Public B As Integer End Structure Structure SSS Public S As SSSS nd Structure Class Clazz Sub TEST() Static x As New SSS() With [| x.S |] Dim s As Action = Sub() .A = "" End Sub End With End Sub End Class </file> </compilation>) Assert.True(dataFlowResults.Succeeded) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.Captured)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("Me, x, s", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnEntry)) Assert.Equal("Me, x, s", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnExit)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("Me, x, s", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub WithStatement_Expression_LValue_4a() Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Structure SSSS Public A As String Public B As Integer End Structure Structure SSS Public S As SSSS nd Structure Class Clazz Sub TEST() Static x As New SSS() With [| x |] .S Dim s As Action = Sub() .A = "" End Sub End With End Sub End Class </file> </compilation>) Assert.True(dataFlowResults.Succeeded) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.Captured)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("Me, x, s", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnEntry)) Assert.Equal("Me, x, s", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnExit)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("Me, x, s", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub WithStatement_Expression_LValue_4b() Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Structure SSSS Public A As String Public B As Integer End Structure Structure SSS Public S As SSSS nd Structure Class Clazz Sub TEST() Static x As New SSS() With x.S Dim s As Action = Sub() [| .A = "" |] End Sub End With x.ToString() End Sub End Class </file> </compilation>) Assert.True(dataFlowResults.Succeeded) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.Captured)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("Me, x, s", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnEntry)) Assert.Equal("Me, x, s", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnExit)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("Me, x, s", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub WithStatement_Expression_LValue_4c() Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Structure SSSS Public A As String Public B As Integer End Structure Structure SSS Public S As SSSS nd Structure Class Clazz Sub TEST() Static x As New SSS() With x.S Dim s As Action = Sub() [| .A |] = "" End Sub End With x.ToString() End Sub End Class </file> </compilation>) Assert.True(dataFlowResults.Succeeded) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.Captured)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("Me, x, s", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnEntry)) Assert.Equal("Me, x, s", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnExit)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("Me, x, s", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <ConditionalFact(GetType(NoUsedAssembliesValidation))> ' https://github.com/dotnet/roslyn/issues/40684: The test hook is blocked by this issue. <WorkItem(40684, "https://github.com/dotnet/roslyn/issues/40684")> Public Sub WithStatement_Expression_LValue_4d() Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Structure SSSS3 Public A As String Public B As Integer End Structure Structure SSSS2 Public S3 As SSSS3 End Structure Structure SSSS Public S2 As SSSS2 End Structure Structure SSS Public S As SSSS End Structure Class Clazz Sub TEST() Static x As New SSS() With x.S With .S2 With .S3 Static s As Action = Sub() [| .A = "" |] End Sub End With End With End With x.ToString() End Sub End Class </file> </compilation>) Assert.True(dataFlowResults.Succeeded) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.Captured)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("Me, x, s", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnEntry)) Assert.Equal("Me, x, s", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnExit)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("Me, x, s", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <ConditionalFact(GetType(NoUsedAssembliesValidation))> ' https://github.com/dotnet/roslyn/issues/40684: The test hook is blocked by this issue. <WorkItem(40684, "https://github.com/dotnet/roslyn/issues/40684")> Public Sub WithStatement_Expression_LValue_4e() Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Structure SSSS3 Public A As String Public B As Integer End Structure Structure SSSS2 Public S3 As SSSS3 End Structure Structure SSSS Public S2 As SSSS2 End Structure Structure SSS Public S As SSSS End Structure Class Clazz Sub TEST() Static x As New SSS() With x.S With .S2 With .S3 Static s As Action = Sub() Dim xyz = [| .A |] End Sub End With End With End With x.ToString() End Sub End Class </file> </compilation>) Assert.True(dataFlowResults.Succeeded) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.Captured)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("Me, x, s", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnEntry)) Assert.Equal("Me, x, s", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnExit)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("Me, x, s, xyz", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub WithStatement_Expression_LValue_4f() Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Structure SSSS3 Public A As String Public B As Integer End Structure Structure SSSS2 Public S3 As SSSS3 End Structure Structure SSSS Public S2 As SSSS2 End Structure Structure SSS Public S As SSSS End Structure Class Clazz Sub TEST() Static x As New SSS() With [| x.S.S2 |].S3 Static s As Action = Sub() .A = "" End Sub End With x.ToString() End Sub End Class </file> </compilation>) Assert.True(dataFlowResults.Succeeded) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.Captured)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("Me, x, s", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnEntry)) Assert.Equal("Me, x, s", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnExit)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("Me, x, s", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub WithStatement_Expression_LValue_4g() Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Structure SSSS3 Public A As String Public B As Integer End Structure Structure SSSS2 Public S3 As SSSS3 End Structure Structure SSSS Public S2 As SSSS2 End Structure Class SSS Public S As SSSS End Class Class Clazz Sub TEST() Static x As New SSS() With [| x.S.S2 |].S3 Static s As Action = Sub() .A = "" End Sub End With x.ToString() End Sub End Class </file> </compilation>) Assert.True(dataFlowResults.Succeeded) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.Captured)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("Me, x", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnEntry)) Assert.Equal("Me, x", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnExit)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("Me, x, s", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub WithStatement_MeReference_1() Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Structure SSSS3 Public A As String Public B As Integer End Structure Structure SSSS2 Public S3 As SSSS3 End Structure Structure SSSS Public S2 As SSSS2 End Structure Structure SSS Public S As SSSS End Structure Class Clazz Public x As New SSS() Sub TEST() With [| x.S.S2 |].S3 Static s As Action = Sub() .A = "" End Sub End With x.ToString() End Sub End Class </file> </compilation>) Assert.True(dataFlowResults.Succeeded) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.Captured)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("Me, s", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnEntry)) Assert.Equal("Me, s", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnExit)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("Me, s", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub WithStatement_ComplexExpression_1() Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Structure SSSS3 Public A As String Public B As Integer End Structure Structure SSSS2 Public S3 As SSSS3 End Structure Structure SSSS Public S2 As SSSS2 End Structure Structure SSS Public S As SSSS End Structure Class Clazz Public x As New SSS() Sub TEST() With DirectCast(Function() Return [| Me.x |] End Function, Func(Of SSS))() With .S.S2 Static a = .S3.A End With End With x.ToString() End Sub End Class </file> </compilation>) Assert.True(dataFlowResults.Succeeded) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.Captured)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnEntry)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnExit)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("Me, a", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub WithStatement_ComplexExpression_2() Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Structure SSSS3 Public A As String Public B As Integer End Structure Structure SSSS2 Public S3 As SSSS3 End Structure Structure SSSS Public S2 As SSSS2 End Structure Structure SSS Public S As SSSS End Structure Class Clazz Public x As New SSS() Sub TEST() Static arr(,) As SSS With arr(1, [| DirectCast(Function() Return x End Function, Func(Of SSS)) |] ().S.S2.S3.B).S Static a = .S2.S3.A End With x.ToString() End Sub End Class </file> </compilation>) Assert.True(dataFlowResults.Succeeded) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.Captured)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnEntry)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnExit)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal("Me, arr", GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("Me, a", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub #End Region #Region "Select Statement" <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestSelectCase_Empty() Dim analysis = CompileAndAnalyzeControlAndDataFlow( <compilation name="TestSelectCase_Empty"> <file name="a.b"> Module Program Sub Main() Static obj As Object = 0 [| Select Case obj End Select |] End Sub End Module </file> </compilation>) Dim controlFlowResults = analysis.Item1 Assert.True(controlFlowResults.Succeeded) Assert.Equal(0, controlFlowResults.ExitPoints.Count()) Assert.Equal(0, controlFlowResults.EntryPoints.Count()) Assert.True(controlFlowResults.EndPointIsReachable) Dim dataFlowResults = analysis.Item2 Assert.True(dataFlowResults.Succeeded) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.Captured)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal("obj", GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("obj", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnEntry)) Assert.Equal("obj", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnExit)) Assert.Equal("obj", GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("obj", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestSelectCase_SingleCaseBlock_01() Dim analysis = CompileAndAnalyzeControlAndDataFlow( <compilation name="TestSelectCase_SingleCaseBlock_01"> <file name="a.b"> Module Program Sub Main() Static obj1 As Object = 0 Static obj2 As Object = 0 Static obj3 As Object [| Select Case obj1 Case obj2 Static obj4 = 1 obj3 = obj4 End Select |] End Sub End Module </file> </compilation>) Dim controlFlowResults = analysis.Item1 Assert.True(controlFlowResults.Succeeded) Assert.Equal(0, controlFlowResults.ExitPoints.Count()) Assert.Equal(0, controlFlowResults.EntryPoints.Count()) Assert.True(controlFlowResults.EndPointIsReachable) Dim dataFlowResults = analysis.Item2 Assert.True(dataFlowResults.Succeeded) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.Captured)) Assert.Equal("obj4", GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal("obj1, obj2, obj4", GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("obj1, obj2", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnEntry)) Assert.Equal("obj1, obj2", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnExit)) Assert.Equal("obj1, obj2, obj4", GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal("obj3, obj4", GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("obj1, obj2", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestSelectCase_SingleCaseBlock_02() Dim analysis = CompileAndAnalyzeControlAndDataFlow( <compilation name="TestSelectCase_SingleCaseBlock_02"> <file name="a.b"> Module Program Sub Main() Static obj1 As Object = 0 Static obj2 As Object = 0 Static obj3 As Object Select Case obj1 Case obj2 [| Static obj4 = 1 obj3 = obj4 |] End Select End Sub End Module </file> </compilation>) Dim controlFlowResults = analysis.Item1 Assert.True(controlFlowResults.Succeeded) Assert.Equal(0, controlFlowResults.ExitPoints.Count()) Assert.Equal(0, controlFlowResults.EntryPoints.Count()) Assert.True(controlFlowResults.EndPointIsReachable) Dim dataFlowResults = analysis.Item2 Assert.True(dataFlowResults.Succeeded) Assert.Equal("obj3, obj4", GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.Captured)) Assert.Equal("obj4", GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal("obj4", GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("obj1, obj2", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnEntry)) Assert.Equal("obj1, obj2, obj3, obj4", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnExit)) Assert.Equal("obj4", GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal("obj3, obj4", GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal("obj1, obj2", GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("obj1, obj2", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestSelectCase_CaseBlocksWithCaseElse_01() Dim analysis = CompileAndAnalyzeControlAndDataFlow( <compilation name="TestSelectCase_CaseBlocksWithCaseElse_01"> <file name="a.b"> Module Program Sub Main() Static obj1 As Object = 0 Static obj2 As Object = 0 Static obj3 As Object Static obj4 As Object [| Select Case obj1 Case obj2 Static obj5 = 1 obj3 = obj5 obj4 = obj5 Case Else Static obj5 = 2 obj2 = obj5 obj4 = obj5 End Select |] obj1 = obj3 + obj4 End Sub End Module </file> </compilation>) Dim controlFlowResults = analysis.Item1 Assert.True(controlFlowResults.Succeeded) Assert.Equal(0, controlFlowResults.ExitPoints.Count()) Assert.Equal(0, controlFlowResults.EntryPoints.Count()) Assert.True(controlFlowResults.EndPointIsReachable) Dim dataFlowResults = analysis.Item2 Assert.True(dataFlowResults.Succeeded) Assert.Equal("obj4", GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.Captured)) Assert.Equal("obj5, obj5", GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal("obj1, obj2, obj5, obj5", GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Equal("obj2, obj3, obj4", GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("obj1, obj2", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnEntry)) Assert.Equal("obj1, obj2, obj4", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnExit)) Assert.Equal("obj1, obj2, obj5, obj5", GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal("obj2, obj3, obj4, obj5, obj5", GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal("obj3, obj4", GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("obj1, obj2", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestSelectCase_CaseBlocksWithCaseElse_01_CaseElseRegion() Dim analysis = CompileAndAnalyzeControlAndDataFlow( <compilation name="TestSelectCase_CaseBlocksWithCaseElse_01_CaseElseRegion"> <file name="a.b"> Module Program Sub Main() Static obj1 As Object = 0 Static obj2 As Object = 0 Static obj3 As Object Static obj4 As Object Select Case obj1 Case obj2 Static obj5 = 1 obj3 = obj5 obj4 = obj5 Case Else [| Static obj5 = 2 obj2 = obj5 obj4 = obj5 |] End Select obj1 = obj3 + obj4 End Sub End Module </file> </compilation>) Dim controlFlowResults = analysis.Item1 Assert.True(controlFlowResults.Succeeded) Assert.Equal(0, controlFlowResults.ExitPoints.Count()) Assert.Equal(0, controlFlowResults.EntryPoints.Count()) Assert.True(controlFlowResults.EndPointIsReachable) Dim dataFlowResults = analysis.Item2 Assert.True(dataFlowResults.Succeeded) Assert.Equal("obj2, obj4, obj5", GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.Captured)) Assert.Equal("obj5", GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal("obj5", GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Equal("obj2, obj4", GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("obj1, obj2", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnEntry)) Assert.Equal("obj1, obj2, obj4, obj5", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnExit)) Assert.Equal("obj5", GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal("obj2, obj4, obj5", GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal("obj1, obj2, obj3, obj4, obj5", GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("obj1, obj2, obj3, obj4, obj5", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestSelectCase_CaseBlocksWithCaseElse_02() Dim analysis = CompileAndAnalyzeControlAndDataFlow( <compilation name="TestSelectCase_CaseBlocksWithCaseElse_02"> <file name="a.b"> Module Program Sub Main() Static obj1 As Object = 0 Static obj2 As Object = 0 Static obj3 As Object [| Select Case obj1 Case obj2 Static obj4 = 1 obj3 = obj4 Case Else End Select |] End Sub End Module </file> </compilation>) Dim controlFlowResults = analysis.Item1 Assert.True(controlFlowResults.Succeeded) Assert.Equal(0, controlFlowResults.ExitPoints.Count()) Assert.Equal(0, controlFlowResults.EntryPoints.Count()) Assert.True(controlFlowResults.EndPointIsReachable) Dim dataFlowResults = analysis.Item2 Assert.True(dataFlowResults.Succeeded) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.Captured)) Assert.Equal("obj4", GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal("obj1, obj2, obj4", GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("obj1, obj2", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnEntry)) Assert.Equal("obj1, obj2", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnExit)) Assert.Equal("obj1, obj2, obj4", GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal("obj3, obj4", GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("obj1, obj2", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestSelectCase_CaseBlockWithCaseElse_03() Dim analysis = CompileAndAnalyzeControlAndDataFlow( <compilation name="TestSelectCase_CaseBlockWithCaseElse_03"> <file name="a.b"> Module Program Sub Main() Static obj1 As Object = 0 Static obj2 As Object = 0 Static obj3 As Object [| Select Case obj1 Case obj2 LabelCase: Static obj4 = 1 obj3 = obj4 Case Else Goto LabelCase End Select |] End Sub End Module </file> </compilation>) Dim controlFlowResults = analysis.Item1 Assert.True(controlFlowResults.Succeeded) Assert.Equal(0, controlFlowResults.ExitPoints.Count()) Assert.Equal(0, controlFlowResults.EntryPoints.Count()) Assert.True(controlFlowResults.EndPointIsReachable) Dim dataFlowResults = analysis.Item2 Assert.True(dataFlowResults.Succeeded) Assert.Equal("obj3, obj4", GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.Captured)) Assert.Equal("obj4", GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal("obj1, obj2, obj4", GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("obj1, obj2", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnEntry)) Assert.Equal("obj1, obj2, obj3, obj4", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnExit)) Assert.Equal("obj1, obj2, obj4", GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal("obj3, obj4", GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("obj1, obj2", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestSelectCase_CaseBlocksWithoutCaseElse_01() Dim analysis = CompileAndAnalyzeControlAndDataFlow( <compilation name="TestSelectCase_CaseBlocksWithoutCaseElse_01"> <file name="a.b"> Module Program Sub Main() Static obj1 As Object = 0 Static obj2 As Object = 0 Static obj3 As Object Static obj4 As Object [| Select Case obj1 Case obj2 Static obj5 = 1 obj3 = obj5 obj4 = obj5 Case obj3 Static obj5 = 2 obj2 = obj5 obj4 = obj5 End Select |] obj1 = obj3 + obj4 End Sub End Module </file> </compilation>) Dim controlFlowResults = analysis.Item1 Assert.True(controlFlowResults.Succeeded) Assert.Equal(0, controlFlowResults.ExitPoints.Count()) Assert.Equal(0, controlFlowResults.EntryPoints.Count()) Assert.True(controlFlowResults.EndPointIsReachable) Dim dataFlowResults = analysis.Item2 Assert.True(dataFlowResults.Succeeded) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.Captured)) Assert.Equal("obj5, obj5", GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal("obj1, obj2, obj3, obj5, obj5", GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Equal("obj2, obj3, obj4", GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("obj1, obj2", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnEntry)) Assert.Equal("obj1, obj2", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnExit)) Assert.Equal("obj1, obj2, obj3, obj5, obj5", GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal("obj2, obj3, obj4, obj5, obj5", GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal("obj3, obj4", GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("obj1, obj2", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestSelectCase_CaseBlockWithoutCaseElse_02() Dim analysis = CompileAndAnalyzeControlAndDataFlow( <compilation name="TestSelectCase_CaseBlockWithoutCaseElse_02"> <file name="a.b"> Module Program Sub Main() Static obj1 As Object = 0 Static obj2 As Object = 0 Static obj3 As Object [| Select Case obj1 Case obj2 LabelCase: Static obj4 = 1 obj3 = obj4 Case obj3 Goto LabelCase End Select |] End Sub End Module </file> </compilation>) Dim controlFlowResults = analysis.Item1 Assert.True(controlFlowResults.Succeeded) Assert.Equal(0, controlFlowResults.ExitPoints.Count()) Assert.Equal(0, controlFlowResults.EntryPoints.Count()) Assert.True(controlFlowResults.EndPointIsReachable) Dim dataFlowResults = analysis.Item2 Assert.True(dataFlowResults.Succeeded) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.Captured)) Assert.Equal("obj4", GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal("obj1, obj2, obj3, obj4", GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Equal("obj3", GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("obj1, obj2", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnEntry)) Assert.Equal("obj1, obj2", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnExit)) Assert.Equal("obj1, obj2, obj3, obj4", GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal("obj3, obj4", GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("obj1, obj2", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestSelectCase_CaseStatementRegion() Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation name="TestSelectCase_CaseStatementRegion"> <file name="a.b"> Module Program Sub Main() Static obj1 As Object = 0 Static obj2 As Object = 0 Static obj3 As Object Select Case obj1 Case [|obj2|] obj3 = 0 End Select End Sub End Module </file> </compilation>) Assert.True(dataFlowResults.Succeeded) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.Captured)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("obj1, obj2", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnEntry)) Assert.Equal("obj1, obj2", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnExit)) Assert.Equal("obj2", GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal("obj1", GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("obj1, obj2, obj3", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestSelectCase_Error_CaseElseBeforeCaseBlock() Dim analysis = CompileAndAnalyzeControlAndDataFlow( <compilation name="TestSelectCase_Error_CaseElseBeforeCaseBlock"> <file name="a.b"> Module Program Sub Main() Static obj1 As Object = 0 Static obj2 As Object = 0 Static obj3 As Object Static obj4 As Object Select Case obj1 Case Else [| Static obj5 = 2 obj2 = obj5 obj4 = obj5 |] Case obj2 Static obj5 = 1 obj3 = obj5 obj4 = obj5 End Select obj1 = obj3 + obj4 End Sub End Module </file> </compilation>) Dim controlFlowResults = analysis.Item1 Assert.True(controlFlowResults.Succeeded) Assert.Equal(0, controlFlowResults.ExitPoints.Count()) Assert.Equal(0, controlFlowResults.EntryPoints.Count()) Assert.True(controlFlowResults.EndPointIsReachable) Dim dataFlowResults = analysis.Item2 Assert.True(dataFlowResults.Succeeded) Assert.Equal("obj2, obj4, obj5", GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.Captured)) Assert.Equal("obj5", GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal("obj5", GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Equal("obj2, obj4", GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("obj1, obj2", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnEntry)) Assert.Equal("obj1, obj2, obj4, obj5", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnExit)) Assert.Equal("obj5", GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal("obj2, obj4, obj5", GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal("obj1, obj2, obj3, obj4, obj5", GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("obj1, obj2, obj3, obj4, obj5", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <WorkItem(529089, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529089")> <Fact> Public Sub CaseClauseNotReachable() Dim analysis = CompileAndAnalyzeControlAndDataFlow( <compilation name="TestSelectCase_Error_CaseElseBeforeCaseBlock"> <file name="a.b"> Module Program Sub Main(args As String()) Static x = 10 Select Case 5 Case 10 [|x = x + 1|] End Select End Sub End Module </file> </compilation>) Dim controlFlowResults = analysis.Item1 Assert.True(controlFlowResults.Succeeded) Assert.Equal(0, controlFlowResults.ExitPoints.Count()) Assert.Equal(0, controlFlowResults.EntryPoints.Count()) Assert.True(controlFlowResults.StartPointIsReachable) Assert.True(controlFlowResults.EndPointIsReachable) Dim dataFlowResults = analysis.Item2 Assert.True(dataFlowResults.Succeeded) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.Captured)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("args, x", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnEntry)) Assert.Equal("args, x", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnExit)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("args, x", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub MyBaseExpressionSyntax() Dim source = <compilation> <file name="a.vb"> Imports System Public Class BaseClass Public Overridable Sub MyMeth() End Sub End Class Public Class MyClass : Inherits BaseClass Public Overrides Sub MyMeth() MyBase.MyMeth() End Sub Public Sub OtherMeth() Static f = Function() MyBase End Sub End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlib40(source) Dim tree = comp.SyntaxTrees.Single() Dim model = comp.GetSemanticModel(tree) Dim invocation = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of InvocationExpressionSyntax)().Single() Dim flowAnalysis = model.AnalyzeDataFlow(invocation) Assert.Empty(flowAnalysis.Captured) Assert.Equal("Me As [MyClass]", flowAnalysis.DataFlowsIn.Single().ToTestDisplayString()) Assert.Empty(flowAnalysis.DataFlowsOut) Assert.Equal("Me As [MyClass]", flowAnalysis.ReadInside.Single().ToTestDisplayString()) Assert.Empty(flowAnalysis.WrittenInside) Assert.Equal("Me As [MyClass]", flowAnalysis.WrittenOutside.Single().ToTestDisplayString()) Dim lambda = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of LambdaExpressionSyntax)().Single() flowAnalysis = model.AnalyzeDataFlow(lambda) Assert.Equal("Me As [MyClass]", flowAnalysis.Captured.Single().ToTestDisplayString()) Assert.Equal("Me As [MyClass]", flowAnalysis.DataFlowsIn.Single().ToTestDisplayString()) Assert.Empty(flowAnalysis.DataFlowsOut) Assert.Equal("Me As [MyClass]", flowAnalysis.ReadInside.Single().ToTestDisplayString()) Assert.Empty(flowAnalysis.WrittenInside) Assert.Equal("Me, f", GetSymbolNamesJoined(flowAnalysis.WrittenOutside)) End Sub #End Region End Class End Namespace
' 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.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Partial Public Class FlowAnalysisTestsWithStaticLocals Inherits FlowTestBase 'All the scenarios have had local declarations changed to Static Local Declarations to Ensure that the 'flow analysis for static locals is exactly the same as for normal local declarations. ' 'The scenarios here should be the same as those in RegionAnalysisTest.vb with the exception of 'a. scenarios that did not involve any locals or 'b. scenarios with locals declared in lambda's only 'c. scenarios using IL ' 'The method names should be the same as those in RegionAnalysisTest.vb and the tests should result in the same 'flow analysis despite the fact that the implementation for static locals is different because of the implementation 'required to preserve state across multiple invocations. ' 'Multiple calls are NOT required to verify the flow analysis for static locals. <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Bug11067() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="Bug11067"> <file name="a.b"> Class Test Public Shared Sub Main() Static y(,) = New Integer(,) {{[|From|]}} End Sub End Class </file> </compilation>) Assert.True(analysis.Succeeded) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Bug13053a() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="Bug13053a"> <file name="a.b"> Class Test Public Shared Sub Main() Static i As Integer = 1 Static o = New MyObject With { .A = [| i |] } End Sub End Class </file> </compilation>) Assert.True(analysis.Succeeded) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub XmlNameInsideEndTag() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="XmlNameInsideEndTag"> <file name="a.b"> Module Module1 Sub S(par As Integer) Static a = &lt;tag&gt; &lt;/ [| tag |] &gt; End Sub End Module </file> </compilation>) Assert.False(analysis.Succeeded) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub ExpressionsInAttributeValues2() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="ExpressionsInAttributeValues2"> <file name="a.b"> Imports System Imports System.Reflection Public Class MyAttribute Public Sub New(p As Object) End Sub End Class &lt;MyAttribute(p:=Sub() [|Static a As Integer = 1 While a &lt; 110 a += 1 End While|] End Sub)&gt; Module Program Sub Main(args As String()) End Sub End Module </file> </compilation>) Assert.False(analysis.Succeeded) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub LowerBoundOfArrayDefinitionSize() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="LowerBoundOfArrayDefinitionSize"> <file name="a.b"> Class Test Public Shared Sub S(x As Integer) Static newTypeArguments([|0|] To x - 1) As String End Sub End Class </file> </compilation>) Assert.False(analysis.Succeeded) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Bug11440b() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="Bug11440"> <file name="a.b"> Imports System Module Program Sub Main(args As String()) GoTo Label Static arg2 As Integer = 2 Label: Static y = [| arg2 |] End Sub End Module </file> </compilation>) Assert.True(analysis.Succeeded) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.Captured)) Assert.Equal("arg2", GetSymbolNamesJoined(analysis.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.DataFlowsOut)) Assert.Equal("args", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)) Assert.Equal("args", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)) Assert.Equal("arg2", GetSymbolNamesJoined(analysis.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.WrittenInside)) Assert.Equal("args, arg2, y", GetSymbolNamesJoined(analysis.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Bug12423a() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="Bug12423a"> <file name="a.b"> Class A Sub Goo() Static x = { [| New B (abc) |] } End Sub End Class Class B Public Sub New(i As Integer) End Sub End Class </file> </compilation>) Assert.True(analysis.Succeeded) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Bug12423b() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="Bug12423b"> <file name="a.b"> Class A Sub Goo(i As Integer) Static x = New B([| i |] ) { New B (abc) } End Sub End Class Class B Public Sub New(i As Integer) End Sub End Class </file> </compilation>) Assert.True(analysis.Succeeded) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestDataFlowForValueTypes() ' WARNING: test matches the same test in C# (TestDataFlowForValueTypes) ' Keep the two tests in sync Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="TestDataFlowForValueTypes"> <file name="a.b"> Imports System Class Tst Shared Sub Tst() Static a As S0 Static b As S1 Static c As S2 Static d As S3 Static e As E0 Static f As E1 [| Console.WriteLine(a) Console.WriteLine(b) Console.WriteLine(c) Console.WriteLine(d) Console.WriteLine(e) Console.WriteLine(f) |] End Sub End Class Structure S0 End Structure Structure S1 Public s0 As S0 End Structure Structure S2 Public s0 As S0 Public s1 As Integer End Structure Structure S3 Public s0 As S0 Public s1 As Object End Structure Enum E0 End Enum Enum E1 V1 End Enum </file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.Captured)) Assert.Equal("c, d, e, f", GetSymbolNamesJoined(analysis.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.DataFlowsOut)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)) Assert.Equal("a, b, c, d, e, f", GetSymbolNamesJoined(analysis.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.WrittenInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Bug10987() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="Bug10987"> <file name="a.b"> Class Test Public Shared Sub Main() Static y(1, 2) = [|New Integer|] End Sub End Class </file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.DataFlowsOut)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.WrittenInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.ReadOutside)) Assert.Equal("y", GetSymbolNamesJoined(analysis.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestExpressionInIfStatement() Dim dataFlowAnalysis = CompileAndAnalyzeDataFlow( <compilation name="TestExpressionInIfStatement"> <file name="a.b"> Module Program Sub Main() Static x = 1 If 1 = [|x|] Then End If End Sub End Module </file> </compilation>) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsIn)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.DefinitelyAssignedOnEntry)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.DefinitelyAssignedOnExit)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub CallingMethodsOnUninitializedStructs() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="CallingMethodsOnUninitializedStructs2"> <file name="a.b"> Public Structure XXX Public x As S(Of Object) Public y As S(Of String) End Structure Public Structure S(Of T) Public x As String Public Property y As T End Structure Public Class Test Public Shared Sub Main(args As String()) Static s As XXX s.x = New S(Of Object)() [|s.x.y.ToString()|] Static t As Object = s End Sub Public Shared Sub S1(ByRef arg As XXX) arg.x.x = "" arg.x.y = arg.x.x End Sub End Class </file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.Captured)) Assert.Equal("s", GetSymbolNamesJoined(analysis.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.DataFlowsOut)) Assert.Equal("args", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)) Assert.Equal("args", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)) Assert.Equal("s", GetSymbolNamesJoined(analysis.ReadInside)) Assert.Equal("s", GetSymbolNamesJoined(analysis.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.WrittenInside)) Assert.Equal("args, s, t", GetSymbolNamesJoined(analysis.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Bug10172() Dim analysis = CompileAndAnalyzeControlAndDataFlow( <compilation name="Bug10172"> <file name="a.b"> Imports System Imports System.Collections.Generic Imports System.Linq Module Module1 Sub Main() Static list = New Integer() {1, 2, 3, 4, 5, 6, 7, 8} Static b = From i In list Where i > Function(i) As String [|Return i|] End Function.Invoke End Sub End Module </file> </compilation>) Assert.True(analysis.Item1.Succeeded) Assert.True(analysis.Item2.Succeeded) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Bug11526() Dim analysis = CompileAndAnalyzeControlAndDataFlow( <compilation name="Bug10172"> <file name="a.b"> Imports System Imports System.Collections.Generic Imports System.Linq Module Module1 Sub Main() Static x = True Static y = DateTime.Now [| Try Catch ex as Exception when x orelse y = #12:00:00 AM# End Try |] End Sub End Module </file> </compilation>) Assert.True(analysis.Item1.Succeeded) Assert.True(analysis.Item2.Succeeded) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Bug10683a() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="Bug10683a"> <file name="a.b"> Imports System Imports System.Collections.Generic Imports System.Linq Module Module1 Sub Main() Static x = New Integer() {} x.First([|Function(i As Integer, r As Integer) As Boolean Return True End Function|]) End Sub End Module </file> </compilation>) Assert.True(analysis.Succeeded) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestArrayDeclaration01() Dim analysis = CompileAndAnalyzeControlAndDataFlow( <compilation name="TestArrayDeclaration01"> <file name="a.b"> Module Program Sub Main(args As String()) [| Static x(5), y As Integer |] End Sub End Module </file> </compilation>) Dim controlFlowAnalysis = analysis.Item1 Dim dataFlowAnalysis = analysis.Item2 Assert.Equal(0, controlFlowAnalysis.ExitPoints.Count()) Assert.Equal(0, controlFlowAnalysis.EntryPoints.Count()) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.AlwaysAssigned)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.WrittenInside)) Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysis.VariablesDeclared)) Assert.True(controlFlowAnalysis.EndPointIsReachable) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestArrayDeclaration02() Dim analysis = CompileAndAnalyzeControlAndDataFlow( <compilation name="TestArrayDeclaration02"> <file name="a.b"> Module Program Sub Main(args As String()) [|If True Then Static x(5), y As Integer |] End Sub End Module </file> </compilation>) Dim controlFlowAnalysis = analysis.Item1 Dim dataFlowAnalysis = analysis.Item2 Assert.Equal(0, controlFlowAnalysis.ExitPoints.Count()) Assert.Equal(0, controlFlowAnalysis.EntryPoints.Count()) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.AlwaysAssigned)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.WrittenInside)) Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysis.VariablesDeclared)) Assert.True(controlFlowAnalysis.EndPointIsReachable) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestArrayDeclaration02_() Dim analysis = CompileAndAnalyzeControlAndDataFlow( <compilation name="TestArrayDeclaration02"> <file name="a.b"> Module Program Sub Main(args As String()) Static b As Boolean = True [|If b Then Static x(5), y As Integer |] End Sub End Module </file> </compilation>) Dim controlFlowAnalysis = analysis.Item1 Dim dataFlowAnalysis = analysis.Item2 Assert.Equal(0, controlFlowAnalysis.ExitPoints.Count()) Assert.Equal(0, controlFlowAnalysis.EntryPoints.Count()) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.AlwaysAssigned)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.WrittenInside)) Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysis.VariablesDeclared)) Assert.True(controlFlowAnalysis.EndPointIsReachable) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestVariablesWithSameName() Dim analysis = CompileAndAnalyzeControlAndDataFlow( <compilation name="TestVariablesWithSameName"> <file name="a.b"> Module Program Sub Main(args As String()) [|If True Then Static x = 1 Else Static x = 1 |] End Sub End Module </file> </compilation>) Dim controlFlowAnalysis = analysis.Item1 Dim dataFlowAnalysis = analysis.Item2 Assert.Equal(0, controlFlowAnalysis.ExitPoints.Count()) Assert.Equal(0, controlFlowAnalysis.EntryPoints.Count()) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.AlwaysAssigned)) Assert.Equal("x, x", GetSymbolNamesJoined(dataFlowAnalysis.WrittenInside)) Assert.Equal("x, x", GetSymbolNamesJoined(dataFlowAnalysis.VariablesDeclared)) Assert.True(controlFlowAnalysis.EndPointIsReachable) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestVariablesWithSameName2() Dim analysis = CompileAndAnalyzeControlAndDataFlow( <compilation name="TestVariablesWithSameName2"> <file name="a.b"> Module Program Sub Main(args As String()) Dim b As Boolean = false [|If b Then Static x = 1 Else Static x = 1 |] End Sub End Module </file> </compilation>) Dim controlFlowAnalysis = analysis.Item1 Dim dataFlowAnalysis = analysis.Item2 Assert.Equal(0, controlFlowAnalysis.ExitPoints.Count()) Assert.Equal(0, controlFlowAnalysis.EntryPoints.Count()) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.AlwaysAssigned)) Assert.Equal("x, x", GetSymbolNamesJoined(dataFlowAnalysis.WrittenInside)) Assert.Equal("x, x", GetSymbolNamesJoined(dataFlowAnalysis.VariablesDeclared)) Assert.True(controlFlowAnalysis.EndPointIsReachable) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestVariablesDeclared01() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="TestVariablesDeclared01"> <file name="a.b"> class C public sub F(x as integer) Static a as integer [| Static b as integer Static x as integer, y = 1 if true then Static z = "a" end if |] Static c as integer end sub end class</file> </compilation>) Assert.Equal("b, x, y, z", GetSymbolNamesJoined(analysis.VariablesDeclared)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestIfElseBranch() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="TestIfElseBranch"> <file name="a.b"> Imports System Module Program Function Goo() As Integer Static x, y, z [| If True x = 1 ElseIf True y = 1 Else z = 1 End If |] Console.WriteLine(x + y + z) End Function End Module </file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.VariablesDeclared)) Assert.Equal("x", GetSymbolNamesJoined(analysis.AlwaysAssigned)) Assert.Equal("x", GetSymbolNamesJoined(analysis.DataFlowsOut)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestIfElseBranch_() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="TestIfElseBranch"> <file name="a.b"> Imports System Module Program Function Goo() As Integer Static x, y, z Static b As Boolean = True [| If b x = 1 ElseIf b y = 1 Else z = 1 End If |] Console.WriteLine(x + y + z) End Function End Module </file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.AlwaysAssigned)) Assert.Equal("x, y, z", GetSymbolNamesJoined(analysis.DataFlowsOut)) Assert.Equal("b", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)) Assert.Equal("b", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestIfElseBranchReachability01() Dim analysis = CompileAndAnalyzeControlFlow( <compilation name="TestIfElseBranchReachability01"> <file name="a.b"> Imports System Module Program Function Goo() As Integer Static x, y If True Then x = 1 Else If True Then Return 1 Else [|Return 1|] Return x + y End Function End Module </file> </compilation>) Assert.Equal(1, analysis.ExitPoints.Count()) Assert.Equal(0, analysis.EntryPoints.Count()) Assert.False(analysis.StartPointIsReachable()) Assert.False(analysis.EndPointIsReachable()) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestIfElseBranchReachability02() Dim analysis = CompileAndAnalyzeControlFlow( <compilation name="TestIfElseBranchReachability02"> <file name="a.b"> Imports System Module Program Function Goo() As Integer Static x, y If True Then x = 1 Else [|If True Then Return 1 Else Return 1|] Return x + y End Function End Module </file> </compilation>) Assert.Equal(2, analysis.ExitPoints.Count()) Assert.Equal(0, analysis.EntryPoints.Count()) Assert.False(analysis.StartPointIsReachable()) Assert.False(analysis.EndPointIsReachable()) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestIfElseBranchReachability03() Dim analysis = CompileAndAnalyzeControlFlow( <compilation name="TestIfElseBranchReachability03"> <file name="a.b"> Imports System Module Program Function Goo() As Integer Static x, y [|If True Then x = 1 Else If True Then Return 1 Else Return 1|] Return x + y End Function End Module </file> </compilation>) Assert.Equal(2, analysis.ExitPoints.Count()) Assert.Equal(0, analysis.EntryPoints.Count()) Assert.True(analysis.StartPointIsReachable()) Assert.True(analysis.EndPointIsReachable()) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestIfElseBranch01() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="TestIfElseBranch01"> <file name="a.b"> Imports System Module Program Function Goo() As Integer Static x, y [|If True Then x = 1 Else y = 1|] Dim z = x + y End Function End Module </file> </compilation>) Assert.Equal("x", GetSymbolNamesJoined(analysis.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.DataFlowsIn)) Assert.Equal("x", GetSymbolNamesJoined(analysis.DataFlowsOut)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)) Assert.Equal("x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.ReadInside)) Assert.Equal("x, y", GetSymbolNamesJoined(analysis.WrittenInside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestIfElseBranch01_() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="TestIfElseBranch01"> <file name="a.b"> Imports System Module Program Function Goo() As Integer Static b As Boolean = True Static x, y [|If b Then x = 1 Else y = 1|] Static z = x + y End Function End Module </file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.AlwaysAssigned)) Assert.Equal("b", GetSymbolNamesJoined(analysis.DataFlowsIn)) Assert.Equal("x, y", GetSymbolNamesJoined(analysis.DataFlowsOut)) Assert.Equal("b", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)) Assert.Equal("b", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)) Assert.Equal("b", GetSymbolNamesJoined(analysis.ReadInside)) Assert.Equal("x, y", GetSymbolNamesJoined(analysis.WrittenInside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestIfElseBranch02() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="TestIfElseBranch02"> <file name="a.b"> Imports System Module Program Function Goo() As Integer Static x, y If True Then [|x = 1|] Else y = 1 Static z = x + y End Function End Module </file> </compilation>) Assert.Equal("x", GetSymbolNamesJoined(analysis.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.DataFlowsIn)) Assert.Equal("x", GetSymbolNamesJoined(analysis.DataFlowsOut)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)) Assert.Equal("x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.ReadInside)) Assert.Equal("x", GetSymbolNamesJoined(analysis.WrittenInside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestIfElseBranch03() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="TestIfElseBranch03"> <file name="a.b"> Imports System Module Program Function Goo() As Integer Static x, y, z If True Then x = 1 Else [|y = 1|] Static z = x + y End Function End Module </file> </compilation>) Assert.Equal("y", GetSymbolNamesJoined(analysis.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.DataFlowsOut)) '' else clause is unreachable Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.ReadInside)) Assert.Equal("y", GetSymbolNamesJoined(analysis.WrittenInside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestIfElseBranch03_() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="TestIfElseBranch03"> <file name="a.b"> Imports System Module Program Function Goo() As Integer Static b As Boolean = True Static x, y, z If b Then x = 1 Else [|y = 1|] Static z = x + y End Function End Module </file> </compilation>) Assert.Equal("y", GetSymbolNamesJoined(analysis.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.DataFlowsIn)) Assert.Equal("y", GetSymbolNamesJoined(analysis.DataFlowsOut)) Assert.Equal("b", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)) Assert.Equal("b, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.ReadInside)) Assert.Equal("y", GetSymbolNamesJoined(analysis.WrittenInside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestIfElseBranch04() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="TestIfElseBranch04"> <file name="a.b"> Imports System Module Program Function Goo() As Integer Static x, y, z If True Then x = 1 Else If True Then y = 1 Else [|z = 1|] Static zz = z + x + y End Function End Module </file> </compilation>) Assert.Equal("z", GetSymbolNamesJoined(analysis.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.DataFlowsOut)) '' else clause is unreachable Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.ReadInside)) Assert.Equal("z", GetSymbolNamesJoined(analysis.WrittenInside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestIfElseBranch04_() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="TestIfElseBranch04"> <file name="a.b"> Imports System Module Program Function Goo() As Integer Static b As Boolean = True Static x, y, z If b Then x = 1 Else If b Then y = 1 Else [|z = 1|] Static zz = z + x + y End Function End Module </file> </compilation>) Assert.Equal("z", GetSymbolNamesJoined(analysis.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.DataFlowsIn)) Assert.Equal("z", GetSymbolNamesJoined(analysis.DataFlowsOut)) Assert.Equal("b", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)) Assert.Equal("b, z", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.ReadInside)) Assert.Equal("z", GetSymbolNamesJoined(analysis.WrittenInside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestIfElseBranch05() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="TestIfElseBranch05"> <file name="a.b"> Imports System Module Program Function Goo() As Integer Static x, y, z If True Then x = 1 Else [|If True Then y = 1 Else y = 1|] Static zz = z + x + y End Function End Module </file> </compilation>) Assert.Equal("y", GetSymbolNamesJoined(analysis.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.DataFlowsOut)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.ReadInside)) Assert.Equal("y", GetSymbolNamesJoined(analysis.WrittenInside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestIfElseBranch05_() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="TestIfElseBranch05"> <file name="a.b"> Imports System Module Program Function Goo() As Integer Static b As Boolean = True Static x, y, z If b Then x = 1 Else [|If b Then y = 1 Else y = 1|] Static zz = z + x + y End Function End Module </file> </compilation>) Assert.Equal("y", GetSymbolNamesJoined(analysis.AlwaysAssigned)) Assert.Equal("b", GetSymbolNamesJoined(analysis.DataFlowsIn)) Assert.Equal("y", GetSymbolNamesJoined(analysis.DataFlowsOut)) Assert.Equal("b", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)) Assert.Equal("b, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)) Assert.Equal("b", GetSymbolNamesJoined(analysis.ReadInside)) Assert.Equal("y", GetSymbolNamesJoined(analysis.WrittenInside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestVariablesInitializedWithSelfReference() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="TestVariablesInitializedWithSelfReference"> <file name="a.b"> class C public sub F(x as integer) [| Static x as integer = x Static y as integer, z as integer = 1 |] end sub end class</file> </compilation>) Assert.Equal("x, y, z", GetSymbolNamesJoined(analysis.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.DataFlowsOut)) Assert.Equal("x", GetSymbolNamesJoined(analysis.DataFlowsIn)) Assert.Equal("Me, x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)) Assert.Equal("Me, x, x, z", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)) Assert.Equal("x, z", GetSymbolNamesJoined(analysis.AlwaysAssigned)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestVariablesDeclared02() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="TestVariablesDeclared02"> <file name="a.b"> class C public sub F(x as integer) [| Static a as integer Static b as integer Static x as integer, y as integer = 1 if true then Static z as string = "a" end if Static c as integer |] end sub end class</file> </compilation>) Assert.Equal("a, b, x, y, z, c", GetSymbolNamesJoined(analysis.VariablesDeclared)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub AlwaysAssignedUnreachable() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="AlwaysAssignedUnreachable"> <file name="a.b"> class C Public Sub F(x As Integer) [| Static y As Integer If x = 1 Then y = 2 Return Else y = 3 Throw New Exception End If Static c As Integer |] End Sub end class</file> </compilation>) Assert.Equal("y", GetSymbolNamesJoined(analysis.AlwaysAssigned)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestDataFlowLateCall() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="TestDataFlowLateCall"> <file name="a.b"> Option Strict Off Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Static o as object = 1 [| goo(o) |] End Sub Sub goo(x As String) End Sub Sub goo(Byref x As Integer) End Sub End Module </file> </compilation>) Assert.Equal("o", GetSymbolNamesJoined(analysis.DataFlowsIn)) Assert.Equal("o", GetSymbolNamesJoined(analysis.DataFlowsOut)) Assert.Equal("args, o", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)) Assert.Equal("args, o", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)) Assert.Equal("o", GetSymbolNamesJoined(analysis.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.ReadOutside)) Assert.Equal("o", GetSymbolNamesJoined(analysis.WrittenInside)) Assert.Equal("args, o", GetSymbolNamesJoined(analysis.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestDataFlowLateCall001() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="TestDataFlowLateCall001"> <file name="a.b"> Option Strict Off Imports System Imports System.Collections.Generic Imports System.Linq Class Program shared Sub Main(args As String()) Static o as object = 1 Static oo as object = new Program [| oo.goo(o) |] End Sub Sub goo(x As String) End Sub Sub goo(Byref x As Integer) End Sub End Class </file> </compilation>) Assert.Equal("o, oo", GetSymbolNamesJoined(analysis.DataFlowsIn)) Assert.Equal("o", GetSymbolNamesJoined(analysis.DataFlowsOut)) Assert.Equal("args, o, oo", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)) Assert.Equal("args, o, oo", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)) Assert.Equal("o, oo", GetSymbolNamesJoined(analysis.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.ReadOutside)) Assert.Equal("o", GetSymbolNamesJoined(analysis.WrittenInside)) Assert.Equal("args, o, oo", GetSymbolNamesJoined(analysis.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestDataFlowIndex() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="TestDataFlowsOut01"> <file name="a.b"> Option Strict Off Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Static o as object = 1 [| Static oo = o(o) |] End Sub Sub goo(x As String) End Sub Sub goo(Byref x As Integer) End Sub End Module </file> </compilation>) Assert.Equal("o", GetSymbolNamesJoined(analysis.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.DataFlowsOut)) Assert.Equal("args, o", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)) Assert.Equal("args, o, oo", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)) Assert.Equal("o", GetSymbolNamesJoined(analysis.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.ReadOutside)) Assert.Equal("oo", GetSymbolNamesJoined(analysis.WrittenInside)) Assert.Equal("args, o", GetSymbolNamesJoined(analysis.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub UnassignedVariableFlowsOut01() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="UnassignedVariableFlowsOut01"> <file name="a.b"> class C public sub F() Static i as Integer = 10 [| Static j as Integer = j + i |] Console.Write(i) Console.Write(j) end sub end class</file> </compilation>) Assert.Equal("j", GetSymbolNamesJoined(analysis.VariablesDeclared)) Assert.Equal("i, j", GetSymbolNamesJoined(analysis.DataFlowsIn)) Assert.Equal("j", GetSymbolNamesJoined(analysis.DataFlowsOut)) Assert.Equal("Me, i", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)) Assert.Equal("Me, i, j", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)) Assert.Equal("i, j", GetSymbolNamesJoined(analysis.ReadInside)) Assert.Equal("i, j", GetSymbolNamesJoined(analysis.ReadOutside)) Assert.Equal("j", GetSymbolNamesJoined(analysis.WrittenInside)) Assert.Equal("Me, i", GetSymbolNamesJoined(analysis.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestDataFlowsIn01() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="TestDataFlowsIn01"> <file name="a.b"> class C public sub F(x as integer) Static a as integer = 1, y as integer = 2 [| Static b as integer = a + x + 3 |] Static c as integer = a + 4 + y end sub end class</file> </compilation>) Assert.Equal("x, a", GetSymbolNamesJoined(analysis.DataFlowsIn)) Assert.Equal("Me, x, a, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)) Assert.Equal("Me, x, a, y, b", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestDataFlowsIn02() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="TestDataFlowsIn02"> <file name="a.b"> class Program sub Test(of T as class, new)(byref t as T) [| Static t1 as T Test(t1) t = t1 |] System.Console.WriteLine(t1.ToString()) end sub end class </file> </compilation>) Assert.Equal("Me, t1", GetSymbolNamesJoined(analysis.DataFlowsIn)) Assert.Equal("Me, t", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)) Assert.Equal("Me, t", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestDataFlowsIn03() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="TestDataFlowsIn03"> <file name="a.b"> class Program shared sub Main(args() as string) Static x as integer = 1 Static y as integer = 2 [| Static z as integer = x + y |] end sub end class </file> </compilation>) Assert.Equal("x, y", GetSymbolNamesJoined(analysis.DataFlowsIn)) Assert.Equal("args, x, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)) Assert.Equal("args, x, y, z", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestDataFlowsOut01() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="TestDataFlowsOut01"> <file name="a.b"> class C public sub F(x as integer) Static a as integer = 1, y as integer [| if x = 1 then x = 2 y = x end if |] Static c as integer = a + 4 + x + y end sub end class</file> </compilation>) Assert.Equal("x, y", GetSymbolNamesJoined(analysis.DataFlowsOut)) Assert.Equal("Me, x, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)) Assert.Equal("Me, x, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestDataFlowsOut02() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="TestDataFlowsOut02"> <file name="a.b"> class Program public sub Test(args() as string) [| Static s as integer = 10, i as integer = 1 Static b as integer = s + i |] System.Console.WriteLine(s) System.Console.WriteLine(i) end sub end class</file> </compilation>) Assert.Equal("s, i", GetSymbolNamesJoined(analysis.DataFlowsOut)) Assert.Equal("Me, args", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)) Assert.Equal("Me, args, s, i, b", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestDataFlowsOut03() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="TestDataFlowsOut03"> <file name="a.b"> imports System.Text module Program sub Main() as string Static builder as StringBuilder = new StringBuilder() [| builder.Append("Hello") builder.Append("From") builder.Append("Roslyn") |] return builder.ToString() end sub end module</file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.DataFlowsOut)) Assert.Equal("builder", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)) Assert.Equal("builder", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestDataFlowsOut06() Dim analysisResults = CompileAndAnalyzeControlAndDataFlow( <compilation> <file name="a.b"><![CDATA[ Class C Sub F(b As Boolean) Static i As Integer = 1 While b [|i = i + 1|] End While End Sub End Class ]]></file> </compilation>) Dim controlFlowAnalysisResults = analysisResults.Item1 Dim dataFlowAnalysisResults = analysisResults.Item2 Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()) Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()) Assert.Equal(True, controlFlowAnalysisResults.StartPointIsReachable) Assert.Equal(True, controlFlowAnalysisResults.EndPointIsReachable) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("Me, b, i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("Me, b, i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("b", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("Me, b, i", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestDataFlowsOut07() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="TestDataFlowsOut07"> <file name="a.b"> class Program sub F(b as boolean) Static i as integer [| i = 2 goto [next] |] [next]: Static j as integer = i end sub end class</file> </compilation>) Assert.Equal("i", GetSymbolNamesJoined(analysis.DataFlowsOut)) Assert.Equal("Me, b", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestDataFlowsOut08() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="TestDataFlowsOut08"> <file name="a.b"> Class Program Sub F() Static i As Integer = 2 Try [| i = 1 |] Finally Static j As Integer = i End Try End Sub End Class </file> </compilation>) Assert.Equal("i", GetSymbolNamesJoined(analysis.DataFlowsOut)) Assert.Equal("Me, i", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)) Assert.Equal("Me, i", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestDataFlowsOut09() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="TestDataFlowsOut09"> <file name="a.b"> class Program sub Test(args() as string) Static i as integer Static s as string [|i = 10 s = args(0) + i.ToString()|] end sub end class</file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.DataFlowsOut)) Assert.Equal("Me, args", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)) Assert.Equal("Me, args, i, s", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestDataFlowsOutExpression01() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="TestDataFlowsOutExpression01"> <file name="a.b"> class C public sub F(x as integer) Static a as integer = 1, y as integer Static tmp as integer = x [| x = 2 y = x |] temp += (a = 2) Static c as integer = a + 4 + x + y end sub end class</file> </compilation>) Assert.Equal("x, y", GetSymbolNamesJoined(analysis.DataFlowsOut)) Assert.Equal("Me, x, a, tmp", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)) Assert.Equal("Me, x, a, y, tmp", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestAlwaysAssigned01() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="TestAlwaysAssigned01"> <file name="a.b"> class C public sub F(x as integer) Static a as integer = 1, y as integer= 1 [| if x = 2 then a = 3 else a = 4 end if x = 4 if x = 3 then y = 12 end if |] Static c as integer = a + 4 + y end sub end class</file> </compilation>) Assert.Equal("x, a", GetSymbolNamesJoined(analysis.AlwaysAssigned)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestAlwaysAssigned03() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="TestAlwaysAssigned03"> <file name="a.b"> module C sub Main(args() as string) Static i as integer = [| int.Parse(args(0).ToString()) |] end sub end module</file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.AlwaysAssigned)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestWrittenInside02() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="TestWrittenInside02"> <file name="a.b"> module C sub Main(args() as string) Static i as integer = [| int.Parse(args(0).ToString()) |] end sub end module</file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.WrittenInside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestWrittenInside03() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="TestWrittenInside03"> <file name="a.b"> module C sub Main(args() as string) Static i as integer i = [| int.Parse(args(0).ToString()) |] end sub end module</file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.WrittenInside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestAlwaysAssigned04() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="TestAlwaysAssigned04"> <file name="a.b"> module C sub Main(args() as string) Static i as integer i = [| int.Parse(args(0).ToString()) |] end sub end module</file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.AlwaysAssigned)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestAlwaysAssignedDuplicateVariables() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="TestAlwaysAssignedDuplicateVariables"> <file name="a.b"> class C public sub F(x as integer) [| Static a, a, b, b as integer b = 1 |] end sub end class</file> </compilation>) Assert.Equal("b", GetSymbolNamesJoined(analysis.AlwaysAssigned)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestAccessedInsideOutside() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="TestAccessedInsideOutside"> <file name="a.b"> class C public sub F(x as integer) Static a, b, c, d, e, f, g, h, i as integer a = 1 b = a + x c = a + x [| d = c f = d e = d |] g = e i = g h = g end sub end class</file> </compilation>) Assert.Equal("c, d", GetSymbolNamesJoined(analysis.ReadInside)) Assert.Equal("d, e, f", GetSymbolNamesJoined(analysis.WrittenInside)) Assert.Equal("x, a, e, g", GetSymbolNamesJoined(analysis.ReadOutside)) Assert.Equal("Me, x, a, b, c, g, h, i", GetSymbolNamesJoined(analysis.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestAlwaysAssignedViaPassingAsByRefParameter() Dim analysisResults = CompileAndAnalyzeControlAndDataFlow( <compilation> <file name="a.b"><![CDATA[ Class C Public Sub F(x As Integer) [| Static a As Integer G(a)|] End Sub Sub G(ByRef x As Integer) x = 1 End Sub End Class ]]></file> </compilation>) Dim controlFlowAnalysisResults = analysisResults.Item1 Dim dataFlowAnalysisResults = analysisResults.Item2 Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()) Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()) Assert.Equal(True, controlFlowAnalysisResults.StartPointIsReachable) Assert.Equal(True, controlFlowAnalysisResults.EndPointIsReachable) Assert.Equal("a", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("Me, a", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal("a", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("Me, x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("Me, x, a", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal("Me, a", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal("a", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("Me, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestDeclarationWithSelfReferenceAndTernaryOperator() Dim analysisResults = CompileAndAnalyzeControlAndDataFlow( <compilation name="TestDeclarationWithSelfReferenceAndTernaryOperator"> <file name="a.b"> class C shared sub Main() [| Static x as integer = if(true, 1, x) |] end sub end class </file> </compilation>) Dim controlFlowAnalysisResults = analysisResults.Item1 Dim dataFlowAnalysisResults = analysisResults.Item2 Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()) Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()) Assert.True(controlFlowAnalysisResults.StartPointIsReachable) Assert.True(controlFlowAnalysisResults.EndPointIsReachable) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestTernaryExpressionWithAssignments() Dim analysisResults = CompileAndAnalyzeControlAndDataFlow( <compilation name="TestTernaryExpressionWithAssignments"> <file name="a.b"> class C shared sub Main() Static x as boolean = true Static y as integer [| Static z as integer y = if(x, 1, 2) z = y |] y.ToString() end sub end class </file> </compilation>) Dim dataFlowAnalysisResults = analysisResults.Item2 Assert.Equal("z", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal("y, z", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("x, y, z", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal("y, z", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestBranchOfTernaryOperator() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation name="TestBranchOfTernaryOperator"> <file name="a.b"> class C shared sub Main() Static x as boolean = true Static y as boolean = if(x,[|x|],true) end sub end class </file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestDeclarationWithSelfReference() Dim analysisResults = CompileAndAnalyzeControlAndDataFlow( <compilation name="TestDeclarationWithSelfReference"> <file name="a.b"> class C shared sub Main() [| Static x as integer = x |] end sub end class </file> </compilation>) Dim controlFlowAnalysisResults = analysisResults.Item1 Dim dataFlowAnalysisResults = analysisResults.Item2 Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()) Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()) Assert.True(controlFlowAnalysisResults.StartPointIsReachable) Assert.True(controlFlowAnalysisResults.EndPointIsReachable) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestIfStatementWithAssignments() Dim analysisResults = CompileAndAnalyzeControlAndDataFlow( <compilation name="TestIfStatementWithAssignments"> <file name="a.b"> class C shared sub Main() Static x as boolean = true Static y as integer [| if x then y = 1 else y = 2 end if |] y.ToString() end sub end class </file> </compilation>) Dim controlFlowAnalysisResults = analysisResults.Item1 Dim dataFlowAnalysisResults = analysisResults.Item2 Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()) Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()) Assert.True(controlFlowAnalysisResults.StartPointIsReachable) Assert.True(controlFlowAnalysisResults.EndPointIsReachable) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestIfStatementWithConstantCondition() Dim analysisResults = CompileAndAnalyzeControlAndDataFlow( <compilation name="TestIfStatementWithConstantCondition"> <file name="a.b"> class C shared sub Main() Static x as boolean = true Static y as integer [| if true then y = x end if |] y.ToString() end sub end class </file> </compilation>) Dim controlFlowAnalysisResults = analysisResults.Item1 Dim dataFlowAnalysisResults = analysisResults.Item2 Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()) Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()) Assert.True(controlFlowAnalysisResults.StartPointIsReachable) Assert.True(controlFlowAnalysisResults.EndPointIsReachable) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestIfStatementWithNonConstantCondition() Dim analysisResults = CompileAndAnalyzeControlAndDataFlow( <compilation name="TestIfStatementWithNonConstantCondition"> <file name="a.b"> class C shared sub Main() Static x as boolean = true Static y as integer [| if true or x then y = x end if |] y.ToString() end sub end class </file> </compilation>) Dim controlFlowAnalysisResults = analysisResults.Item1 Dim dataFlowAnalysisResults = analysisResults.Item2 Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()) Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()) Assert.True(controlFlowAnalysisResults.StartPointIsReachable) Assert.True(controlFlowAnalysisResults.EndPointIsReachable) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestSingleVariableSelection() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation name="TestSingleVariableSelection"> <file name="a.b"> class C shared sub Main() Static x as boolean = true Static y as boolean = x or [| x |] end sub end class </file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestParenthesizedExpressionSelection() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation name="TestParenthesizedExpressionSelection"> <file name="a.b"> class C shared sub Main() Static x as boolean = true Static y as boolean = x or [|(x = x) |] orelse x end sub end class </file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) ' In C# '=' is an assignment while in VB it is a comparison. Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) 'C# flows out because this is an assignment expression. In VB this is an equality test. Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) 'C# this is an assignment. In VB, this is a comparison so no assignment. Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestRefArgumentSelection() Dim analysisResults = CompileAndAnalyzeControlAndDataFlow( <compilation name="TestRefArgumentSelection"> <file name="a.b"> class C shared sub Main() Static x as integer = 0 [| Goo( x ) |] System.Console.WriteLine(x) end sub shared sub Goo(byref x as integer) end sub end class </file> </compilation>) Dim controlFlowAnalysisResults = analysisResults.Item1 Dim dataFlowAnalysisResults = analysisResults.Item2 Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()) Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()) Assert.True(controlFlowAnalysisResults.StartPointIsReachable) Assert.True(controlFlowAnalysisResults.EndPointIsReachable) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <WorkItem(541891, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541891")> <Fact()> Public Sub TestRefArgumentSelection02() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation name="TestRefArgumentSelection02"> <file name="a.b"> class C Sub Main() Static x As UInteger System.Console.WriteLine([|Goo(x)|]) End Sub Function Goo(ByRef x As ULong) x = 123 Return x + 1 End Function end class </file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("Me, x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("Me, x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal("Me, x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <WorkItem(541891, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541891")> <Fact()> Public Sub TestRefArgumentSelection02a() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation name="TestRefArgumentSelection02"> <file name="a.b"> class C Sub Main() Static x As UInteger System.Console.WriteLine(Goo([|x|])) End Sub Function Goo(ByRef x As ULong) x = 123 Return x + 1 End Function end class </file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal("Me, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestCompoundAssignmentTargetSelection01() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation name="TestCompoundAssignmentTargetSelection01"> <file name="a.b"> class C Sub Main() Static x As String = "" [|x|]+=1 End Sub end class </file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("Me, x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("Me, x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal("Me, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestCompoundAssignmentTargetSelection02() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation name="TestCompoundAssignmentTargetSelection02"> <file name="a.b"> class C Sub Main() Static x As String = "" [|x+=1|] End Sub end class </file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("Me, x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("Me, x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal("Me, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestCompoundAssignmentTargetSelection03() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation name="TestCompoundAssignmentTargetSelection03"> <file name="a.b"> Imports System Module M1 Sub M(ParamArray ary As Long()) Static local01 As Integer = 1 Static local02 As Short = 2 [| local01 ^= local02 Try local02 &lt;&lt;= ary(0) ary(1) *= local01 Static flocal As Single = 0 flocal /= ary(0) ary(1) \= ary(0) Catch ex As Exception Finally Dim slocal = Nothing slocal &amp;= Nothing End Try |] End Sub End Module </file> </compilation>) Assert.Equal("flocal, ex, slocal", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal("local01, slocal", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("ary, local01, local02, flocal", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal("local01, local02, flocal", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("ary, local01, local02", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("ary, local01, local02, slocal", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal("ary, local01, local02, flocal, slocal", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("local01, local02, flocal, ex, slocal", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal("ary, local01, local02", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestRefArgumentSelection03() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation name="TestRefArgumentSelection03"> <file name="a.b"> class C Sub Main() Static x As ULong System.Console.WriteLine([|Goo(x)|]) End Sub Function Goo(ByRef x As ULong) x = 123 Return x + 1 End Function end class </file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("Me, x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("Me, x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal("Me, x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestInvocation() Dim analysisResults = CompileAndAnalyzeControlAndDataFlow( <compilation name="TestInvocation"> <file name="a.b"> class C shared sub Main() Static x as integer = 1, y as integer = 1 [| Goo(x) |] end sub shared sub Goo(int x) end sub end class </file> </compilation>) Dim controlFlowAnalysisResults = analysisResults.Item1 Dim dataFlowAnalysisResults = analysisResults.Item2 Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()) Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()) Assert.True(controlFlowAnalysisResults.StartPointIsReachable) Assert.True(controlFlowAnalysisResults.EndPointIsReachable) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) ' Sees Me beng read Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestInvocationWithAssignmentInArguments() Dim analysisResults = CompileAndAnalyzeControlAndDataFlow( <compilation name="TestInvocationWithAssignmentInArguments"> <file name="a.b"> class C shared sub Main() Static x as integer = 1, y as integer = 1 [| x = y y = 2 Goo(y, 2) ' VB does not support expression assignment F(x = y, y = 2) |] Static z as integer = x + y } shared sub Goo(int x, int y) end sub } </file> </compilation>) Dim controlFlowAnalysisResults = analysisResults.Item1 Dim dataFlowAnalysisResults = analysisResults.Item2 Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()) Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()) Assert.True(controlFlowAnalysisResults.StartPointIsReachable) Assert.True(controlFlowAnalysisResults.EndPointIsReachable) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) ' Sees Me being read Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("x, y, z", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestArrayInitializer() Dim analysisResults = CompileAndAnalyzeControlAndDataFlow( <compilation> <file name="a.b"><![CDATA[ Class C Sub Main(args As String()) Static y As Integer = 1 Static x(,) As Integer x = { { [|y|] } } End Sub End Class ]]></file> </compilation>) Dim controlFlowAnalysisResults = analysisResults.Item1 Dim dataFlowAnalysisResults = analysisResults.Item2 Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()) Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()) Assert.Equal(True, controlFlowAnalysisResults.StartPointIsReachable) Assert.Equal(True, controlFlowAnalysisResults.EndPointIsReachable) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("Me, args, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("Me, args, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("Me, args, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub ByRefParameterNotInAppropriateCollections1() ' ByRef parameters are not considered assigned Dim analysisResults = CompileAndAnalyzeControlAndDataFlow( <compilation name="AssertFromInvalidKeywordAsExpr"> <file name="a.b"> Imports System Imports System.Collections.Generic Class Program Sub Test(of T)(ByRef t As T) [| Static t1 As T Test(t1) t = t1 |] System.Console.WriteLine(t1.ToString()) End Sub End Class </file> </compilation>) Dim controlFlowAnalysisResults = analysisResults.Item1 Dim dataFlowAnalysisResults = analysisResults.Item2 Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()) Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()) Assert.True(controlFlowAnalysisResults.StartPointIsReachable) Assert.True(controlFlowAnalysisResults.EndPointIsReachable) Assert.Equal("t1", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal("t", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("Me, t1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal("t, t1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("Me, t", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("Me, t, t1", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal("Me, t1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("t, t1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal("t, t1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("Me, t, t1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub ByRefParameterNotInAppropriateCollections2() ' ByRef parameters are not considered assigned Dim analysisResults = CompileAndAnalyzeControlAndDataFlow( <compilation name="AssertFromInvalidKeywordAsExpr"> <file name="a.b"> Imports System Imports System.Collections.Generic Class Program Sub Test(Of T)(ByRef t As T) [| Static t1 As T = GetValue(of T)(t) |] System.Console.WriteLine(t1.ToString()) End Sub Private Function GetValue(Of T)(ByRef t As T) As T Return t End Function End Class </file> </compilation>) Dim controlFlowAnalysisResults = analysisResults.Item1 Dim dataFlowAnalysisResults = analysisResults.Item2 Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()) Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()) Assert.True(controlFlowAnalysisResults.StartPointIsReachable) Assert.True(controlFlowAnalysisResults.EndPointIsReachable) Assert.Equal("t1", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal("t1", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("Me, t", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal("t, t1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("Me, t", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("Me, t, t1", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal("Me, t", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("t, t1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal("t, t1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("Me, t, t1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub BinaryAndAlso01() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation name="BinaryAndAlso01"> <file name="a.b"> Class A Function F(ByRef p As Boolean) As Boolean Return Nothing End Function Sub Test1() Static x As Boolean = True Static y As Boolean = False Static z As Boolean = IF(Nothing, [|F(x)|]) AndAlso IF(Nothing, F(y)) AndAlso False End Sub End Class </file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("Me, x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("Me, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("Me, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal("Me, x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("Me, y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("Me, x, y, z", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub BinaryAndAlso02() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation name="BinaryAndAlso02"> <file name="a.b"> Class A Function F(ByRef p As Boolean) As Boolean Return Nothing End Function Sub Test1() Static x As Boolean Static y As Boolean = False Static z As Boolean = x AndAlso [|y|] AndAlso False End Sub End Class </file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("Me, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("Me, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("Me, y, z", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub BinaryOrElse01() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation name="BinaryOrElse01"> <file name="a.b"> Class A Function F(ByRef p As Boolean) As Boolean Return Nothing End Function Sub Test1() Static x As Boolean = True Static y As Boolean = False Static z As Boolean = IF(Nothing, [|F(x)|]) OrElse IF(Nothing, F(y)) OrElse False End Sub End Class </file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("Me, x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal("Me, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("Me, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal("Me, x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub BinaryOrElse02() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation name="BinaryOrElse02"> <file name="a.b"> Class A Function F(ByRef p As Boolean) As Boolean Return Nothing End Function Sub Test1() Static x As Boolean Static y As Boolean = False Static z As Boolean = x OrElse [|y|] OrElse False End Sub End Class </file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal("Me, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("Me, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestMultipleLocalsInitializedByAsNew1() Dim dataFlowAnalysis = CompileAndAnalyzeDataFlow( <compilation name="TestMultipleLocalsInitializedByAsNew"> <file name="a.b"> Module Program Class c Sub New(i As Integer) End Sub End Class Sub Main(args As String()) Static a As Integer = 1 Static x, y, z As New c([|a|]+1) End Sub End Module </file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.WrittenInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.VariablesDeclared)) Assert.Equal("args, a, x, y, z", GetSymbolNamesJoined(dataFlowAnalysis.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestMultipleLocalsInitializedByAsNew2() Dim analysis = CompileAndAnalyzeControlAndDataFlow( <compilation name="TestMultipleLocalsInitializedByAsNew"> <file name="a.b"> Module Program Class c Sub New(i As Integer) End Sub End Class Sub Main(args As String()) Static a As Integer = 1 [|Static x, y, z As New c(a)|] End Sub End Module </file> </compilation>) Dim controlFlowAnalysis = analysis.Item1 Dim dataFlowAnalysis = analysis.Item2 Assert.Equal(0, controlFlowAnalysis.ExitPoints.Count()) Assert.Equal(0, controlFlowAnalysis.EntryPoints.Count()) Assert.Equal("x, y, z", GetSymbolNamesJoined(dataFlowAnalysis.AlwaysAssigned)) Assert.Equal("x, y, z", GetSymbolNamesJoined(dataFlowAnalysis.WrittenInside)) Assert.Equal("x, y, z", GetSymbolNamesJoined(dataFlowAnalysis.VariablesDeclared)) Assert.Equal("args, a", GetSymbolNamesJoined(dataFlowAnalysis.WrittenOutside)) Assert.True(controlFlowAnalysis.StartPointIsReachable) Assert.True(controlFlowAnalysis.EndPointIsReachable) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestElementAccess01() Dim analysis = CompileAndAnalyzeControlAndDataFlow( <compilation name="TestElementAccess"> <file name="elem.b"> Imports System Public Class Test Sub F(p as Long()) Static v() As Long = new Long() { 1, 2, 3 } [| v(0) = p(0) p(0) = v(1) |] v(1) = v(0) ' p(2) = p(0) End Sub End Class </file> </compilation>) Dim dataFlowAnalysis = analysis.Item2 Assert.True(dataFlowAnalysis.Succeeded) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.AlwaysAssigned)) Assert.Equal("p, v", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsOut)) Assert.Equal("Me, p, v", GetSymbolNamesJoined(dataFlowAnalysis.DefinitelyAssignedOnEntry)) Assert.Equal("Me, p, v", GetSymbolNamesJoined(dataFlowAnalysis.DefinitelyAssignedOnExit)) Assert.Equal("p, v", GetSymbolNamesJoined(dataFlowAnalysis.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.WrittenInside)) Assert.Equal("v", GetSymbolNamesJoined(dataFlowAnalysis.ReadOutside)) Assert.Equal("Me, p, v", GetSymbolNamesJoined(dataFlowAnalysis.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub DataFlowForDeclarationOfEnumTypedVariable() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"><![CDATA[ Class C Sub Main(args As String()) [|Static s As color|] Try Catch ex As Exception When s = color.black Console.Write("Exception") End Try End Sub End Class Enum color black End Enum ]]></file> </compilation>) Assert.Equal("s", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal("s", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("Me, args", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("Me, args", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("s", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("Me, args, ex", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub IdentifierNameInMemberAccessExpr() Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Public Class Goo Sub M() Static c As C = New C() Static n1 = c.[|M|] End Sub End Class </file> </compilation>) Assert.False(dataFlowResults.Succeeded) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub IdentifierNameInMemberAccessExpr2() Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Public Class C Sub M() Static c As C = New C() Static n1 = c.[|M|] End Sub End Class </file> </compilation>) Assert.False(dataFlowResults.Succeeded) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub IdentifierNameSyntax() Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports Microsoft.VisualBasic Public Class C Sub M() Static n1 = [|ChrW|](85) End Sub End Class </file> </compilation>) Assert.True(dataFlowResults.Succeeded) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub IdentifierNameSyntax2() Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports Microsoft.VisualBasic Public Class C Sub M() Static n1 = [|Goo|](85) End Sub Function Goo(i As Integer) As Integer Return i End Function End Class </file> </compilation>) Assert.True(dataFlowResults.Succeeded) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub IdentifierNameSyntax3() Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports Microsoft.VisualBasic Public Class C Sub M() Static n1 = [|Goo|](85) End Sub ReadOnly Property Goo(i As Integer) As Integer Get Return i End Get End Property End Class </file> </compilation>) Assert.True(dataFlowResults.Succeeded) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub PredefinedTypeIncompleteSub() Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Friend Module AcceptVB7_12mod Sub AcceptVB7_12() Static lng As [|Integer|] Static int1 As Short </file> </compilation>) Assert.False(dataFlowResults.Succeeded) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub PredefinedType2() Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Friend Module AcceptVB7_12mod Sub AcceptVB7_12() Static lng As [|Integer|] Static int1 As Short End Sub And Module </file> </compilation>) Assert.False(dataFlowResults.Succeeded) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub CollectionInitSyntax() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module Program Sub Main(args As String()) Static i1 = New Integer() {4, 5} End Sub End Module </file> </compilation>) Dim tree = compilation.SyntaxTrees.First() Dim model = compilation.GetSemanticModel(tree) Dim exprSyntaxNode = DirectCast(tree.GetCompilationUnitRoot().FindToken(tree.GetRoot.ToFullString().IndexOf("{4, 5}", StringComparison.Ordinal)).Parent, CollectionInitializerSyntax) Dim analysis = model.AnalyzeDataFlow(exprSyntaxNode) Assert.False(analysis.Succeeded) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub CollectionInitSyntax2() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System.Collections.Generic Module Program Sub Main(args As String()) Static i1 = New List(Of Integer) From {4, 5} End Sub End Module </file> </compilation>) Dim tree = compilation.SyntaxTrees.First() Dim model = compilation.GetSemanticModel(tree) Dim exprSyntaxNode = DirectCast(tree.GetCompilationUnitRoot().FindToken(tree.GetRoot.ToFullString().IndexOf("{4, 5}", StringComparison.Ordinal)).Parent, CollectionInitializerSyntax) Dim analysis = model.AnalyzeDataFlow(exprSyntaxNode) Assert.False(analysis.Succeeded) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub CollectionInitSyntax3() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System.Collections.Generic Module Program Sub Main(args As String()) Static i1 = {4, 5} End Sub End Module </file> </compilation>) Dim tree = compilation.SyntaxTrees.First() Dim model = compilation.GetSemanticModel(tree) Dim exprSyntaxNode = DirectCast(tree.GetCompilationUnitRoot().FindToken(tree.GetRoot.ToFullString().IndexOf("{4, 5}", StringComparison.Ordinal)).Parent, CollectionInitializerSyntax) Dim analysis = model.AnalyzeDataFlow(exprSyntaxNode) Assert.True(analysis.Succeeded) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub IfStatementSyntax() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module Program Sub Main(args As String()) Static x = 10 If False x = x + 1 End If End Sub End Module </file> </compilation>) Dim tree = compilation.SyntaxTrees.First() Dim model = compilation.GetSemanticModel(tree) Dim stmtSyntaxNode = DirectCast(tree.GetCompilationUnitRoot().FindToken(tree.GetRoot.ToFullString().IndexOf("If False", StringComparison.Ordinal)).Parent, IfStatementSyntax) Dim analysis = model.AnalyzeControlFlow(stmtSyntaxNode, stmtSyntaxNode) Assert.False(analysis.Succeeded) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub ElseStatementSyntax() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module Program Sub Main(args As String()) Static x = 10 If False x = x + 1 Else x = x - 1 End If End Sub End Module </file> </compilation>) Dim tree = compilation.SyntaxTrees.First() Dim model = compilation.GetSemanticModel(tree) Dim stmtSyntaxNode = DirectCast(tree.GetCompilationUnitRoot().FindToken(tree.GetRoot.ToFullString().IndexOf("Else", StringComparison.Ordinal)).Parent, ElseStatementSyntax) Dim analysis = model.AnalyzeControlFlow(stmtSyntaxNode, stmtSyntaxNode) Assert.False(analysis.Succeeded) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub NamespaceIdentifierNameInMemberAccess3() Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Namespace STForEach01 Friend Module STForEach01mod ReadOnly Property STForEach01 As Integer Get Return 1 End Get End Property End Module End Namespace Friend Module MainModule Sub Main() Static a As Integer = [|STForEach01|].STForEach01 End Sub End Module </file> </compilation>) Assert.False(dataFlowResults.Succeeded) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub NamespaceIdentifierNameInMemberAccess4() Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Namespace STForEach01 Friend Module STForEach01mod ReadOnly Property STForEach01 As Integer Get Return 1 End Get End Property End Module End Namespace Friend Module MainModule Sub Main() Static a As Integer = [|STForEach01.STForEach01mod|].STForEach01 End Sub End Module </file> </compilation>) Assert.False(dataFlowResults.Succeeded) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub NamespaceIdentifierNameInMemberAccess5() Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Module Program Sub Main() Static d1 = Sub(x As Integer) [|System|].Console.WriteLine(x) End Sub End Sub End Module </file> </compilation>) Assert.False(dataFlowResults.Succeeded) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub NamespaceIdentifierNameInMemberAccess9() Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Public Class Compilation Public Class B Public Shared Function M(a As Integer) As Boolean Return False End Function End Class End Class Friend Class Program Public Shared Sub Main() Static x = [| Compilation |].B.M(a:=123) End Sub Public ReadOnly Property Compilation As Compilation Get Return Nothing End Get End Property End Class </file> </compilation>) Assert.False(dataFlowResults.Succeeded) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub NamespaceIdentifierNameInMemberAccess10() Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Public Class Compilation Public Shared Function M(a As Integer) As Boolean Return False End Function End Class Friend Class Program Public Shared Sub Main() Static x = [| Compilation |].M(a:=123) End Sub Public ReadOnly Property Compilation As Compilation Get Return Nothing End Get End Property End Class </file> </compilation>) Assert.False(dataFlowResults.Succeeded) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub ConstLocalUsedInLambda01() Dim analysisResult = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Module M1 Sub Main() Static local = 1 Const constLocal = 2 Static f = [| Function(p as sbyte) As Short Return local + constlocal + p End Function |] Console.Write(f) End Sub End Module </file> </compilation>) Assert.Equal("p", GetSymbolNamesJoined(analysisResult.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysisResult.AlwaysAssigned)) Assert.Equal("local", GetSymbolNamesJoined(analysisResult.Captured)) Assert.Equal("local, constLocal", GetSymbolNamesJoined(analysisResult.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysisResult.DataFlowsOut)) Assert.Equal("local, constLocal, f", GetSymbolNamesJoined(analysisResult.DefinitelyAssignedOnEntry)) Assert.Equal("local, constLocal, f", GetSymbolNamesJoined(analysisResult.DefinitelyAssignedOnExit)) Assert.Equal("local, constLocal, p", GetSymbolNamesJoined(analysisResult.ReadInside)) ' WHY Assert.Equal("p", GetSymbolNamesJoined(analysisResult.WrittenInside)) Assert.Equal("f", GetSymbolNamesJoined(analysisResult.ReadOutside)) Assert.Equal("local, constLocal, f", GetSymbolNamesJoined(analysisResult.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub ConstLocalUsedInLambda02() Dim analysisResult = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Class C Function F(mp As Short) As Integer Try Static local = 1 Const constLocal = 2 Static lf = [| Sub() local = constlocal + mp End Sub |] lf() Return local Finally End Try End Function End Class </file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(analysisResult.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysisResult.AlwaysAssigned)) Assert.Equal("mp, local", GetSymbolNamesJoined(analysisResult.Captured)) Assert.Equal("mp, constLocal", GetSymbolNamesJoined(analysisResult.DataFlowsIn)) Assert.Equal("local", GetSymbolNamesJoined(analysisResult.DataFlowsOut)) Assert.Equal("Me, mp, local, constLocal, lf", GetSymbolNamesJoined(analysisResult.DefinitelyAssignedOnEntry)) Assert.Equal("Me, mp, local, constLocal, lf", GetSymbolNamesJoined(analysisResult.DefinitelyAssignedOnExit)) Assert.Equal("mp, constLocal", GetSymbolNamesJoined(analysisResult.ReadInside)) Assert.Equal("local", GetSymbolNamesJoined(analysisResult.WrittenInside)) Assert.Equal("local, lf", GetSymbolNamesJoined(analysisResult.ReadOutside)) Assert.Equal("Me, mp, local, constLocal, lf", GetSymbolNamesJoined(analysisResult.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub LiteralExprInVarDeclInsideSingleLineLambda() Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Module Test Sub Sub1() Static x = Sub() Dim y = [|10|] End Sub End Module </file> </compilation>) Assert.True(dataFlowResults.Succeeded) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub ObjectCreationExpr() Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Module Program Sub Main(args As String()) Static x As [|New C|] End Sub End Module </file> </compilation>) Assert.True(dataFlowResults.Succeeded) End Sub #Region "ObjectInitializer" <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub ObjectInitializersNoStaticLocalsAccessed() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Public Class C1 Public FieldInt As Long Public FieldStr As String Public Property PropInt As Integer End Class Public Class C2 Public Shared Sub Main() Static intlocal As Integer Static x = New C1() With {.FieldStr = [|.FieldInt.ToString()|]} End Sub End Class </file> </compilation>) Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub ObjectInitializersStaticLocalsAccessed1_OnlyImplicitReceiverRegion1() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Public Structure S1 Public FieldInt As Long Public FieldStr As String Public Property PropInt As Integer End Structure Public Class S2 Public Shared Sub Main() Static x, y As New S1() With {.FieldStr = [|.FieldInt.ToString()|]} End Sub End Class </file> </compilation>) Assert.False(dataFlowAnalysisResults.Succeeded) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub ObjectInitializersStaticLocalsAccessed1_OnlyImplicitReceiverRegion2() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Public Structure S1 Public FieldInt As Long Public FieldStr As String Public Property PropInt As Integer End Structure Public Class S2 Public Shared Sub Main() Static x, y As New S1() With {.FieldInt = [|.FieldStr.Length|]} End Sub End Class </file> </compilation>) Assert.False(dataFlowAnalysisResults.Succeeded) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub ObjectInitializersStaticLocalsAccessed1_DeclAndImplicitReceiverRegion() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Public Structure S1 Public FieldInt As Long Public FieldStr As String Public Property PropInt As Integer End Structure Public Class S2 Public Shared Sub Main() [| Static x, y As New S1() With {.FieldInt = .FieldStr.Length} |] End Sub End Class </file> </compilation>) Assert.True(dataFlowAnalysisResults.Succeeded) Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub ObjectInitializersStaticLocalsAccessed1_ValidRegion1() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Public Structure S1 Public FieldInt As Long Public FieldStr As String Default Public Property PropInt(i As String) As String Get Return 0 End Get Set(value As String) End Set End Property End Structure Public Class S2 Public Shared Sub Main() Static x, y As New S1() With {.FieldInt = !A.Length } x.FieldInt = [| x!A.Length |] End Sub End Class </file> </compilation>) Assert.True(dataFlowAnalysisResults.Succeeded) Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub ObjectInitializersStaticLocalsAccessed1_ValidRegion2() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Public Structure S1 Public FieldInt As Long Public FieldStr As String Default Public Property PropInt(i As String) As String Get Return 0 End Get Set(value As String) End Set End Property End Structure Public Class S2 Public Shared Sub Main() Static x, y As New S1() With {.FieldInt = [| x!A.Length |] } End Sub End Class </file> </compilation>) Assert.True(dataFlowAnalysisResults.Succeeded) Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub ObjectInitializersStaticLocalsAccessed1_InvalidRegion3() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Public Structure S1 Public FieldInt As Long Public FieldStr As String Default Public Property PropInt(i As String) As String Get Return 0 End Get Set(value As String) End Set End Property End Structure Public Class S2 Public Shared Sub Main() Static x, y As New S1() With {.FieldStr = [| !A |] } End Sub End Class </file> </compilation>) Assert.False(dataFlowAnalysisResults.Succeeded) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub ObjectInitializersStaticLocalsAccessed1a_ObjectInitializer() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Public Structure S1 Public FieldInt As Long Public FieldStr As String Public Property PropInt As Integer End Structure Public Class S2 Public Shared Sub Main() Static o As New S1() With o [|Console.WriteLine(New S1() With {.FieldStr = .FieldInt.ToString()})|] End With End Sub End Class </file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("o", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("o", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("o", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub ObjectInitializersStaticLocalsAccessed1a_ObjectInitializer2() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Public Structure S1 Public FieldInt As Long Public FieldStr As String Public Property PropInt As Integer End Structure Public Class S2 Public Shared Sub Main() Static o As New S1() With o Console.WriteLine(New S1() With {.FieldStr = [|.FieldInt.ToString()|] }) End With End Sub End Class </file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("o", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("o", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("o", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub ObjectInitializersStaticLocalsAccessed1b() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Public Structure S1 Public FieldInt As Long Public FieldStr As String Public Property PropInt As Integer End Structure Public Class S2 Public Shared Sub Main() Static o As New S1() With o [|Console.WriteLine(New List(Of String) From {.FieldStr, "Brian", "Tim"})|] End With End Sub End Class </file> </compilation>) Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) Assert.Equal("o", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("o", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("o", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal("o", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("o", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub ObjectInitializersStaticLocalsAccessed1bb() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Public Structure S1 Public FieldInt As Long Public FieldStr As String Public Property PropInt As Integer End Structure Public Class S2 Public Shared Sub Main() Static o As New S1() [|Console.WriteLine(New List(Of String) From {o.FieldStr, "Brian", "Tim"})|] End Sub End Class </file> </compilation>) Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) Assert.Equal("o", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("o", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("o", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal("o", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("o", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub ObjectInitializers_StructWithFieldAccessesInLambda1() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Structure SS1 Public A As String Public B As String End Structure Structure SS2 Public X As SS1 Public Y As SS1 End Structure Structure Clazz Shared Sub TEST() Static a, b As New SS2() With {.X = Function() As SS1 With .Y [| .A = "1" |] '.B = "2" End With Return .Y End Function.Invoke()} End Sub End Structure </file> </compilation>) Assert.False(dataFlowAnalysisResults.Succeeded) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub ObjectInitializers_StructWithFieldAccessesInLambda2() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Structure SS1 Public A As String Public B As String End Structure Structure SS2 Public X As SS1 Public Y As SS1 End Structure Structure Clazz Shared Sub TEST() Static a, b As New SS2() With {.X = Function() As SS1 With .Y [| b.Y.B = a.Y.A a.Y.A = "1" |] End With Return .Y End Function.Invoke()} End Sub End Structure </file> </compilation>) Assert.True(dataFlowAnalysisResults.Succeeded) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("a, b", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) Assert.Equal("a", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("a", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("a", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal("a", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("a, b", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal("a, b", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("a, b", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub ObjectInitializers_StructWithFieldAccessesInLambda3() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Structure SS1 Public A As String Public B As String End Structure Structure SS2 Public X As SS1 Public Y As SS1 End Structure Structure Clazz Sub New(i As Integer) Static l = Sub() Dim a, b As New SS2() With {.X = Function() As SS1 With .Y [| b.Y.B = a.Y.A a.Y.A = "1" |] End With Return .Y End Function.Invoke()} End Sub End Sub End Structure </file> </compilation>) Assert.True(dataFlowAnalysisResults.Succeeded) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("a, b", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) Assert.Equal("a", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("i, l, a", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("i, l, a", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal("a", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("Me, a, b", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal("a, b", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("Me, i, l, a, b", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub ObjectInitializers_StructWithFieldAccessesInLambda4() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Structure SS1 Public A As String Public B As String End Structure Structure SS2 Public X As SS1 Public Y As SS1 End Structure Structure Clazz Sub New(i As Integer) Static a, b As New SS2() With {.X = Function() As SS1 [| a.Y = New SS1() b.Y = New SS1() |] Return .Y End Function.Invoke()} Console.WriteLine(a.ToString()) End Sub End Structure </file> </compilation>) Assert.True(dataFlowAnalysisResults.Succeeded) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("a, b", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("i, a", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("i, a", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("Me, a, b", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal("a, b", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("Me, i, a, b", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub ObjectInitializers_StructWithFieldAccessesInLambda5() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Structure SS1 Public A As String Public B As String End Structure Structure SS2 Public X As SS1 Public Y As SS1 End Structure Structure Clazz Sub New(i As Integer) Static a, b As New SS2() With {.X = Function() As SS1 [| b.Y = New SS1() |] Return a.Y End Function.Invoke()} Console.WriteLine(a.ToString()) End Sub End Structure </file> </compilation>) Assert.True(dataFlowAnalysisResults.Succeeded) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("a, b", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("i, a", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("i, a", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("Me, a", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal("b", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("Me, i, a, b", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub ObjectInitializers_StructWithFieldAccessesInLambda6() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Structure SS1 Public A As String Public B As String End Structure Structure SS2 Public X As SS1 Public Y As SS1 End Structure Structure Clazz Sub New(i As Integer) Static a, b As New SS2() With {.X = Function() As SS1 [| b.Y = New SS1() |] Return b.Y End Function.Invoke()} Console.WriteLine(a.ToString()) End Sub End Structure </file> </compilation>) Assert.True(dataFlowAnalysisResults.Succeeded) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("b", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal("b", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("i, a", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("i, a", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("Me, a, b", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal("b", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("Me, i, a, b", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub ObjectInitializers_PassingFieldByRef() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Structure SS1 Public A As String Public B As String End Structure Structure SS2 Public X As SS1 Public Y As SS1 End Structure Structure Clazz Shared Function Transform(ByRef p As SS1) As SS1 Return p End Function Sub New(i As Integer) Static a, b As New SS2() With {.X = [| Transform(b.Y) |] } End Sub End Structure </file> </compilation>) Assert.True(dataFlowAnalysisResults.Succeeded) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) Assert.Equal("b", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("i, a", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("i, a", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal("b", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal("b", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("Me, i, a, b", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub ObjectInitializersLocalsAccessed2() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Public Structure S1 Public FieldInt As Long Public FieldStr As String Public Property PropInt As Integer End Structure Public Class S2 Public Shared Sub Main() Static x As New S1() With {.FieldStr = [|.FieldInt.ToString()|]} End Sub End Class </file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub ObjectInitializersWithLocalsAccessed() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Public Class C1 Public FieldStr As String End Class Public Class C2 Public Shared Function GetStr(p as string) return p end Function Public Shared Sub Main() Static strlocal As String Static x = New C1() With {.FieldStr = [|GetStr(strLocal)|]} End Sub End Class </file> </compilation>) Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("strlocal", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal("strlocal", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub ObjectInitializersWithLocalCaptured() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Class C1 Public Field As Integer = 42 Public Field2 As Func(Of Integer) End Class Class C1(Of T) Public Field As T End Class Class C2 Public Shared Sub Main() Static localint as integer = 23 Static x As New C1 With {.Field2 = [|Function() As Integer Return localint End Function|]} x.Field = 42 Console.WriteLine(x.Field2.Invoke()) End Sub End Class </file> </compilation>) Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("localint", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("localint", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("localint", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal("localint", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("localint, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal("localint", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub ObjectInitializersWholeStatement() Dim analysisResults = CompileAndAnalyzeControlAndDataFlow( <compilation> <file name="a.vb"> Imports System Class C1 Public Field As Integer = 42 Public Field2 As Func(Of Integer) End Class Class C1(Of T) Public Field As T End Class Class C2 Public Shared Sub Main() Static localint as integer [|Static x As New C1 With {.Field2 = Function() As Integer localInt = 23 Return localint End Function}|] x.Field = 42 Console.WriteLine(x.Field2.Invoke()) End Sub End Class </file> </compilation>) Dim dataFlowAnalysisResults = analysisResults.Item2 Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal("localint", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal("localint, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) Assert.Equal("localint", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) Dim controlFlowAnalysisResults = analysisResults.Item1 Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count) Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count) Assert.True(controlFlowAnalysisResults.EndPointIsReachable) Assert.True(controlFlowAnalysisResults.StartPointIsReachable) End Sub #End Region #Region "CollectionInitializer" <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub CollectionInitializersCompleteObjectCreationExpression() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Public Class C2 Public Shared Sub Main() Static goo as string = "Hello World" Static x as [|New List(Of String) From {goo, "!"}|] End Sub End Class </file> </compilation>) Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("goo", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("goo", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("goo", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal("goo", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("goo, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub CollectionInitializersOutermostInitializerAreNoVBExpressions() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Public Class C2 Public Shared Sub Main() Static goo as string = "Hello World" Static x as New List(Of String) From [|{goo, "!"}|] End Sub End Class </file> </compilation>) Assert.False(dataFlowAnalysisResults.Succeeded) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub CollectionInitializersTopLevelInitializerAreNoVBExpressions() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Public Class C2 Public Shared Sub Main() Static goo as string = "Hello World" Static x as New Dictionary(Of String, Integer) From {[|{goo, 1}|], {"bar", 42}} End Sub End Class </file> </compilation>) Assert.False(dataFlowAnalysisResults.Succeeded) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub CollectionInitializersLiftedLocals() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Public Class C2 Public Shared Sub Main() Static goo As String = "Hello World" Static x As [|New List(Of Action) From { Sub() Console.WriteLine(goo) End Sub, Sub() Console.WriteLine(x.Item(0)) x = nothing End Sub }|] End Sub End Class </file> </compilation>) Assert.True(dataFlowAnalysisResults.Succeeded) Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("goo, x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("goo", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("goo", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal("goo, x", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)) Assert.Equal("goo, x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("goo, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub CollectionInitUndeclaredIdentifier() Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Static f1() As String = {[|X|]} End Sub End Module </file> </compilation>) Assert.True(dataFlowAnalysisResults.Succeeded) End Sub #End Region <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub UserDefinedOperatorBody() Dim analysisResults = CompileAndAnalyzeControlAndDataFlow( <compilation> <file name="a.vb"> Imports System Module Module1 Class B2 Public f As Integer Public Sub New(x As Integer) f = x End Sub Shared Widening Operator CType(x As Integer) As B2 [| Return New B2(x) |] End Operator End Class Sub Main() Static x As Integer = 11 Static b2 As B2 = x End Sub End Module </file> </compilation>) Dim ctrlFlowResults = analysisResults.Item1 Assert.True(ctrlFlowResults.Succeeded) Assert.Equal(1, ctrlFlowResults.ExitPoints.Count()) Assert.Equal(0, ctrlFlowResults.EntryPoints.Count()) Assert.True(ctrlFlowResults.StartPointIsReachable) Assert.False(ctrlFlowResults.EndPointIsReachable) Dim dataFlowResults = analysisResults.Item2 Assert.True(dataFlowResults.Succeeded) Assert.Empty(dataFlowResults.VariablesDeclared) Assert.Empty(dataFlowResults.AlwaysAssigned) Assert.Empty(dataFlowResults.Captured) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Empty((dataFlowResults.DataFlowsOut)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnEntry)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnExit)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Empty(dataFlowResults.WrittenInside) Assert.Empty(dataFlowResults.ReadOutside) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub UserDefinedOperatorInExpression() Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Module Module1 Class B2 Public f As Integer Public Sub New(x As Integer) f = x End Sub Shared Operator -(x As Integer, y As B2) As B2 Return New B2(x) End Operator End Class Sub Main(args As String()) Static x As Short = 123 Static bb = New B2(x) Static ret = [| Function(y) Return args.Length - (y - (x - bb)) End Function |] End Sub End Module </file> </compilation>) Assert.True(dataFlowResults.Succeeded) Assert.Equal("y", GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Empty(dataFlowResults.AlwaysAssigned) Assert.Equal("args, x, bb", GetSymbolNamesJoined(dataFlowResults.Captured)) Assert.Equal("args, x, bb", GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Empty(dataFlowResults.DataFlowsOut) Assert.Equal("args, x, bb, ret", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnEntry)) Assert.Equal("args, x, bb, ret", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnExit)) Assert.Equal("args, x, bb, y", GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal("y", GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("args, x, bb, ret", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub UserDefinedLiftedOperatorInExpr() Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Class A Structure S Shared Narrowing Operator CType(x As S?) As Integer System.Console.WriteLine("Operator Conv") Return 123 'Nothing End Operator Shared Operator *(x As S?, y As Integer?) As Integer? System.Console.WriteLine("Operator *") Return y End Operator End Structure End Class Module Program Sub M(Optional p As Integer? = Nothing) Static local As A.S? = New A.S() Static f As Func(Of A.S, Integer?) = [| Function(x) Return x * local * p End Function |] Console.Write(f(local)) End Sub End Module </file> </compilation>) Assert.True(dataFlowResults.Succeeded) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Empty(dataFlowResults.AlwaysAssigned) Assert.Equal("p, local", GetSymbolNamesJoined(dataFlowResults.Captured)) Assert.Equal("p, local", GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Empty(dataFlowResults.DataFlowsOut) Assert.Equal("f", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnEntry)) Assert.Equal("f", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnExit)) Assert.Equal("p, local, x", GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal("local, f", GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("p, local, f", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub DataFlowsInAndNullable() ' WARNING: if this test is edited, the test with the ' test with the same name in C# must be modified too Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Structure S Public F As Integer Public Sub New(_f As Integer) Me.F = _f End Sub End Structure Module Program Sub Main(args As String()) Static i As Integer? = 1 Static s As New S(1) [| Console.Write(i.Value) Console.Write(s.F) |] End Sub End Module </file> </compilation>) Assert.True(dataFlowResults.Succeeded) Assert.Empty(dataFlowResults.VariablesDeclared) Assert.Empty(dataFlowResults.AlwaysAssigned) Assert.Empty(dataFlowResults.Captured) Assert.Equal("i, s", GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Empty(dataFlowResults.DataFlowsOut) Assert.Equal("args", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnEntry)) Assert.Equal("args", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnExit)) Assert.Equal("i, s", GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Empty(dataFlowResults.WrittenInside) Assert.Empty(dataFlowResults.ReadOutside) Assert.Equal("args, i, s", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestWithEventsInitializer() Dim comp = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Class C1 WithEvents e As C1 = [|Me|] End Class </file> </compilation>) Debug.Assert(comp.Succeeded) End Sub <WorkItem(546820, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546820")> <Fact()> Public Sub TestDataFlowsInAndOut() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="TestDataFlowsInAndOut"> <file name="a.b"> class Program shared sub Main(args() as string) Static x as integer Static y as integer = 2 [| If x = y Then x = 2 y = 3 End If |] end sub end class </file> </compilation>) Assert.Equal("x, y", GetSymbolNamesJoined(analysis.DataFlowsIn)) Assert.Equal("x, y", GetSymbolNamesJoined(analysis.DataFlowsOut)) Assert.Equal("args, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)) Assert.Equal("args, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)) End Sub <WorkItem(546820, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546820")> <Fact()> Public Sub TestDataFlowsInAndOut2() Dim analysis = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"> class Program shared sub Main(args() as string) Static x as integer = 1 Static y as integer = 1 [| y = x x = 2 |] x = 3 y = 3 end sub end class </file> </compilation>) Assert.Equal("x", GetSymbolNamesJoined(analysis.DataFlowsIn)) Assert.Equal("x", GetSymbolNamesJoined(analysis.DataFlowsOut)) Assert.Equal("args, x, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)) Assert.Equal("args, x, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)) End Sub <WorkItem(546820, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546820")> <Fact()> Public Sub TestDataFlowsInAndOut3() Dim analysis = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"> class Program shared sub Main(args() as string) Static x as integer = 1 if x = 1 then [| x = 2 |] x = 3 end if end sub end class </file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.DataFlowsIn)) Assert.Equal("x", GetSymbolNamesJoined(analysis.DataFlowsOut)) Assert.Equal("args, x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)) Assert.Equal("args, x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)) End Sub <WorkItem(546820, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546820")> <Fact()> Public Sub TestDataFlowsInAndOut4() Dim analysis = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"> Imports System class Program shared sub Main(args() as string) [| Static x as integer = 1 Console.WriteLine(x) |] end sub end class </file> </compilation>) Assert.Equal("x", GetSymbolNamesJoined(analysis.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.DataFlowsOut)) Assert.Equal("args", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)) Assert.Equal("args, x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)) End Sub <WorkItem(546820, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546820")> <Fact()> Public Sub TestDataFlowsInAndOut5() Dim analysis = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"> Imports System class Program shared sub Main(args() as string) Static x as integer = 1 dim y = x [| x = 1 |] end sub end class </file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.DataFlowsIn)) Assert.Equal("x", GetSymbolNamesJoined(analysis.DataFlowsOut)) Assert.Equal("args, x, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)) Assert.Equal("args, x, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)) End Sub <WorkItem(546820, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546820")> <Fact()> Public Sub TestDataFlowsInAndOut6() Dim analysis = CompileAndAnalyzeDataFlow( <compilation> <file name="a.b"> Imports System class Program shared sub Main(args() as string) Static x as integer = 1 [| x = 1 |] dim y = x end sub end class </file> </compilation>) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.DataFlowsIn)) Assert.Equal("x", GetSymbolNamesJoined(analysis.DataFlowsOut)) Assert.Equal("args, x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)) Assert.Equal("args, x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)) End Sub #Region "Anonymous Type, Lambda" <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestCaptured() Dim analysis = CompileAndAnalyzeDataFlow( <compilation name="TestLifted"> <file name="a.b"> class C Dim field = 123 public sub F(x as integer) Static a as integer = 1, y as integer = 1 [| Static l1 = function() x+y+field |] Static c as integer = a + 4 + y end sub end class</file> </compilation>) Assert.Equal("l1", GetSymbolNamesJoined(analysis.VariablesDeclared)) Assert.Equal("l1", GetSymbolNamesJoined(analysis.AlwaysAssigned)) Assert.Equal("Me, x, y", GetSymbolNamesJoined(analysis.Captured)) Assert.Equal("Me, x, y", GetSymbolNamesJoined(analysis.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(analysis.DataFlowsOut)) Assert.Equal("Me, x, a, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)) Assert.Equal("Me, x, a, y, l1", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)) Assert.Equal("Me, x, y", GetSymbolNamesJoined(analysis.ReadInside)) Assert.Equal("l1", GetSymbolNamesJoined(analysis.WrittenInside)) Assert.Equal("a, y", GetSymbolNamesJoined(analysis.ReadOutside)) Assert.Equal("Me, x, a, y, c", GetSymbolNamesJoined(analysis.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestRegionControlFlowAnalysisInsideLambda() Dim controlFlowAnalysis = CompileAndAnalyzeControlFlow( <compilation name="TestRegionControlFlowAnalysisInsideLambda"> <file name="a.b"> Imports System Module Module1 Sub Main() Static f1 As Func(Of Integer, Integer) = Function(lambdaParam As Integer) [| Return lambdaParam + 1 |] End Function End Sub End Module </file> </compilation>) Assert.Equal(1, controlFlowAnalysis.ExitPoints.Count()) Assert.Equal(0, controlFlowAnalysis.EntryPoints.Count()) Assert.True(controlFlowAnalysis.StartPointIsReachable) Assert.False(controlFlowAnalysis.EndPointIsReachable) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestRegionControlFlowAnalysisInsideLambda2() Dim controlFlowAnalysis = CompileAndAnalyzeControlFlow( <compilation name="TestRegionControlFlowAnalysisInsideLambda2"> <file name="a.b"> Imports System Module Module1 Sub Main() Static f1 As Object = Function(lambdaParam As Integer) [| Return lambdaParam + 1 |] End Function End Sub End Module </file> </compilation>) Assert.Equal(1, controlFlowAnalysis.ExitPoints.Count()) Assert.Equal(0, controlFlowAnalysis.EntryPoints.Count()) Assert.True(controlFlowAnalysis.StartPointIsReachable) Assert.False(controlFlowAnalysis.EndPointIsReachable) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestRegionControlFlowAnalysisInsideLambda3() Dim controlFlowAnalysis = CompileAndAnalyzeControlFlow( <compilation name="TestRegionControlFlowAnalysisInsideLambda3"> <file name="a.b"> Imports System Module Module1 Sub Main() Static f1 As Object = Nothing f1 = Function(lambdaParam As Integer) [| Return lambdaParam + 1 |] End Function End Sub End Module </file> </compilation>) Assert.Equal(1, controlFlowAnalysis.ExitPoints.Count()) Assert.Equal(0, controlFlowAnalysis.EntryPoints.Count()) Assert.True(controlFlowAnalysis.StartPointIsReachable) Assert.False(controlFlowAnalysis.EndPointIsReachable) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub DoLoopInLambdaBody() Dim analysisResults = CompileAndAnalyzeControlAndDataFlow( <compilation name="DoLoopWithContinue"> <file name="a.b"> Class A Function Test1() As Integer Static x As Integer = 5 Console.Write(x) Static x as System.Action(of Integer) = Sub(i) [| Do Console.Write(i) i = i + 1 Continue Do 'Blah Loop Until i > 5 |] end sub Return x End Function End Class </file> </compilation>) Dim controlFlowAnalysisResults = analysisResults.Item1 Dim dataFlowAnalysisResults = analysisResults.Item2 Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()) Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()) Assert.True(controlFlowAnalysisResults.StartPointIsReachable) Assert.True(controlFlowAnalysisResults.EndPointIsReachable) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)) Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)) Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)) Assert.Equal("Me, x, x, i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)) Assert.Equal("Me, x, x, i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)) Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)) Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)) Assert.Equal("Me, x, x, i", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub AnonymousTypeAsLambdaLocal() Dim analysisResults = CompileAndAnalyzeControlAndDataFlow( <compilation> <file name="a.vb"> Option Infer On Imports System Public Class Test delegate R Func(OfT, R)(ref T t); Public Shared Sub Main() Dim local(3) As String [| Static lambda As Func(Of Integer, Integer) = Function(ByRef p As Integer) As Integer p = p * 2 Dim at = New With {New C(Of Integer)().F, C(Of String).SF, .L = local.Length + p} Console.Write("{0}, {1}, {2}", at.F, at.SF) Return at.L End Function |] End Sub Class C(Of T) Public Function F() As T Return Nothing End Function Shared Public Function SF() As T Return Nothing End Function End Class End Class </file> </compilation>) Dim controlFlowResults = analysisResults.Item1 Dim dataFlowResults = analysisResults.Item2 Assert.True(controlFlowResults.Succeeded) Assert.True(dataFlowResults.Succeeded) Assert.Equal("lambda", GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal("local", GetSymbolNamesJoined(dataFlowResults.Captured)) Assert.Equal("lambda, p, at", GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal("local", GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Equal("p", GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("local", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnEntry)) Assert.Equal("local, lambda", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnExit)) Assert.Equal("local, p, at", GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal("lambda, p, at", GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("local", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub AnonymousTypeAsNewInLocalContext() Dim analysisResults = CompileAndAnalyzeControlAndDataFlow( <compilation> <file name="a.vb"> Imports System Interface IGoo Delegate Sub DS(ByRef p As Char) End Interface Class CGoo Implements IGoo End Class Friend Module AM Sub Main(args As String()) Static igoo As IGoo = New CGoo() Static at1 As New With {.if = igoo} [| Static at2 As New With {.if = at1, igoo, .friend = New With {Key args, .lambda = DirectCast(Sub(ByRef p As Char) args(0) = p &amp; p p = "Q"c End Sub, IGoo.DS)}} |] Console.Write(args(0)) End Sub End Module </file> </compilation>) Dim controlFlowResults = analysisResults.Item1 Dim dataFlowResults = analysisResults.Item2 Assert.True(controlFlowResults.Succeeded) Assert.True(dataFlowResults.Succeeded) Assert.Equal("at2", GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal("args", GetSymbolNamesJoined(dataFlowResults.Captured)) Assert.Equal("at2, p", GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal("args, igoo, at1", GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Equal("p", GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("args, igoo, at1", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnEntry)) Assert.Equal("args, igoo, at1, at2", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnExit)) Assert.Equal("args, igoo, at1, p", GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal("at2, p", GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal("args, igoo", GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("args, igoo, at1", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub AnonymousTypeAsExpression() Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Interface IGoo Delegate Sub DS(ByRef p As Char) End Interface Friend Module AM Sub Main(args As String()) Static at1 As New With {.friend = New With {args, Key.lambda = DirectCast(Sub(ByRef p As Char) args(0) = p &amp; p p = "Q"c End Sub, IGoo.DS) } } Dim at2 As New With { Key .a= at1, .friend = New With { [| at1 |] }} Console.Write(args(0)) End Sub End Module </file> </compilation>) Assert.True(dataFlowResults.Succeeded) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal("args", GetSymbolNamesJoined(dataFlowResults.Captured)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal("at1", GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("args, at1", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnEntry)) Assert.Equal("args, at1", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnExit)) Assert.Equal("at1", GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal("args, at1, p", GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("args, at1, p, at2", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub AnonymousTypeAccessInstanceMember() Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Class AM Dim field = 123 Sub M(args As String()) Static at1 As New With {.friend = [| New With {args, Key.lambda = Sub(ByRef ary As Char()) Field = ary.Length End Sub } |] } End Sub End Class </file> </compilation>) Assert.True(dataFlowResults.Succeeded) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.Captured)) Assert.Equal("ary", GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal("Me, args", GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Equal("ary", GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("Me, args", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnEntry)) Assert.Equal("Me, args", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnExit)) Assert.Equal("Me, args, ary", GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal("ary", GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("Me, args, at1", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub AnonymousTypeFieldInitializerWithLeftOmitted() Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Class AM Dim field = 123 Sub M(args As String()) Static var1 As New AM Static at1 As New With { var1, .friend = [| .var1 |] } End Sub End Class </file> </compilation>) Assert.True(dataFlowResults.Succeeded) Assert.Null(GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Null(GetSymbolNamesJoined(dataFlowResults.Captured)) Assert.Null(GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Null(GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Null(GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("Me, args, var1", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnEntry)) Assert.Equal("Me, args, var1", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnExit)) Assert.Null(GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Null(GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal("var1", GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("Me, args, var1, at1", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub AnonymousTypeUsingMe() Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Class Base Protected Function F1() As Long Return 123 End Function Friend Overridable Function F2(n As Integer) As Integer Return 456 End Function End Class Class Derived Inherits Base Friend Overrides Function F2(n As Integer) As Integer Return 789 End Function Sub M() Dim func = Function(x) Dim at = [| New With {.dim = New With {Key .nested = Me.F2(x * x)}} |] Return at.dim.nested End Function End Sub End Class </file> </compilation>) Assert.True(dataFlowResults.Succeeded) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.Captured)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal("Me, x", GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("Me, func, x", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnEntry)) Assert.Equal("Me, func, x", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnExit)) Assert.Equal("Me, x", GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal("at", GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("Me, func, x, at", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub AnonymousTypeAccessMyBase() Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Class Base Protected Overridable Function F1() As Long Return 123 End Function End Class Class Derived Inherits Base Protected Overrides Function F1() As Long Return 789 End Function Sub M() Static func = Function(x) Dim at = [| New With {Key .dim = New With {MyBase.F1()}} |] Return at.dim.F1 End Function End Sub End Class </file> </compilation>) Assert.True(dataFlowResults.Succeeded) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.Captured)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("Me, func, x", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnEntry)) Assert.Equal("Me, func, x", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnExit)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal("at", GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("Me, func, x, at", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub AnonymousTypeAccessMyClass() Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Module M1 Class B1 Public Overridable Function F() As String Return "B1::F_" End Function End Class Class B2 Inherits B1 Public Overrides Function F() As String Return "B2::F_" End Function Public Sub TestMMM() Static an = [| New With {.an = Function(s) As String Return s + Me.F() + MyBase.F() + MyClass.F() End Function } |] Console.WriteLine(an.an("R=")) End Sub End Class Class D Inherits B2 Public Overrides Function F() As String Return "D::F_" End Function End Class Public Sub Main() Call (New D()).TestMMM() End Sub End Module </file> </compilation>) Assert.True(dataFlowResults.Succeeded) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.Captured)) Assert.Equal("s", GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnEntry)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnExit)) Assert.Equal("Me, s", GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal("s", GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal("an", GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("Me, an", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub AddressOfExpr() Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Module Program Sub Main() Static x5 = Function() AddressOf [|Main|] End Sub End Module </file> </compilation>) Assert.True(dataFlowResults.Succeeded) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub XmlEmbeddedExpression() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports System.Xml.Linq Module M Function F() As Object Static v0 = "v0" Static v1 = XName.Get("v1", "") Static v2 = XName.Get("v2", "") Static v3 = "v3" Static v4 = New XAttribute(XName.Get("v4", ""), "v4") Static v5 = "v5" Return <?xml version="1.0"?><<%= v1 %> <%= v2 %>="v2" v3=<%= v3 %> <%= v4 %>><%= v5 %></> End Function End Module ]]></file> </compilation>, references:=XmlReferences) Dim tree = compilation.SyntaxTrees.First() Dim model = compilation.GetSemanticModel(tree) Dim root = tree.GetCompilationUnitRoot() Dim node = DirectCast(root.FindToken(root.ToFullString().IndexOf("Return", StringComparison.Ordinal)).Parent, StatementSyntax) Dim dataFlowAnalysis = model.AnalyzeDataFlow(node, node) Assert.True(dataFlowAnalysis.Succeeded) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.AlwaysAssigned)) Assert.Equal("v1, v2, v3, v4, v5", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsOut)) Assert.Equal("v0, v1, v2, v3, v4, v5", GetSymbolNamesJoined(dataFlowAnalysis.DefinitelyAssignedOnEntry)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.DefinitelyAssignedOnExit)) Assert.Equal("v1, v2, v3, v4, v5", GetSymbolNamesJoined(dataFlowAnalysis.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.WrittenInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.ReadOutside)) Assert.Equal("v0, v1, v2, v3, v4, v5", GetSymbolNamesJoined(dataFlowAnalysis.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub XmlMemberAccess() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports System.Xml.Linq Module M Function F() As Object Static x = <a><b><c d="e"/></b></a> Return x.<b>...<c>.@<d> End Function End Module ]]></file> </compilation>, references:=XmlReferences) Dim tree = compilation.SyntaxTrees.First() Dim model = compilation.GetSemanticModel(tree) Dim root = tree.GetCompilationUnitRoot() Dim node = DirectCast(root.FindToken(root.ToFullString().IndexOf("Return", StringComparison.Ordinal)).Parent, StatementSyntax) Dim dataFlowAnalysis = model.AnalyzeDataFlow(node, node) Assert.True(dataFlowAnalysis.Succeeded) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.AlwaysAssigned)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsOut)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.DefinitelyAssignedOnEntry)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.DefinitelyAssignedOnExit)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.WrittenInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.ReadOutside)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub GenericStructureCycle() Dim source = <compilation> <file name="c.vb"><![CDATA[ Structure S(Of T) Public F As S(Of S(Of T)) End Structure Module M Sub M() Static o As S(Of Object) End Sub End Module ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source) Dim tree = compilation.SyntaxTrees.First() Dim model = compilation.GetSemanticModel(tree) Dim root = tree.GetCompilationUnitRoot() Dim node = DirectCast(root.FindToken(root.ToFullString().IndexOf("Static", StringComparison.Ordinal)).Parent, StatementSyntax) Dim dataFlowAnalysis = model.AnalyzeDataFlow(node, node) Assert.True(dataFlowAnalysis.Succeeded) Assert.Equal("o", GetSymbolNamesJoined(dataFlowAnalysis.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsOut)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.DefinitelyAssignedOnEntry)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.DefinitelyAssignedOnExit)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.WrittenInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.ReadOutside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.WrittenOutside)) End Sub #End Region #Region "With Statement" <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub WithStatement_Expression_RValue_3() Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Structure SSS Public A As String Public B As Integer Public Sub New(_a As String, _b As Integer) End Sub End Structure Class Clazz Sub TEST(i As Integer) With [| New SSS(Me.ToString(), i) |] Static s As Action = Sub() .A = "" End Sub End With End Sub End Class </file> </compilation>) Assert.True(dataFlowResults.Succeeded) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.Captured)) Assert.Equal("Me, i", GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("Me, i", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnEntry)) Assert.Equal("Me, i", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnExit)) Assert.Equal("Me, i", GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("Me, i, s", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub WithStatement_Expression_LValue_1() Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Structure SSS Public A As String Public B As Integer Public Sub New(_a As String, _b As Integer) End Sub End Structure Class Clazz Sub TEST(i As Integer) Static x As New SSS(Me.ToString(), i) With [| x |] End With End Sub End Class </file> </compilation>) Assert.False(dataFlowResults.Succeeded) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub WithStatement_Expression_LValue_2() Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Structure SSS Public A As String Public B As Integer Public Sub New(_a As String, _b As Integer) End Sub End Structure Class Clazz Sub TEST(i As Integer) Static x As New SSS(Me.ToString(), i) With [| x |] .A = "" End With End Sub End Class </file> </compilation>) Assert.True(dataFlowResults.Succeeded) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.Captured)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("Me, i, x", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnEntry)) Assert.Equal("Me, i, x", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnExit)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal("Me, i", GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("Me, i, x", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub WithStatement_Expression_LValue_2_() Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Structure SSS Public A As String Public B As Integer Public Sub New(_a As String, _b As Integer) End Sub End Structure Class Clazz Sub TEST(i As Integer) Static x As New SSS(Me.ToString(), i) With [| x |] .A = "" Dim a = .A Dim b = .B .B = 1 End With End Sub End Class </file> </compilation>) Assert.True(dataFlowResults.Succeeded) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.Captured)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("Me, i, x", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnEntry)) Assert.Equal("Me, i, x", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnExit)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal("Me, i, x", GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("Me, i, x, a, b", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub WithStatement_Expression_LValue_2a() Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Structure SSS Public A As String Public B As Integer Public Sub New(_a As String, _b As Integer) End Sub End Structure Class Clazz Sub TEST(i As Integer) Static x As New SSS(Me.ToString(), i) With x [| .A = "" |] End With End Sub End Class </file> </compilation>) Assert.True(dataFlowResults.Succeeded) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.Captured)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("Me, i, x", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnEntry)) Assert.Equal("Me, i, x", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnExit)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal("Me, i", GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("Me, i, x", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub WithStatement_Expression_LValue_2b() Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Structure SSS Public A As String Public B As Integer Public Sub New(_a As String, _b As Integer) End Sub End Structure Class Clazz Sub TEST(i As Integer) Static x As New SSS(Me.ToString(), i) With x [| .B = "" |] End With End Sub End Class </file> </compilation>) Assert.True(dataFlowResults.Succeeded) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.Captured)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("Me, i, x", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnEntry)) Assert.Equal("Me, i, x", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnExit)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal("Me, i", GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("Me, i, x", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub WithStatement_Expression_LValue_3() Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Structure SSS Public A As String Public B As Integer Public Sub New(_a As String, _b As Integer) End Sub End Structure Class Clazz Sub TEST(i As Integer) Static x As New SSS(Me.ToString(), i) With [| x |] Dim s As Action = Sub() .A = "" End Sub End With End Sub End Class </file> </compilation>) Assert.True(dataFlowResults.Succeeded) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.Captured)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("Me, i, x, s", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnEntry)) Assert.Equal("Me, i, x, s", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnExit)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal("Me, i", GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("Me, i, x, s", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub WithStatement_Expression_LValue_4() Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Structure SSSS Public A As String Public B As Integer End Structure Structure SSS Public S As SSSS nd Structure Class Clazz Sub TEST() Static x As New SSS() With [| x.S |] Dim s As Action = Sub() .A = "" End Sub End With End Sub End Class </file> </compilation>) Assert.True(dataFlowResults.Succeeded) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.Captured)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("Me, x, s", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnEntry)) Assert.Equal("Me, x, s", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnExit)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("Me, x, s", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub WithStatement_Expression_LValue_4a() Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Structure SSSS Public A As String Public B As Integer End Structure Structure SSS Public S As SSSS nd Structure Class Clazz Sub TEST() Static x As New SSS() With [| x |] .S Dim s As Action = Sub() .A = "" End Sub End With End Sub End Class </file> </compilation>) Assert.True(dataFlowResults.Succeeded) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.Captured)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("Me, x, s", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnEntry)) Assert.Equal("Me, x, s", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnExit)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("Me, x, s", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub WithStatement_Expression_LValue_4b() Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Structure SSSS Public A As String Public B As Integer End Structure Structure SSS Public S As SSSS nd Structure Class Clazz Sub TEST() Static x As New SSS() With x.S Dim s As Action = Sub() [| .A = "" |] End Sub End With x.ToString() End Sub End Class </file> </compilation>) Assert.True(dataFlowResults.Succeeded) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.Captured)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("Me, x, s", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnEntry)) Assert.Equal("Me, x, s", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnExit)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("Me, x, s", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub WithStatement_Expression_LValue_4c() Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Structure SSSS Public A As String Public B As Integer End Structure Structure SSS Public S As SSSS nd Structure Class Clazz Sub TEST() Static x As New SSS() With x.S Dim s As Action = Sub() [| .A |] = "" End Sub End With x.ToString() End Sub End Class </file> </compilation>) Assert.True(dataFlowResults.Succeeded) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.Captured)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("Me, x, s", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnEntry)) Assert.Equal("Me, x, s", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnExit)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("Me, x, s", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <ConditionalFact(GetType(NoUsedAssembliesValidation))> ' https://github.com/dotnet/roslyn/issues/40684: The test hook is blocked by this issue. <WorkItem(40684, "https://github.com/dotnet/roslyn/issues/40684")> Public Sub WithStatement_Expression_LValue_4d() Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Structure SSSS3 Public A As String Public B As Integer End Structure Structure SSSS2 Public S3 As SSSS3 End Structure Structure SSSS Public S2 As SSSS2 End Structure Structure SSS Public S As SSSS End Structure Class Clazz Sub TEST() Static x As New SSS() With x.S With .S2 With .S3 Static s As Action = Sub() [| .A = "" |] End Sub End With End With End With x.ToString() End Sub End Class </file> </compilation>) Assert.True(dataFlowResults.Succeeded) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.Captured)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("Me, x, s", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnEntry)) Assert.Equal("Me, x, s", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnExit)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("Me, x, s", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <ConditionalFact(GetType(NoUsedAssembliesValidation))> ' https://github.com/dotnet/roslyn/issues/40684: The test hook is blocked by this issue. <WorkItem(40684, "https://github.com/dotnet/roslyn/issues/40684")> Public Sub WithStatement_Expression_LValue_4e() Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Structure SSSS3 Public A As String Public B As Integer End Structure Structure SSSS2 Public S3 As SSSS3 End Structure Structure SSSS Public S2 As SSSS2 End Structure Structure SSS Public S As SSSS End Structure Class Clazz Sub TEST() Static x As New SSS() With x.S With .S2 With .S3 Static s As Action = Sub() Dim xyz = [| .A |] End Sub End With End With End With x.ToString() End Sub End Class </file> </compilation>) Assert.True(dataFlowResults.Succeeded) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.Captured)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("Me, x, s", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnEntry)) Assert.Equal("Me, x, s", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnExit)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("Me, x, s, xyz", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub WithStatement_Expression_LValue_4f() Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Structure SSSS3 Public A As String Public B As Integer End Structure Structure SSSS2 Public S3 As SSSS3 End Structure Structure SSSS Public S2 As SSSS2 End Structure Structure SSS Public S As SSSS End Structure Class Clazz Sub TEST() Static x As New SSS() With [| x.S.S2 |].S3 Static s As Action = Sub() .A = "" End Sub End With x.ToString() End Sub End Class </file> </compilation>) Assert.True(dataFlowResults.Succeeded) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.Captured)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("Me, x, s", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnEntry)) Assert.Equal("Me, x, s", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnExit)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("Me, x, s", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub WithStatement_Expression_LValue_4g() Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Structure SSSS3 Public A As String Public B As Integer End Structure Structure SSSS2 Public S3 As SSSS3 End Structure Structure SSSS Public S2 As SSSS2 End Structure Class SSS Public S As SSSS End Class Class Clazz Sub TEST() Static x As New SSS() With [| x.S.S2 |].S3 Static s As Action = Sub() .A = "" End Sub End With x.ToString() End Sub End Class </file> </compilation>) Assert.True(dataFlowResults.Succeeded) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.Captured)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("Me, x", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnEntry)) Assert.Equal("Me, x", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnExit)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("Me, x, s", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub WithStatement_MeReference_1() Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Structure SSSS3 Public A As String Public B As Integer End Structure Structure SSSS2 Public S3 As SSSS3 End Structure Structure SSSS Public S2 As SSSS2 End Structure Structure SSS Public S As SSSS End Structure Class Clazz Public x As New SSS() Sub TEST() With [| x.S.S2 |].S3 Static s As Action = Sub() .A = "" End Sub End With x.ToString() End Sub End Class </file> </compilation>) Assert.True(dataFlowResults.Succeeded) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.Captured)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("Me, s", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnEntry)) Assert.Equal("Me, s", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnExit)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("Me, s", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub WithStatement_ComplexExpression_1() Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Structure SSSS3 Public A As String Public B As Integer End Structure Structure SSSS2 Public S3 As SSSS3 End Structure Structure SSSS Public S2 As SSSS2 End Structure Structure SSS Public S As SSSS End Structure Class Clazz Public x As New SSS() Sub TEST() With DirectCast(Function() Return [| Me.x |] End Function, Func(Of SSS))() With .S.S2 Static a = .S3.A End With End With x.ToString() End Sub End Class </file> </compilation>) Assert.True(dataFlowResults.Succeeded) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.Captured)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnEntry)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnExit)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("Me, a", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub WithStatement_ComplexExpression_2() Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation> <file name="a.vb"> Imports System Structure SSSS3 Public A As String Public B As Integer End Structure Structure SSSS2 Public S3 As SSSS3 End Structure Structure SSSS Public S2 As SSSS2 End Structure Structure SSS Public S As SSSS End Structure Class Clazz Public x As New SSS() Sub TEST() Static arr(,) As SSS With arr(1, [| DirectCast(Function() Return x End Function, Func(Of SSS)) |] ().S.S2.S3.B).S Static a = .S2.S3.A End With x.ToString() End Sub End Class </file> </compilation>) Assert.True(dataFlowResults.Succeeded) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.Captured)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnEntry)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnExit)) Assert.Equal("Me", GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal("Me, arr", GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("Me, a", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub #End Region #Region "Select Statement" <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestSelectCase_Empty() Dim analysis = CompileAndAnalyzeControlAndDataFlow( <compilation name="TestSelectCase_Empty"> <file name="a.b"> Module Program Sub Main() Static obj As Object = 0 [| Select Case obj End Select |] End Sub End Module </file> </compilation>) Dim controlFlowResults = analysis.Item1 Assert.True(controlFlowResults.Succeeded) Assert.Equal(0, controlFlowResults.ExitPoints.Count()) Assert.Equal(0, controlFlowResults.EntryPoints.Count()) Assert.True(controlFlowResults.EndPointIsReachable) Dim dataFlowResults = analysis.Item2 Assert.True(dataFlowResults.Succeeded) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.Captured)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal("obj", GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("obj", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnEntry)) Assert.Equal("obj", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnExit)) Assert.Equal("obj", GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("obj", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestSelectCase_SingleCaseBlock_01() Dim analysis = CompileAndAnalyzeControlAndDataFlow( <compilation name="TestSelectCase_SingleCaseBlock_01"> <file name="a.b"> Module Program Sub Main() Static obj1 As Object = 0 Static obj2 As Object = 0 Static obj3 As Object [| Select Case obj1 Case obj2 Static obj4 = 1 obj3 = obj4 End Select |] End Sub End Module </file> </compilation>) Dim controlFlowResults = analysis.Item1 Assert.True(controlFlowResults.Succeeded) Assert.Equal(0, controlFlowResults.ExitPoints.Count()) Assert.Equal(0, controlFlowResults.EntryPoints.Count()) Assert.True(controlFlowResults.EndPointIsReachable) Dim dataFlowResults = analysis.Item2 Assert.True(dataFlowResults.Succeeded) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.Captured)) Assert.Equal("obj4", GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal("obj1, obj2, obj4", GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("obj1, obj2", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnEntry)) Assert.Equal("obj1, obj2", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnExit)) Assert.Equal("obj1, obj2, obj4", GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal("obj3, obj4", GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("obj1, obj2", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestSelectCase_SingleCaseBlock_02() Dim analysis = CompileAndAnalyzeControlAndDataFlow( <compilation name="TestSelectCase_SingleCaseBlock_02"> <file name="a.b"> Module Program Sub Main() Static obj1 As Object = 0 Static obj2 As Object = 0 Static obj3 As Object Select Case obj1 Case obj2 [| Static obj4 = 1 obj3 = obj4 |] End Select End Sub End Module </file> </compilation>) Dim controlFlowResults = analysis.Item1 Assert.True(controlFlowResults.Succeeded) Assert.Equal(0, controlFlowResults.ExitPoints.Count()) Assert.Equal(0, controlFlowResults.EntryPoints.Count()) Assert.True(controlFlowResults.EndPointIsReachable) Dim dataFlowResults = analysis.Item2 Assert.True(dataFlowResults.Succeeded) Assert.Equal("obj3, obj4", GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.Captured)) Assert.Equal("obj4", GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal("obj4", GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("obj1, obj2", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnEntry)) Assert.Equal("obj1, obj2, obj3, obj4", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnExit)) Assert.Equal("obj4", GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal("obj3, obj4", GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal("obj1, obj2", GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("obj1, obj2", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestSelectCase_CaseBlocksWithCaseElse_01() Dim analysis = CompileAndAnalyzeControlAndDataFlow( <compilation name="TestSelectCase_CaseBlocksWithCaseElse_01"> <file name="a.b"> Module Program Sub Main() Static obj1 As Object = 0 Static obj2 As Object = 0 Static obj3 As Object Static obj4 As Object [| Select Case obj1 Case obj2 Static obj5 = 1 obj3 = obj5 obj4 = obj5 Case Else Static obj5 = 2 obj2 = obj5 obj4 = obj5 End Select |] obj1 = obj3 + obj4 End Sub End Module </file> </compilation>) Dim controlFlowResults = analysis.Item1 Assert.True(controlFlowResults.Succeeded) Assert.Equal(0, controlFlowResults.ExitPoints.Count()) Assert.Equal(0, controlFlowResults.EntryPoints.Count()) Assert.True(controlFlowResults.EndPointIsReachable) Dim dataFlowResults = analysis.Item2 Assert.True(dataFlowResults.Succeeded) Assert.Equal("obj4", GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.Captured)) Assert.Equal("obj5, obj5", GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal("obj1, obj2, obj5, obj5", GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Equal("obj2, obj3, obj4", GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("obj1, obj2", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnEntry)) Assert.Equal("obj1, obj2, obj4", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnExit)) Assert.Equal("obj1, obj2, obj5, obj5", GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal("obj2, obj3, obj4, obj5, obj5", GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal("obj3, obj4", GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("obj1, obj2", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestSelectCase_CaseBlocksWithCaseElse_01_CaseElseRegion() Dim analysis = CompileAndAnalyzeControlAndDataFlow( <compilation name="TestSelectCase_CaseBlocksWithCaseElse_01_CaseElseRegion"> <file name="a.b"> Module Program Sub Main() Static obj1 As Object = 0 Static obj2 As Object = 0 Static obj3 As Object Static obj4 As Object Select Case obj1 Case obj2 Static obj5 = 1 obj3 = obj5 obj4 = obj5 Case Else [| Static obj5 = 2 obj2 = obj5 obj4 = obj5 |] End Select obj1 = obj3 + obj4 End Sub End Module </file> </compilation>) Dim controlFlowResults = analysis.Item1 Assert.True(controlFlowResults.Succeeded) Assert.Equal(0, controlFlowResults.ExitPoints.Count()) Assert.Equal(0, controlFlowResults.EntryPoints.Count()) Assert.True(controlFlowResults.EndPointIsReachable) Dim dataFlowResults = analysis.Item2 Assert.True(dataFlowResults.Succeeded) Assert.Equal("obj2, obj4, obj5", GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.Captured)) Assert.Equal("obj5", GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal("obj5", GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Equal("obj2, obj4", GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("obj1, obj2", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnEntry)) Assert.Equal("obj1, obj2, obj4, obj5", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnExit)) Assert.Equal("obj5", GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal("obj2, obj4, obj5", GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal("obj1, obj2, obj3, obj4, obj5", GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("obj1, obj2, obj3, obj4, obj5", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestSelectCase_CaseBlocksWithCaseElse_02() Dim analysis = CompileAndAnalyzeControlAndDataFlow( <compilation name="TestSelectCase_CaseBlocksWithCaseElse_02"> <file name="a.b"> Module Program Sub Main() Static obj1 As Object = 0 Static obj2 As Object = 0 Static obj3 As Object [| Select Case obj1 Case obj2 Static obj4 = 1 obj3 = obj4 Case Else End Select |] End Sub End Module </file> </compilation>) Dim controlFlowResults = analysis.Item1 Assert.True(controlFlowResults.Succeeded) Assert.Equal(0, controlFlowResults.ExitPoints.Count()) Assert.Equal(0, controlFlowResults.EntryPoints.Count()) Assert.True(controlFlowResults.EndPointIsReachable) Dim dataFlowResults = analysis.Item2 Assert.True(dataFlowResults.Succeeded) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.Captured)) Assert.Equal("obj4", GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal("obj1, obj2, obj4", GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("obj1, obj2", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnEntry)) Assert.Equal("obj1, obj2", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnExit)) Assert.Equal("obj1, obj2, obj4", GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal("obj3, obj4", GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("obj1, obj2", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestSelectCase_CaseBlockWithCaseElse_03() Dim analysis = CompileAndAnalyzeControlAndDataFlow( <compilation name="TestSelectCase_CaseBlockWithCaseElse_03"> <file name="a.b"> Module Program Sub Main() Static obj1 As Object = 0 Static obj2 As Object = 0 Static obj3 As Object [| Select Case obj1 Case obj2 LabelCase: Static obj4 = 1 obj3 = obj4 Case Else Goto LabelCase End Select |] End Sub End Module </file> </compilation>) Dim controlFlowResults = analysis.Item1 Assert.True(controlFlowResults.Succeeded) Assert.Equal(0, controlFlowResults.ExitPoints.Count()) Assert.Equal(0, controlFlowResults.EntryPoints.Count()) Assert.True(controlFlowResults.EndPointIsReachable) Dim dataFlowResults = analysis.Item2 Assert.True(dataFlowResults.Succeeded) Assert.Equal("obj3, obj4", GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.Captured)) Assert.Equal("obj4", GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal("obj1, obj2, obj4", GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("obj1, obj2", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnEntry)) Assert.Equal("obj1, obj2, obj3, obj4", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnExit)) Assert.Equal("obj1, obj2, obj4", GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal("obj3, obj4", GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("obj1, obj2", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestSelectCase_CaseBlocksWithoutCaseElse_01() Dim analysis = CompileAndAnalyzeControlAndDataFlow( <compilation name="TestSelectCase_CaseBlocksWithoutCaseElse_01"> <file name="a.b"> Module Program Sub Main() Static obj1 As Object = 0 Static obj2 As Object = 0 Static obj3 As Object Static obj4 As Object [| Select Case obj1 Case obj2 Static obj5 = 1 obj3 = obj5 obj4 = obj5 Case obj3 Static obj5 = 2 obj2 = obj5 obj4 = obj5 End Select |] obj1 = obj3 + obj4 End Sub End Module </file> </compilation>) Dim controlFlowResults = analysis.Item1 Assert.True(controlFlowResults.Succeeded) Assert.Equal(0, controlFlowResults.ExitPoints.Count()) Assert.Equal(0, controlFlowResults.EntryPoints.Count()) Assert.True(controlFlowResults.EndPointIsReachable) Dim dataFlowResults = analysis.Item2 Assert.True(dataFlowResults.Succeeded) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.Captured)) Assert.Equal("obj5, obj5", GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal("obj1, obj2, obj3, obj5, obj5", GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Equal("obj2, obj3, obj4", GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("obj1, obj2", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnEntry)) Assert.Equal("obj1, obj2", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnExit)) Assert.Equal("obj1, obj2, obj3, obj5, obj5", GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal("obj2, obj3, obj4, obj5, obj5", GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal("obj3, obj4", GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("obj1, obj2", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestSelectCase_CaseBlockWithoutCaseElse_02() Dim analysis = CompileAndAnalyzeControlAndDataFlow( <compilation name="TestSelectCase_CaseBlockWithoutCaseElse_02"> <file name="a.b"> Module Program Sub Main() Static obj1 As Object = 0 Static obj2 As Object = 0 Static obj3 As Object [| Select Case obj1 Case obj2 LabelCase: Static obj4 = 1 obj3 = obj4 Case obj3 Goto LabelCase End Select |] End Sub End Module </file> </compilation>) Dim controlFlowResults = analysis.Item1 Assert.True(controlFlowResults.Succeeded) Assert.Equal(0, controlFlowResults.ExitPoints.Count()) Assert.Equal(0, controlFlowResults.EntryPoints.Count()) Assert.True(controlFlowResults.EndPointIsReachable) Dim dataFlowResults = analysis.Item2 Assert.True(dataFlowResults.Succeeded) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.Captured)) Assert.Equal("obj4", GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal("obj1, obj2, obj3, obj4", GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Equal("obj3", GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("obj1, obj2", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnEntry)) Assert.Equal("obj1, obj2", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnExit)) Assert.Equal("obj1, obj2, obj3, obj4", GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal("obj3, obj4", GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("obj1, obj2", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestSelectCase_CaseStatementRegion() Dim dataFlowResults = CompileAndAnalyzeDataFlow( <compilation name="TestSelectCase_CaseStatementRegion"> <file name="a.b"> Module Program Sub Main() Static obj1 As Object = 0 Static obj2 As Object = 0 Static obj3 As Object Select Case obj1 Case [|obj2|] obj3 = 0 End Select End Sub End Module </file> </compilation>) Assert.True(dataFlowResults.Succeeded) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.Captured)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("obj1, obj2", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnEntry)) Assert.Equal("obj1, obj2", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnExit)) Assert.Equal("obj2", GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal("obj1", GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("obj1, obj2, obj3", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestSelectCase_Error_CaseElseBeforeCaseBlock() Dim analysis = CompileAndAnalyzeControlAndDataFlow( <compilation name="TestSelectCase_Error_CaseElseBeforeCaseBlock"> <file name="a.b"> Module Program Sub Main() Static obj1 As Object = 0 Static obj2 As Object = 0 Static obj3 As Object Static obj4 As Object Select Case obj1 Case Else [| Static obj5 = 2 obj2 = obj5 obj4 = obj5 |] Case obj2 Static obj5 = 1 obj3 = obj5 obj4 = obj5 End Select obj1 = obj3 + obj4 End Sub End Module </file> </compilation>) Dim controlFlowResults = analysis.Item1 Assert.True(controlFlowResults.Succeeded) Assert.Equal(0, controlFlowResults.ExitPoints.Count()) Assert.Equal(0, controlFlowResults.EntryPoints.Count()) Assert.True(controlFlowResults.EndPointIsReachable) Dim dataFlowResults = analysis.Item2 Assert.True(dataFlowResults.Succeeded) Assert.Equal("obj2, obj4, obj5", GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.Captured)) Assert.Equal("obj5", GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal("obj5", GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Equal("obj2, obj4", GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("obj1, obj2", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnEntry)) Assert.Equal("obj1, obj2, obj4, obj5", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnExit)) Assert.Equal("obj5", GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal("obj2, obj4, obj5", GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal("obj1, obj2, obj3, obj4, obj5", GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("obj1, obj2, obj3, obj4, obj5", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <WorkItem(529089, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529089")> <Fact> Public Sub CaseClauseNotReachable() Dim analysis = CompileAndAnalyzeControlAndDataFlow( <compilation name="TestSelectCase_Error_CaseElseBeforeCaseBlock"> <file name="a.b"> Module Program Sub Main(args As String()) Static x = 10 Select Case 5 Case 10 [|x = x + 1|] End Select End Sub End Module </file> </compilation>) Dim controlFlowResults = analysis.Item1 Assert.True(controlFlowResults.Succeeded) Assert.Equal(0, controlFlowResults.ExitPoints.Count()) Assert.Equal(0, controlFlowResults.EntryPoints.Count()) Assert.True(controlFlowResults.StartPointIsReachable) Assert.True(controlFlowResults.EndPointIsReachable) Dim dataFlowResults = analysis.Item2 Assert.True(dataFlowResults.Succeeded) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.Captured)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.VariablesDeclared)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.DataFlowsIn)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.DataFlowsOut)) Assert.Equal("args, x", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnEntry)) Assert.Equal("args, x", GetSymbolNamesJoined(dataFlowResults.DefinitelyAssignedOnExit)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.ReadInside)) Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.WrittenInside)) Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.ReadOutside)) Assert.Equal("args, x", GetSymbolNamesJoined(dataFlowResults.WrittenOutside)) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub MyBaseExpressionSyntax() Dim source = <compilation> <file name="a.vb"> Imports System Public Class BaseClass Public Overridable Sub MyMeth() End Sub End Class Public Class MyClass : Inherits BaseClass Public Overrides Sub MyMeth() MyBase.MyMeth() End Sub Public Sub OtherMeth() Static f = Function() MyBase End Sub End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlib40(source) Dim tree = comp.SyntaxTrees.Single() Dim model = comp.GetSemanticModel(tree) Dim invocation = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of InvocationExpressionSyntax)().Single() Dim flowAnalysis = model.AnalyzeDataFlow(invocation) Assert.Empty(flowAnalysis.Captured) Assert.Equal("Me As [MyClass]", flowAnalysis.DataFlowsIn.Single().ToTestDisplayString()) Assert.Empty(flowAnalysis.DataFlowsOut) Assert.Equal("Me As [MyClass]", flowAnalysis.ReadInside.Single().ToTestDisplayString()) Assert.Empty(flowAnalysis.WrittenInside) Assert.Equal("Me As [MyClass]", flowAnalysis.WrittenOutside.Single().ToTestDisplayString()) Dim lambda = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of LambdaExpressionSyntax)().Single() flowAnalysis = model.AnalyzeDataFlow(lambda) Assert.Equal("Me As [MyClass]", flowAnalysis.Captured.Single().ToTestDisplayString()) Assert.Equal("Me As [MyClass]", flowAnalysis.DataFlowsIn.Single().ToTestDisplayString()) Assert.Empty(flowAnalysis.DataFlowsOut) Assert.Equal("Me As [MyClass]", flowAnalysis.ReadInside.Single().ToTestDisplayString()) Assert.Empty(flowAnalysis.WrittenInside) Assert.Equal("Me, f", GetSymbolNamesJoined(flowAnalysis.WrittenOutside)) End Sub #End Region End Class End Namespace
-1
dotnet/roslyn
56,011
React to string comparison changing on .NET Core
The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
jaredpar
"2021-08-30T17:18:52Z"
"2021-08-30T20:20:04Z"
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
4d99cda6e446e77dbb302e26388c1093bd3ef569
React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
./src/EditorFeatures/VisualBasic/FindUsages/VisualBasicFindUsagesLSPService.vb
' 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 Microsoft.CodeAnalysis.Editor.FindUsages Imports Microsoft.CodeAnalysis.Editor.Shared.Utilities Imports Microsoft.CodeAnalysis.Host.Mef Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.FindUsages <ExportLanguageService(GetType(IFindUsagesLSPService), LanguageNames.VisualBasic), [Shared]> Friend Class VisualBasicFindUsagesLSPService Inherits AbstractFindUsagesService <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub End Class End Namespace
' 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 Microsoft.CodeAnalysis.Editor.FindUsages Imports Microsoft.CodeAnalysis.Editor.Shared.Utilities Imports Microsoft.CodeAnalysis.Host.Mef Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.FindUsages <ExportLanguageService(GetType(IFindUsagesLSPService), LanguageNames.VisualBasic), [Shared]> Friend Class VisualBasicFindUsagesLSPService Inherits AbstractFindUsagesService <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub End Class End Namespace
-1
dotnet/roslyn
56,011
React to string comparison changing on .NET Core
The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
jaredpar
"2021-08-30T17:18:52Z"
"2021-08-30T20:20:04Z"
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
4d99cda6e446e77dbb302e26388c1093bd3ef569
React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
./src/Compilers/VisualBasic/Portable/Symbols/Tuples/TupleMethodSymbol.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Globalization Imports System.Threading Imports Microsoft.CodeAnalysis Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ''' <summary> ''' Represents a method of a tuple type (such as (int, byte).ToString()) ''' that is backed by a method within the tuple underlying type. ''' </summary> Friend NotInheritable Class TupleMethodSymbol Inherits WrappedMethodSymbol Private ReadOnly _containingType As TupleTypeSymbol Private ReadOnly _underlyingMethod As MethodSymbol Private ReadOnly _typeParameters As ImmutableArray(Of TypeParameterSymbol) Private _lazyParameters As ImmutableArray(Of ParameterSymbol) Public Overrides ReadOnly Property IsTupleMethod As Boolean Get Return True End Get End Property Public Overrides ReadOnly Property TupleUnderlyingMethod As MethodSymbol Get Return Me._underlyingMethod.ConstructedFrom End Get End Property Public Overrides ReadOnly Property UnderlyingMethod As MethodSymbol Get Return Me._underlyingMethod End Get End Property Public Overrides ReadOnly Property AssociatedSymbol As Symbol Get Return Me._containingType.GetTupleMemberSymbolForUnderlyingMember(Of Symbol)(Me._underlyingMethod.ConstructedFrom.AssociatedSymbol) End Get End Property Public Overrides ReadOnly Property ContainingSymbol As Symbol Get Return Me._containingType End Get End Property Public Overrides ReadOnly Property ExplicitInterfaceImplementations As ImmutableArray(Of MethodSymbol) Get Return Me._underlyingMethod.ConstructedFrom.ExplicitInterfaceImplementations End Get End Property Public Overrides ReadOnly Property Parameters As ImmutableArray(Of ParameterSymbol) Get If Me._lazyParameters.IsDefault Then InterlockedOperations.Initialize(Of ParameterSymbol)(Me._lazyParameters, Me.CreateParameters()) End If Return Me._lazyParameters End Get End Property Public Overrides ReadOnly Property IsSub As Boolean Get Return Me._underlyingMethod.IsSub End Get End Property Public Overrides ReadOnly Property ReturnType As TypeSymbol Get Return Me._underlyingMethod.ReturnType End Get End Property Public Overrides ReadOnly Property ReturnTypeCustomModifiers As ImmutableArray(Of CustomModifier) Get Return Me._underlyingMethod.ReturnTypeCustomModifiers End Get End Property Public Overrides ReadOnly Property RefCustomModifiers As ImmutableArray(Of CustomModifier) Get Return Me._underlyingMethod.RefCustomModifiers End Get End Property Public Overrides ReadOnly Property TypeArguments As ImmutableArray(Of TypeSymbol) Get Return StaticCast(Of TypeSymbol).From(Me._typeParameters) End Get End Property Public Overrides ReadOnly Property TypeParameters As ImmutableArray(Of TypeParameterSymbol) Get Return Me._typeParameters End Get End Property Public Sub New(container As TupleTypeSymbol, underlyingMethod As MethodSymbol) Debug.Assert(underlyingMethod.ConstructedFrom Is underlyingMethod) Me._containingType = container Me._underlyingMethod = underlyingMethod Me._typeParameters = Me._underlyingMethod.TypeParameters End Sub Private Function CreateParameters() As ImmutableArray(Of ParameterSymbol) Return Me._underlyingMethod.Parameters.SelectAsArray(Of ParameterSymbol)(Function(p) New TupleParameterSymbol(Me, p)) End Function Public Overrides Function GetAttributes() As ImmutableArray(Of VisualBasicAttributeData) Return Me._underlyingMethod.GetAttributes() End Function Public Overrides Function GetReturnTypeAttributes() As ImmutableArray(Of VisualBasicAttributeData) Return Me._underlyingMethod.GetReturnTypeAttributes() End Function Friend Overrides Function CalculateLocalSyntaxOffset(localPosition As Integer, localTree As SyntaxTree) As Integer Throw ExceptionUtilities.Unreachable End Function Friend Overrides Function GetUseSiteInfo() As UseSiteInfo(Of AssemblySymbol) Dim useSiteInfo As UseSiteInfo(Of AssemblySymbol) = MyBase.GetUseSiteInfo() MyBase.MergeUseSiteInfo(useSiteInfo, Me._underlyingMethod.GetUseSiteInfo()) Return useSiteInfo End Function Public Overrides Function GetHashCode() As Integer Return Me._underlyingMethod.ConstructedFrom.GetHashCode() End Function Public Overrides Function Equals(obj As Object) As Boolean Return Me.Equals(TryCast(obj, TupleMethodSymbol)) End Function Public Overloads Function Equals(other As TupleMethodSymbol) As Boolean Return other Is Me OrElse (other IsNot Nothing AndAlso TypeSymbol.Equals(Me._containingType, other._containingType, TypeCompareKind.ConsiderEverything) AndAlso Me._underlyingMethod.ConstructedFrom = other._underlyingMethod.ConstructedFrom) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Globalization Imports System.Threading Imports Microsoft.CodeAnalysis Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ''' <summary> ''' Represents a method of a tuple type (such as (int, byte).ToString()) ''' that is backed by a method within the tuple underlying type. ''' </summary> Friend NotInheritable Class TupleMethodSymbol Inherits WrappedMethodSymbol Private ReadOnly _containingType As TupleTypeSymbol Private ReadOnly _underlyingMethod As MethodSymbol Private ReadOnly _typeParameters As ImmutableArray(Of TypeParameterSymbol) Private _lazyParameters As ImmutableArray(Of ParameterSymbol) Public Overrides ReadOnly Property IsTupleMethod As Boolean Get Return True End Get End Property Public Overrides ReadOnly Property TupleUnderlyingMethod As MethodSymbol Get Return Me._underlyingMethod.ConstructedFrom End Get End Property Public Overrides ReadOnly Property UnderlyingMethod As MethodSymbol Get Return Me._underlyingMethod End Get End Property Public Overrides ReadOnly Property AssociatedSymbol As Symbol Get Return Me._containingType.GetTupleMemberSymbolForUnderlyingMember(Of Symbol)(Me._underlyingMethod.ConstructedFrom.AssociatedSymbol) End Get End Property Public Overrides ReadOnly Property ContainingSymbol As Symbol Get Return Me._containingType End Get End Property Public Overrides ReadOnly Property ExplicitInterfaceImplementations As ImmutableArray(Of MethodSymbol) Get Return Me._underlyingMethod.ConstructedFrom.ExplicitInterfaceImplementations End Get End Property Public Overrides ReadOnly Property Parameters As ImmutableArray(Of ParameterSymbol) Get If Me._lazyParameters.IsDefault Then InterlockedOperations.Initialize(Of ParameterSymbol)(Me._lazyParameters, Me.CreateParameters()) End If Return Me._lazyParameters End Get End Property Public Overrides ReadOnly Property IsSub As Boolean Get Return Me._underlyingMethod.IsSub End Get End Property Public Overrides ReadOnly Property ReturnType As TypeSymbol Get Return Me._underlyingMethod.ReturnType End Get End Property Public Overrides ReadOnly Property ReturnTypeCustomModifiers As ImmutableArray(Of CustomModifier) Get Return Me._underlyingMethod.ReturnTypeCustomModifiers End Get End Property Public Overrides ReadOnly Property RefCustomModifiers As ImmutableArray(Of CustomModifier) Get Return Me._underlyingMethod.RefCustomModifiers End Get End Property Public Overrides ReadOnly Property TypeArguments As ImmutableArray(Of TypeSymbol) Get Return StaticCast(Of TypeSymbol).From(Me._typeParameters) End Get End Property Public Overrides ReadOnly Property TypeParameters As ImmutableArray(Of TypeParameterSymbol) Get Return Me._typeParameters End Get End Property Public Sub New(container As TupleTypeSymbol, underlyingMethod As MethodSymbol) Debug.Assert(underlyingMethod.ConstructedFrom Is underlyingMethod) Me._containingType = container Me._underlyingMethod = underlyingMethod Me._typeParameters = Me._underlyingMethod.TypeParameters End Sub Private Function CreateParameters() As ImmutableArray(Of ParameterSymbol) Return Me._underlyingMethod.Parameters.SelectAsArray(Of ParameterSymbol)(Function(p) New TupleParameterSymbol(Me, p)) End Function Public Overrides Function GetAttributes() As ImmutableArray(Of VisualBasicAttributeData) Return Me._underlyingMethod.GetAttributes() End Function Public Overrides Function GetReturnTypeAttributes() As ImmutableArray(Of VisualBasicAttributeData) Return Me._underlyingMethod.GetReturnTypeAttributes() End Function Friend Overrides Function CalculateLocalSyntaxOffset(localPosition As Integer, localTree As SyntaxTree) As Integer Throw ExceptionUtilities.Unreachable End Function Friend Overrides Function GetUseSiteInfo() As UseSiteInfo(Of AssemblySymbol) Dim useSiteInfo As UseSiteInfo(Of AssemblySymbol) = MyBase.GetUseSiteInfo() MyBase.MergeUseSiteInfo(useSiteInfo, Me._underlyingMethod.GetUseSiteInfo()) Return useSiteInfo End Function Public Overrides Function GetHashCode() As Integer Return Me._underlyingMethod.ConstructedFrom.GetHashCode() End Function Public Overrides Function Equals(obj As Object) As Boolean Return Me.Equals(TryCast(obj, TupleMethodSymbol)) End Function Public Overloads Function Equals(other As TupleMethodSymbol) As Boolean Return other Is Me OrElse (other IsNot Nothing AndAlso TypeSymbol.Equals(Me._containingType, other._containingType, TypeCompareKind.ConsiderEverything) AndAlso Me._underlyingMethod.ConstructedFrom = other._underlyingMethod.ConstructedFrom) End Function End Class End Namespace
-1
dotnet/roslyn
56,011
React to string comparison changing on .NET Core
The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
jaredpar
"2021-08-30T17:18:52Z"
"2021-08-30T20:20:04Z"
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
4d99cda6e446e77dbb302e26388c1093bd3ef569
React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Simplification/VisualBasicInferredMemberNameSimplifier.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Simplification Friend Module VisualBasicInferredMemberNameSimplifier Friend Function CanSimplifyTupleName(node As SimpleArgumentSyntax, parseOptions As VisualBasicParseOptions) As Boolean ' Tuple elements are arguments in a tuple expression If node.NameColonEquals Is Nothing OrElse Not node.IsParentKind(SyntaxKind.TupleExpression) Then Return False End If If parseOptions.LanguageVersion < LanguageVersion.VisualBasic15_3 Then Return False End If If RemovalCausesAmbiguity(DirectCast(node.Parent, TupleExpressionSyntax).Arguments, node) Then Return False End If Dim inferredName = node.Expression.TryGetInferredMemberName() If inferredName Is Nothing OrElse Not CaseInsensitiveComparison.Equals(inferredName, node.NameColonEquals.Name.Identifier.ValueText) Then Return False End If Return True End Function Friend Function CanSimplifyNamedFieldInitializer(node As NamedFieldInitializerSyntax) As Boolean Dim parentMemberInitializer As ObjectMemberInitializerSyntax = DirectCast(node.Parent, ObjectMemberInitializerSyntax) ' Spec requires explicit names for object creation expressions (unlike anonymous objects and tuples which can infer them) Dim requiresExplicitNames = parentMemberInitializer.IsParentKind(SyntaxKind.ObjectCreationExpression) If requiresExplicitNames OrElse RemovalCausesAmbiguity(parentMemberInitializer.Initializers, node) Then Return False End If Dim inferredName = node.Expression.TryGetInferredMemberName() If inferredName Is Nothing OrElse Not CaseInsensitiveComparison.Equals(inferredName, node.Name.Identifier.ValueText) Then Return False End If Return True End Function ' An explicit name cannot be removed if some other position would produce it as inferred name Private Function RemovalCausesAmbiguity(arguments As SeparatedSyntaxList(Of SimpleArgumentSyntax), toRemove As SimpleArgumentSyntax) As Boolean Dim name = toRemove.NameColonEquals.Name.Identifier.ValueText For Each argument In arguments If argument Is toRemove Then Continue For End If If argument.NameColonEquals Is Nothing AndAlso CaseInsensitiveComparison.Equals(argument.Expression.TryGetInferredMemberName(), name) Then Return True End If Next Return False End Function ' An explicit name cannot be removed if some other position would produce it as inferred name Private Function RemovalCausesAmbiguity(initializers As SeparatedSyntaxList(Of FieldInitializerSyntax), toRemove As NamedFieldInitializerSyntax) As Boolean Dim name = toRemove.Name.Identifier.ValueText For Each initializer In initializers If initializer Is toRemove Then Continue For End If Dim inferredInitializer = TryCast(initializer, InferredFieldInitializerSyntax) If inferredInitializer IsNot Nothing AndAlso CaseInsensitiveComparison.Equals(inferredInitializer.Expression.TryGetInferredMemberName(), name) Then Return True End If Next Return False End Function End Module End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Simplification Friend Module VisualBasicInferredMemberNameSimplifier Friend Function CanSimplifyTupleName(node As SimpleArgumentSyntax, parseOptions As VisualBasicParseOptions) As Boolean ' Tuple elements are arguments in a tuple expression If node.NameColonEquals Is Nothing OrElse Not node.IsParentKind(SyntaxKind.TupleExpression) Then Return False End If If parseOptions.LanguageVersion < LanguageVersion.VisualBasic15_3 Then Return False End If If RemovalCausesAmbiguity(DirectCast(node.Parent, TupleExpressionSyntax).Arguments, node) Then Return False End If Dim inferredName = node.Expression.TryGetInferredMemberName() If inferredName Is Nothing OrElse Not CaseInsensitiveComparison.Equals(inferredName, node.NameColonEquals.Name.Identifier.ValueText) Then Return False End If Return True End Function Friend Function CanSimplifyNamedFieldInitializer(node As NamedFieldInitializerSyntax) As Boolean Dim parentMemberInitializer As ObjectMemberInitializerSyntax = DirectCast(node.Parent, ObjectMemberInitializerSyntax) ' Spec requires explicit names for object creation expressions (unlike anonymous objects and tuples which can infer them) Dim requiresExplicitNames = parentMemberInitializer.IsParentKind(SyntaxKind.ObjectCreationExpression) If requiresExplicitNames OrElse RemovalCausesAmbiguity(parentMemberInitializer.Initializers, node) Then Return False End If Dim inferredName = node.Expression.TryGetInferredMemberName() If inferredName Is Nothing OrElse Not CaseInsensitiveComparison.Equals(inferredName, node.Name.Identifier.ValueText) Then Return False End If Return True End Function ' An explicit name cannot be removed if some other position would produce it as inferred name Private Function RemovalCausesAmbiguity(arguments As SeparatedSyntaxList(Of SimpleArgumentSyntax), toRemove As SimpleArgumentSyntax) As Boolean Dim name = toRemove.NameColonEquals.Name.Identifier.ValueText For Each argument In arguments If argument Is toRemove Then Continue For End If If argument.NameColonEquals Is Nothing AndAlso CaseInsensitiveComparison.Equals(argument.Expression.TryGetInferredMemberName(), name) Then Return True End If Next Return False End Function ' An explicit name cannot be removed if some other position would produce it as inferred name Private Function RemovalCausesAmbiguity(initializers As SeparatedSyntaxList(Of FieldInitializerSyntax), toRemove As NamedFieldInitializerSyntax) As Boolean Dim name = toRemove.Name.Identifier.ValueText For Each initializer In initializers If initializer Is toRemove Then Continue For End If Dim inferredInitializer = TryCast(initializer, InferredFieldInitializerSyntax) If inferredInitializer IsNot Nothing AndAlso CaseInsensitiveComparison.Equals(inferredInitializer.Expression.TryGetInferredMemberName(), name) Then Return True End If Next Return False End Function End Module End Namespace
-1
dotnet/roslyn
56,011
React to string comparison changing on .NET Core
The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
jaredpar
"2021-08-30T17:18:52Z"
"2021-08-30T20:20:04Z"
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
4d99cda6e446e77dbb302e26388c1093bd3ef569
React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
./src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/DeclarationTests.vb
' 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.CodeGen Imports Microsoft.CodeAnalysis.ExpressionEvaluator Imports Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests Imports Microsoft.VisualStudio.Debugger.Evaluation Imports Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation Imports Roslyn.Test.Utilities Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.UnitTests Public Class DeclarationTests Inherits ExpressionCompilerTestBase <Fact> Public Sub Declarations() Const source = "Class C Private Shared F As Object Shared Sub M(Of T)(x As Object) Dim y As Object If x Is Nothing Then Dim z As Object End If End Sub End Class" Dim comp = CreateCompilationWithMscorlib40({source}, options:=TestOptions.DebugDll, assemblyName:=ExpressionCompilerUtilities.GenerateUniqueName()) WithRuntimeInstance(comp, Sub(runtime) Dim context = CreateMethodContext(runtime, "C.M") Dim resultProperties As ResultProperties = Nothing Dim errorMessage As String = Nothing Dim missingAssemblyIdentities As ImmutableArray(Of AssemblyIdentity) = Nothing Dim testData = New CompilationTestData() context.CompileExpression( "z = $3", DkmEvaluationFlags.None, ImmutableArray.Create(ObjectIdAlias(3, GetType(Integer))), DebuggerDiagnosticFormatter.Instance, resultProperties, errorMessage, missingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData) Assert.Empty(missingAssemblyIdentities) Assert.Null(errorMessage) Assert.Equal(resultProperties.Flags, DkmClrCompilationResultFlags.PotentialSideEffect Or DkmClrCompilationResultFlags.ReadOnlyResult) testData.GetMethodData("<>x.<>m0").VerifyIL( "{ // Code size 62 (0x3e) .maxstack 4 .locals init (Object V_0, //y Boolean V_1, Object V_2, System.Guid V_3) IL_0000: ldtoken ""Object"" IL_0005: call ""Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type"" IL_000a: ldstr ""z"" IL_000f: ldloca.s V_3 IL_0011: initobj ""System.Guid"" IL_0017: ldloc.3 IL_0018: ldnull IL_0019: call ""Sub Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, String, System.Guid, Byte())"" IL_001e: ldstr ""z"" IL_0023: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress(Of Object)(String) As Object"" IL_0028: ldstr ""$3"" IL_002d: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(String) As Object"" IL_0032: unbox.any ""Integer"" IL_0037: box ""Integer"" IL_003c: stind.ref IL_003d: ret }") End Sub) End Sub <Fact> Public Sub References() Const source = "Class C Delegate Sub D() Friend F As Object Private Shared G As Object Shared Sub M(Of T)(x As Object) Dim y As Object End Sub End Class" Dim comp = CreateCompilationWithMscorlib40({source}, options:=TestOptions.DebugDll, assemblyName:=ExpressionCompilerUtilities.GenerateUniqueName()) WithRuntimeInstance(comp, Sub(runtime) Dim context = CreateMethodContext(runtime, "C.M") Dim aliases = ImmutableArray.Create( VariableAlias("x", GetType(String)), VariableAlias("y", GetType(Integer)), VariableAlias("t", GetType(Object)), VariableAlias("d", "C"), VariableAlias("f", GetType(Integer))) Dim errorMessage As String = Nothing Dim testData = New CompilationTestData() context.CompileExpression( "If(If(If(If(If(x, y), T), F), DirectCast(D, C).F), C.G)", DkmEvaluationFlags.TreatAsExpression, aliases, errorMessage, testData) Assert.Equal(testData.Methods.Count, 1) testData.GetMethodData("<>x.<>m0").VerifyIL( "{ // Code size 78 (0x4e) .maxstack 2 .locals init (Object V_0) //y IL_0000: ldarg.0 IL_0001: dup IL_0002: brtrue.s IL_0006 IL_0004: pop IL_0005: ldloc.0 IL_0006: dup IL_0007: brtrue.s IL_0014 IL_0009: pop IL_000a: ldstr ""t"" IL_000f: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(String) As Object"" IL_0014: dup IL_0015: brtrue.s IL_002c IL_0017: pop IL_0018: ldstr ""f"" IL_001d: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(String) As Object"" IL_0022: unbox.any ""Integer"" IL_0027: box ""Integer"" IL_002c: dup IL_002d: brtrue.s IL_0044 IL_002f: pop IL_0030: ldstr ""d"" IL_0035: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(String) As Object"" IL_003a: castclass ""C"" IL_003f: ldfld ""C.F As Object"" IL_0044: dup IL_0045: brtrue.s IL_004d IL_0047: pop IL_0048: ldsfld ""C.G As Object"" IL_004d: ret } ") End Sub) End Sub <Fact> Public Sub BindingError_Initializer() Const source = "Class C Shared Sub M() End Sub End Class" Dim comp = CreateCompilationWithMscorlib40({source}, options:=TestOptions.DebugDll, assemblyName:=ExpressionCompilerUtilities.GenerateUniqueName()) WithRuntimeInstance(comp, Sub(runtime) Dim context = CreateMethodContext(runtime, "C.M") Dim errorMessage As String = Nothing Dim testData = New CompilationTestData() context.CompileExpression( "x = F()", DkmEvaluationFlags.None, NoAliases, errorMessage, testData) Assert.Equal(errorMessage, "error BC30451: 'F' is not declared. It may be inaccessible due to its protection level.") End Sub) End Sub <WorkItem(1098750, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1098750")> <Fact> Public Sub ReferenceInSameDeclaration() Const source = "Module M Function F(s As String) As String Return s End Function Sub M(o As Object) End Sub End Module" Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(MakeSources(source, assemblyName:=ExpressionCompilerUtilities.GenerateUniqueName()), options:=TestOptions.DebugDll) WithRuntimeInstance(comp, Sub(runtime) Dim context = CreateMethodContext(runtime, "M.M") Dim errorMessage As String = Nothing Dim testData = New CompilationTestData() context.CompileExpression( "s = F(s)", DkmEvaluationFlags.None, NoAliases, errorMessage, testData) testData.GetMethodData("<>x.<>m0").VerifyIL( "{ // Code size 62 (0x3e) .maxstack 4 .locals init (System.Guid V_0) IL_0000: ldtoken ""Object"" IL_0005: call ""Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type"" IL_000a: ldstr ""s"" IL_000f: ldloca.s V_0 IL_0011: initobj ""System.Guid"" IL_0017: ldloc.0 IL_0018: ldnull IL_0019: call ""Sub Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, String, System.Guid, Byte())"" IL_001e: ldstr ""s"" IL_0023: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress(Of Object)(String) As Object"" IL_0028: ldstr ""s"" IL_002d: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(String) As Object"" IL_0032: call ""Function Microsoft.VisualBasic.CompilerServices.Conversions.ToString(Object) As String"" IL_0037: call ""Function M.F(String) As String"" IL_003c: stind.ref IL_003d: ret }") testData = New CompilationTestData() context.CompileExpression( "M(If(t, t))", DkmEvaluationFlags.None, NoAliases, errorMessage, testData) testData.GetMethodData("<>x.<>m0").VerifyIL( "{ // Code size 65 (0x41) .maxstack 4 .locals init (System.Guid V_0) IL_0000: ldtoken ""Object"" IL_0005: call ""Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type"" IL_000a: ldstr ""t"" IL_000f: ldloca.s V_0 IL_0011: initobj ""System.Guid"" IL_0017: ldloc.0 IL_0018: ldnull IL_0019: call ""Sub Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, String, System.Guid, Byte())"" IL_001e: ldstr ""t"" IL_0023: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(String) As Object"" IL_0028: dup IL_0029: brtrue.s IL_0036 IL_002b: pop IL_002c: ldstr ""t"" IL_0031: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(String) As Object"" IL_0036: call ""Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"" IL_003b: call ""Sub M.M(Object)"" IL_0040: ret }") End Sub) End Sub <WorkItem(1100849, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1100849")> <Fact> Public Sub PassByRef() Const source = "Module M Function F(Of T)(ByRef t1 As T) As T t1 = Nothing Return t1 End Function Sub M() End Sub End Module" Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(MakeSources(source, assemblyName:=ExpressionCompilerUtilities.GenerateUniqueName()), options:=TestOptions.DebugDll) WithRuntimeInstance(comp, Sub(runtime) Dim context = CreateMethodContext(runtime, "M.M") Dim errorMessage As String = Nothing Dim testData = New CompilationTestData() context.CompileExpression( "F(o)", DkmEvaluationFlags.None, NoAliases, errorMessage, testData) testData.GetMethodData("<>x.<>m0").VerifyIL( "{ // Code size 47 (0x2f) .maxstack 4 .locals init (System.Guid V_0) IL_0000: ldtoken ""Object"" IL_0005: call ""Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type"" IL_000a: ldstr ""o"" IL_000f: ldloca.s V_0 IL_0011: initobj ""System.Guid"" IL_0017: ldloc.0 IL_0018: ldnull IL_0019: call ""Sub Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, String, System.Guid, Byte())"" IL_001e: ldstr ""o"" IL_0023: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress(Of Object)(String) As Object"" IL_0028: call ""Function M.F(Of Object)(ByRef Object) As Object"" IL_002d: pop IL_002e: ret }") End Sub) End Sub <Fact> Public Sub Keyword() Const source = "Class C Shared Sub M() End Sub End Class" Dim comp = CreateCompilationWithMscorlib40({source}, options:=TestOptions.DebugDll, assemblyName:=ExpressionCompilerUtilities.GenerateUniqueName()) WithRuntimeInstance(comp, Sub(runtime) Dim context = CreateMethodContext(runtime, "C.M") Dim errorMessage As String = Nothing Dim testData = New CompilationTestData() context.CompileExpression( "[Me] = [Class]", DkmEvaluationFlags.None, ImmutableArray.Create(VariableAlias("class")), errorMessage, testData) testData.GetMethodData("<>x.<>m0").VerifyIL( "{ // Code size 57 (0x39) .maxstack 4 .locals init (System.Guid V_0) IL_0000: ldtoken ""Object"" IL_0005: call ""Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type"" IL_000a: ldstr ""Me"" IL_000f: ldloca.s V_0 IL_0011: initobj ""System.Guid"" IL_0017: ldloc.0 IL_0018: ldnull IL_0019: call ""Sub Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, String, System.Guid, Byte())"" IL_001e: ldstr ""Me"" IL_0023: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress(Of Object)(String) As Object"" IL_0028: ldstr ""class"" IL_002d: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(String) As Object"" IL_0032: call ""Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"" IL_0037: stind.ref IL_0038: ret }") End Sub) End Sub <Fact> Public Sub Generic() Const source = "Class C Shared Sub M(Of T)(x As T) End Sub End Class" Dim comp = CreateCompilationWithMscorlib40({source}, options:=TestOptions.DebugDll, assemblyName:=ExpressionCompilerUtilities.GenerateUniqueName()) WithRuntimeInstance(comp, Sub(runtime) Dim context = CreateMethodContext(runtime, "C.M") Dim errorMessage As String = Nothing Dim testData = New CompilationTestData() context.CompileExpression( "y = x", DkmEvaluationFlags.None, NoAliases, errorMessage, testData) testData.GetMethodData("<>x.<>m0").VerifyIL( "{ // Code size 48 (0x30) .maxstack 4 .locals init (System.Guid V_0) IL_0000: ldtoken ""Object"" IL_0005: call ""Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type"" IL_000a: ldstr ""y"" IL_000f: ldloca.s V_0 IL_0011: initobj ""System.Guid"" IL_0017: ldloc.0 IL_0018: ldnull IL_0019: call ""Sub Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, String, System.Guid, Byte())"" IL_001e: ldstr ""y"" IL_0023: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress(Of Object)(String) As Object"" IL_0028: ldarg.0 IL_0029: box ""T"" IL_002e: stind.ref IL_002f: ret }") End Sub) End Sub <WorkItem(1101237, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1101237")> <Fact> Public Sub TypeChar() Const source = "Module M Sub M() End Sub End Module" Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(MakeSources(source, assemblyName:=ExpressionCompilerUtilities.GenerateUniqueName()), options:=TestOptions.DebugDll) WithRuntimeInstance(comp, Sub(runtime) Dim context = CreateMethodContext(runtime, "M.M") Dim errorMessage As String = Nothing Dim testData As CompilationTestData ' Object testData = New CompilationTestData() context.CompileExpression( "x = 3", DkmEvaluationFlags.None, NoAliases, errorMessage, testData) testData.GetMethodData("<>x.<>m0").VerifyIL( "{ // Code size 48 (0x30) .maxstack 4 .locals init (System.Guid V_0) IL_0000: ldtoken ""Object"" IL_0005: call ""Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type"" IL_000a: ldstr ""x"" IL_000f: ldloca.s V_0 IL_0011: initobj ""System.Guid"" IL_0017: ldloc.0 IL_0018: ldnull IL_0019: call ""Sub Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, String, System.Guid, Byte())"" IL_001e: ldstr ""x"" IL_0023: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress(Of Object)(String) As Object"" IL_0028: ldc.i4.3 IL_0029: box ""Integer"" IL_002e: stind.ref IL_002f: ret }") ' Integer testData = New CompilationTestData() context.CompileExpression( "x% = 3", DkmEvaluationFlags.None, NoAliases, errorMessage, testData) testData.GetMethodData("<>x.<>m0").VerifyIL( "{ // Code size 43 (0x2b) .maxstack 4 .locals init (System.Guid V_0) IL_0000: ldtoken ""Integer"" IL_0005: call ""Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type"" IL_000a: ldstr ""x"" IL_000f: ldloca.s V_0 IL_0011: initobj ""System.Guid"" IL_0017: ldloc.0 IL_0018: ldnull IL_0019: call ""Sub Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, String, System.Guid, Byte())"" IL_001e: ldstr ""x"" IL_0023: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress(Of Integer)(String) As Integer"" IL_0028: ldc.i4.3 IL_0029: stind.i4 IL_002a: ret }") ' Long testData = New CompilationTestData() context.CompileExpression( "x& = 3", DkmEvaluationFlags.None, NoAliases, errorMessage, testData) testData.GetMethodData("<>x.<>m0").VerifyIL( "{ // Code size 44 (0x2c) .maxstack 4 .locals init (System.Guid V_0) IL_0000: ldtoken ""Long"" IL_0005: call ""Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type"" IL_000a: ldstr ""x"" IL_000f: ldloca.s V_0 IL_0011: initobj ""System.Guid"" IL_0017: ldloc.0 IL_0018: ldnull IL_0019: call ""Sub Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, String, System.Guid, Byte())"" IL_001e: ldstr ""x"" IL_0023: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress(Of Long)(String) As Long"" IL_0028: ldc.i4.3 IL_0029: conv.i8 IL_002a: stind.i8 IL_002b: ret }") ' Single testData = New CompilationTestData() context.CompileExpression( "x! = 3", DkmEvaluationFlags.None, NoAliases, errorMessage, testData) testData.GetMethodData("<>x.<>m0").VerifyIL( "{ // Code size 47 (0x2f) .maxstack 4 .locals init (System.Guid V_0) IL_0000: ldtoken ""Single"" IL_0005: call ""Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type"" IL_000a: ldstr ""x"" IL_000f: ldloca.s V_0 IL_0011: initobj ""System.Guid"" IL_0017: ldloc.0 IL_0018: ldnull IL_0019: call ""Sub Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, String, System.Guid, Byte())"" IL_001e: ldstr ""x"" IL_0023: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress(Of Single)(String) As Single"" IL_0028: ldc.r4 3 IL_002d: stind.r4 IL_002e: ret }") ' Double testData = New CompilationTestData() context.CompileExpression( "x# = 3", DkmEvaluationFlags.None, NoAliases, errorMessage, testData) testData.GetMethodData("<>x.<>m0").VerifyIL( "{ // Code size 51 (0x33) .maxstack 4 .locals init (System.Guid V_0) IL_0000: ldtoken ""Double"" IL_0005: call ""Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type"" IL_000a: ldstr ""x"" IL_000f: ldloca.s V_0 IL_0011: initobj ""System.Guid"" IL_0017: ldloc.0 IL_0018: ldnull IL_0019: call ""Sub Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, String, System.Guid, Byte())"" IL_001e: ldstr ""x"" IL_0023: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress(Of Double)(String) As Double"" IL_0028: ldc.r8 3 IL_0031: stind.r8 IL_0032: ret }") ' String testData = New CompilationTestData() context.CompileExpression( "x$ = 3", DkmEvaluationFlags.None, NoAliases, errorMessage, testData) testData.GetMethodData("<>x.<>m0").VerifyIL( "{ // Code size 48 (0x30) .maxstack 4 .locals init (System.Guid V_0) IL_0000: ldtoken ""String"" IL_0005: call ""Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type"" IL_000a: ldstr ""x"" IL_000f: ldloca.s V_0 IL_0011: initobj ""System.Guid"" IL_0017: ldloc.0 IL_0018: ldnull IL_0019: call ""Sub Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, String, System.Guid, Byte())"" IL_001e: ldstr ""x"" IL_0023: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress(Of String)(String) As String"" IL_0028: ldc.i4.3 IL_0029: call ""Function Microsoft.VisualBasic.CompilerServices.Conversions.ToString(Integer) As String"" IL_002e: stind.ref IL_002f: ret }") ' Decimal testData = New CompilationTestData() context.CompileExpression( "x@ = 3", DkmEvaluationFlags.None, NoAliases, errorMessage, testData) testData.GetMethodData("<>x.<>m0").VerifyIL( "{ // Code size 53 (0x35) .maxstack 4 .locals init (System.Guid V_0) IL_0000: ldtoken ""Decimal"" IL_0005: call ""Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type"" IL_000a: ldstr ""x"" IL_000f: ldloca.s V_0 IL_0011: initobj ""System.Guid"" IL_0017: ldloc.0 IL_0018: ldnull IL_0019: call ""Sub Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, String, System.Guid, Byte())"" IL_001e: ldstr ""x"" IL_0023: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress(Of Decimal)(String) As Decimal"" IL_0028: ldc.i4.3 IL_0029: conv.i8 IL_002a: newobj ""Sub Decimal..ctor(Long)"" IL_002f: stobj ""Decimal"" IL_0034: ret }") End Sub) End Sub ''' <summary> ''' Should not allow names with '$' prefix. ''' </summary> <WorkItem(1106819, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1106819")> <Fact> Public Sub NoPrefix() Const source = "Module M Sub M() End Sub End Module" Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(MakeSources(source, assemblyName:=ExpressionCompilerUtilities.GenerateUniqueName()), options:=TestOptions.DebugDll) WithRuntimeInstance(comp, Sub(runtime) Dim context = CreateMethodContext(runtime, "M.M") Dim errorMessage As String = Nothing ' $1 Dim testData = New CompilationTestData() Dim result = context.CompileExpression( "$1 = 1", DkmEvaluationFlags.None, NoAliases, errorMessage, testData) Assert.Equal(errorMessage, "error BC30037: Character is not valid.") ' $exception testData = New CompilationTestData() result = context.CompileExpression( "$1 = 2", DkmEvaluationFlags.None, NoAliases, errorMessage, testData) Assert.Equal(errorMessage, "error BC30037: Character is not valid.") ' $ReturnValue testData = New CompilationTestData() result = context.CompileExpression( "$ReturnValue = 3", DkmEvaluationFlags.None, NoAliases, errorMessage, testData) Assert.Equal(errorMessage, "error BC30037: Character is not valid.") ' $x testData = New CompilationTestData() result = context.CompileExpression( "$x = 4", DkmEvaluationFlags.None, NoAliases, errorMessage, testData) Assert.Equal(errorMessage, "error BC30037: Character is not valid.") End Sub) End Sub <WorkItem(1101243, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1101243")> <Fact> Public Sub [ReDim]() Const source = "Module M Sub M() End Sub End Module" Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(MakeSources(source, assemblyName:=ExpressionCompilerUtilities.GenerateUniqueName()), options:=TestOptions.DebugDll) WithRuntimeInstance(comp, Sub(runtime) Dim context = CreateMethodContext(runtime, "M.M") Dim errorMessage As String = Nothing Dim testData = New CompilationTestData() context.CompileExpression( "ReDim a(3)", DkmEvaluationFlags.None, NoAliases, errorMessage, testData) testData.GetMethodData("<>x.<>m0").VerifyIL( "{ // Code size 48 (0x30) .maxstack 4 .locals init (System.Guid V_0) IL_0000: ldtoken ""Object"" IL_0005: call ""Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type"" IL_000a: ldstr ""a"" IL_000f: ldloca.s V_0 IL_0011: initobj ""System.Guid"" IL_0017: ldloc.0 IL_0018: ldnull IL_0019: call ""Sub Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, String, System.Guid, Byte())"" IL_001e: ldstr ""a"" IL_0023: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress(Of Object)(String) As Object"" IL_0028: ldc.i4.4 IL_0029: newarr ""Object"" IL_002e: stind.ref IL_002f: ret }") testData = New CompilationTestData() context.CompileExpression( "ReDim Preserve a(3)", DkmEvaluationFlags.None, NoAliases, errorMessage, testData) testData.GetMethodData("<>x.<>m0").VerifyIL( "{ // Code size 68 (0x44) .maxstack 4 .locals init (System.Guid V_0) IL_0000: ldtoken ""Object"" IL_0005: call ""Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type"" IL_000a: ldstr ""a"" IL_000f: ldloca.s V_0 IL_0011: initobj ""System.Guid"" IL_0017: ldloc.0 IL_0018: ldnull IL_0019: call ""Sub Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, String, System.Guid, Byte())"" IL_001e: ldstr ""a"" IL_0023: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress(Of Object)(String) As Object"" IL_0028: ldstr ""a"" IL_002d: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(String) As Object"" IL_0032: castclass ""System.Array"" IL_0037: ldc.i4.4 IL_0038: newarr ""Object"" IL_003d: call ""Function Microsoft.VisualBasic.CompilerServices.Utils.CopyArray(System.Array, System.Array) As System.Array"" IL_0042: stind.ref IL_0043: ret }") End Sub) End Sub <WorkItem(1101318, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1101318")> <Fact> Public Sub CompoundAssignment() Const source = "Module M Sub M() End Sub End Module" Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(MakeSources(source, assemblyName:=ExpressionCompilerUtilities.GenerateUniqueName()), options:=TestOptions.DebugDll) WithRuntimeInstance(comp, Sub(runtime) Dim context = CreateMethodContext(runtime, "M.M") Dim errorMessage As String = Nothing Dim testData = New CompilationTestData() context.CompileExpression( "x += 1", DkmEvaluationFlags.None, NoAliases, errorMessage, testData) testData.GetMethodData("<>x.<>m0").VerifyIL( "{ // Code size 63 (0x3f) .maxstack 4 .locals init (System.Guid V_0) IL_0000: ldtoken ""Object"" IL_0005: call ""Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type"" IL_000a: ldstr ""x"" IL_000f: ldloca.s V_0 IL_0011: initobj ""System.Guid"" IL_0017: ldloc.0 IL_0018: ldnull IL_0019: call ""Sub Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, String, System.Guid, Byte())"" IL_001e: ldstr ""x"" IL_0023: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress(Of Object)(String) As Object"" IL_0028: ldstr ""x"" IL_002d: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(String) As Object"" IL_0032: ldc.i4.1 IL_0033: box ""Integer"" IL_0038: call ""Function Microsoft.VisualBasic.CompilerServices.Operators.AddObject(Object, Object) As Object"" IL_003d: stind.ref IL_003e: ret }") End Sub) End Sub <WorkItem(1115044, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1115044")> <Fact> Public Sub CaseSensitivity() Const source = "Class C Shared Sub M() End Sub End Class" Dim comp = CreateCompilationWithMscorlib40({source}, options:=TestOptions.DebugDll, assemblyName:=ExpressionCompilerUtilities.GenerateUniqueName()) WithRuntimeInstance(comp, Sub(runtime) Dim context = CreateMethodContext(runtime, "C.M") Dim errorMessage As String = Nothing Dim testData = New CompilationTestData() Dim result = context.CompileExpression( "X", DkmEvaluationFlags.TreatAsExpression, ImmutableArray.Create(VariableAlias("x", GetType(String))), errorMessage, testData) Assert.Null(errorMessage) testData.GetMethodData("<>x.<>m0").VerifyIL( "{ // Code size 16 (0x10) .maxstack 1 IL_0000: ldstr ""x"" IL_0005: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(String) As Object"" IL_000a: castclass ""String"" IL_000f: ret } ") End Sub) End Sub <WorkItem(1115044, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1115044")> <Fact> Public Sub CaseSensitivity_ImplicitDeclaration() Const source = "Class C Shared Sub M() End Sub End Class" Dim comp = CreateCompilationWithMscorlib40({source}, options:=TestOptions.DebugDll, assemblyName:=ExpressionCompilerUtilities.GenerateUniqueName()) WithRuntimeInstance(comp, Sub(runtime) Dim context = CreateMethodContext(runtime, "C.M") Dim errorMessage As String = Nothing Dim testData = New CompilationTestData() Dim result = context.CompileExpression( "x = X", DkmEvaluationFlags.None, NoAliases, errorMessage, testData) Assert.Null(errorMessage) ' Use before initialization is allowed in the EE. ' Note that all x's are lowercase (i.e. normalized). testData.GetMethodData("<>x.<>m0").VerifyIL( "{ // Code size 57 (0x39) .maxstack 4 .locals init (System.Guid V_0) IL_0000: ldtoken ""Object"" IL_0005: call ""Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type"" IL_000a: ldstr ""x"" IL_000f: ldloca.s V_0 IL_0011: initobj ""System.Guid"" IL_0017: ldloc.0 IL_0018: ldnull IL_0019: call ""Sub Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, String, System.Guid, Byte())"" IL_001e: ldstr ""x"" IL_0023: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress(Of Object)(String) As Object"" IL_0028: ldstr ""x"" IL_002d: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(String) As Object"" IL_0032: call ""Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"" IL_0037: stind.ref IL_0038: ret } ") End Sub) End Sub End Class End Namespace
' 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.CodeGen Imports Microsoft.CodeAnalysis.ExpressionEvaluator Imports Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests Imports Microsoft.VisualStudio.Debugger.Evaluation Imports Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation Imports Roslyn.Test.Utilities Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.UnitTests Public Class DeclarationTests Inherits ExpressionCompilerTestBase <Fact> Public Sub Declarations() Const source = "Class C Private Shared F As Object Shared Sub M(Of T)(x As Object) Dim y As Object If x Is Nothing Then Dim z As Object End If End Sub End Class" Dim comp = CreateCompilationWithMscorlib40({source}, options:=TestOptions.DebugDll, assemblyName:=ExpressionCompilerUtilities.GenerateUniqueName()) WithRuntimeInstance(comp, Sub(runtime) Dim context = CreateMethodContext(runtime, "C.M") Dim resultProperties As ResultProperties = Nothing Dim errorMessage As String = Nothing Dim missingAssemblyIdentities As ImmutableArray(Of AssemblyIdentity) = Nothing Dim testData = New CompilationTestData() context.CompileExpression( "z = $3", DkmEvaluationFlags.None, ImmutableArray.Create(ObjectIdAlias(3, GetType(Integer))), DebuggerDiagnosticFormatter.Instance, resultProperties, errorMessage, missingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData) Assert.Empty(missingAssemblyIdentities) Assert.Null(errorMessage) Assert.Equal(resultProperties.Flags, DkmClrCompilationResultFlags.PotentialSideEffect Or DkmClrCompilationResultFlags.ReadOnlyResult) testData.GetMethodData("<>x.<>m0").VerifyIL( "{ // Code size 62 (0x3e) .maxstack 4 .locals init (Object V_0, //y Boolean V_1, Object V_2, System.Guid V_3) IL_0000: ldtoken ""Object"" IL_0005: call ""Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type"" IL_000a: ldstr ""z"" IL_000f: ldloca.s V_3 IL_0011: initobj ""System.Guid"" IL_0017: ldloc.3 IL_0018: ldnull IL_0019: call ""Sub Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, String, System.Guid, Byte())"" IL_001e: ldstr ""z"" IL_0023: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress(Of Object)(String) As Object"" IL_0028: ldstr ""$3"" IL_002d: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(String) As Object"" IL_0032: unbox.any ""Integer"" IL_0037: box ""Integer"" IL_003c: stind.ref IL_003d: ret }") End Sub) End Sub <Fact> Public Sub References() Const source = "Class C Delegate Sub D() Friend F As Object Private Shared G As Object Shared Sub M(Of T)(x As Object) Dim y As Object End Sub End Class" Dim comp = CreateCompilationWithMscorlib40({source}, options:=TestOptions.DebugDll, assemblyName:=ExpressionCompilerUtilities.GenerateUniqueName()) WithRuntimeInstance(comp, Sub(runtime) Dim context = CreateMethodContext(runtime, "C.M") Dim aliases = ImmutableArray.Create( VariableAlias("x", GetType(String)), VariableAlias("y", GetType(Integer)), VariableAlias("t", GetType(Object)), VariableAlias("d", "C"), VariableAlias("f", GetType(Integer))) Dim errorMessage As String = Nothing Dim testData = New CompilationTestData() context.CompileExpression( "If(If(If(If(If(x, y), T), F), DirectCast(D, C).F), C.G)", DkmEvaluationFlags.TreatAsExpression, aliases, errorMessage, testData) Assert.Equal(testData.Methods.Count, 1) testData.GetMethodData("<>x.<>m0").VerifyIL( "{ // Code size 78 (0x4e) .maxstack 2 .locals init (Object V_0) //y IL_0000: ldarg.0 IL_0001: dup IL_0002: brtrue.s IL_0006 IL_0004: pop IL_0005: ldloc.0 IL_0006: dup IL_0007: brtrue.s IL_0014 IL_0009: pop IL_000a: ldstr ""t"" IL_000f: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(String) As Object"" IL_0014: dup IL_0015: brtrue.s IL_002c IL_0017: pop IL_0018: ldstr ""f"" IL_001d: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(String) As Object"" IL_0022: unbox.any ""Integer"" IL_0027: box ""Integer"" IL_002c: dup IL_002d: brtrue.s IL_0044 IL_002f: pop IL_0030: ldstr ""d"" IL_0035: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(String) As Object"" IL_003a: castclass ""C"" IL_003f: ldfld ""C.F As Object"" IL_0044: dup IL_0045: brtrue.s IL_004d IL_0047: pop IL_0048: ldsfld ""C.G As Object"" IL_004d: ret } ") End Sub) End Sub <Fact> Public Sub BindingError_Initializer() Const source = "Class C Shared Sub M() End Sub End Class" Dim comp = CreateCompilationWithMscorlib40({source}, options:=TestOptions.DebugDll, assemblyName:=ExpressionCompilerUtilities.GenerateUniqueName()) WithRuntimeInstance(comp, Sub(runtime) Dim context = CreateMethodContext(runtime, "C.M") Dim errorMessage As String = Nothing Dim testData = New CompilationTestData() context.CompileExpression( "x = F()", DkmEvaluationFlags.None, NoAliases, errorMessage, testData) Assert.Equal(errorMessage, "error BC30451: 'F' is not declared. It may be inaccessible due to its protection level.") End Sub) End Sub <WorkItem(1098750, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1098750")> <Fact> Public Sub ReferenceInSameDeclaration() Const source = "Module M Function F(s As String) As String Return s End Function Sub M(o As Object) End Sub End Module" Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(MakeSources(source, assemblyName:=ExpressionCompilerUtilities.GenerateUniqueName()), options:=TestOptions.DebugDll) WithRuntimeInstance(comp, Sub(runtime) Dim context = CreateMethodContext(runtime, "M.M") Dim errorMessage As String = Nothing Dim testData = New CompilationTestData() context.CompileExpression( "s = F(s)", DkmEvaluationFlags.None, NoAliases, errorMessage, testData) testData.GetMethodData("<>x.<>m0").VerifyIL( "{ // Code size 62 (0x3e) .maxstack 4 .locals init (System.Guid V_0) IL_0000: ldtoken ""Object"" IL_0005: call ""Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type"" IL_000a: ldstr ""s"" IL_000f: ldloca.s V_0 IL_0011: initobj ""System.Guid"" IL_0017: ldloc.0 IL_0018: ldnull IL_0019: call ""Sub Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, String, System.Guid, Byte())"" IL_001e: ldstr ""s"" IL_0023: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress(Of Object)(String) As Object"" IL_0028: ldstr ""s"" IL_002d: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(String) As Object"" IL_0032: call ""Function Microsoft.VisualBasic.CompilerServices.Conversions.ToString(Object) As String"" IL_0037: call ""Function M.F(String) As String"" IL_003c: stind.ref IL_003d: ret }") testData = New CompilationTestData() context.CompileExpression( "M(If(t, t))", DkmEvaluationFlags.None, NoAliases, errorMessage, testData) testData.GetMethodData("<>x.<>m0").VerifyIL( "{ // Code size 65 (0x41) .maxstack 4 .locals init (System.Guid V_0) IL_0000: ldtoken ""Object"" IL_0005: call ""Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type"" IL_000a: ldstr ""t"" IL_000f: ldloca.s V_0 IL_0011: initobj ""System.Guid"" IL_0017: ldloc.0 IL_0018: ldnull IL_0019: call ""Sub Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, String, System.Guid, Byte())"" IL_001e: ldstr ""t"" IL_0023: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(String) As Object"" IL_0028: dup IL_0029: brtrue.s IL_0036 IL_002b: pop IL_002c: ldstr ""t"" IL_0031: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(String) As Object"" IL_0036: call ""Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"" IL_003b: call ""Sub M.M(Object)"" IL_0040: ret }") End Sub) End Sub <WorkItem(1100849, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1100849")> <Fact> Public Sub PassByRef() Const source = "Module M Function F(Of T)(ByRef t1 As T) As T t1 = Nothing Return t1 End Function Sub M() End Sub End Module" Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(MakeSources(source, assemblyName:=ExpressionCompilerUtilities.GenerateUniqueName()), options:=TestOptions.DebugDll) WithRuntimeInstance(comp, Sub(runtime) Dim context = CreateMethodContext(runtime, "M.M") Dim errorMessage As String = Nothing Dim testData = New CompilationTestData() context.CompileExpression( "F(o)", DkmEvaluationFlags.None, NoAliases, errorMessage, testData) testData.GetMethodData("<>x.<>m0").VerifyIL( "{ // Code size 47 (0x2f) .maxstack 4 .locals init (System.Guid V_0) IL_0000: ldtoken ""Object"" IL_0005: call ""Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type"" IL_000a: ldstr ""o"" IL_000f: ldloca.s V_0 IL_0011: initobj ""System.Guid"" IL_0017: ldloc.0 IL_0018: ldnull IL_0019: call ""Sub Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, String, System.Guid, Byte())"" IL_001e: ldstr ""o"" IL_0023: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress(Of Object)(String) As Object"" IL_0028: call ""Function M.F(Of Object)(ByRef Object) As Object"" IL_002d: pop IL_002e: ret }") End Sub) End Sub <Fact> Public Sub Keyword() Const source = "Class C Shared Sub M() End Sub End Class" Dim comp = CreateCompilationWithMscorlib40({source}, options:=TestOptions.DebugDll, assemblyName:=ExpressionCompilerUtilities.GenerateUniqueName()) WithRuntimeInstance(comp, Sub(runtime) Dim context = CreateMethodContext(runtime, "C.M") Dim errorMessage As String = Nothing Dim testData = New CompilationTestData() context.CompileExpression( "[Me] = [Class]", DkmEvaluationFlags.None, ImmutableArray.Create(VariableAlias("class")), errorMessage, testData) testData.GetMethodData("<>x.<>m0").VerifyIL( "{ // Code size 57 (0x39) .maxstack 4 .locals init (System.Guid V_0) IL_0000: ldtoken ""Object"" IL_0005: call ""Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type"" IL_000a: ldstr ""Me"" IL_000f: ldloca.s V_0 IL_0011: initobj ""System.Guid"" IL_0017: ldloc.0 IL_0018: ldnull IL_0019: call ""Sub Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, String, System.Guid, Byte())"" IL_001e: ldstr ""Me"" IL_0023: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress(Of Object)(String) As Object"" IL_0028: ldstr ""class"" IL_002d: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(String) As Object"" IL_0032: call ""Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"" IL_0037: stind.ref IL_0038: ret }") End Sub) End Sub <Fact> Public Sub Generic() Const source = "Class C Shared Sub M(Of T)(x As T) End Sub End Class" Dim comp = CreateCompilationWithMscorlib40({source}, options:=TestOptions.DebugDll, assemblyName:=ExpressionCompilerUtilities.GenerateUniqueName()) WithRuntimeInstance(comp, Sub(runtime) Dim context = CreateMethodContext(runtime, "C.M") Dim errorMessage As String = Nothing Dim testData = New CompilationTestData() context.CompileExpression( "y = x", DkmEvaluationFlags.None, NoAliases, errorMessage, testData) testData.GetMethodData("<>x.<>m0").VerifyIL( "{ // Code size 48 (0x30) .maxstack 4 .locals init (System.Guid V_0) IL_0000: ldtoken ""Object"" IL_0005: call ""Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type"" IL_000a: ldstr ""y"" IL_000f: ldloca.s V_0 IL_0011: initobj ""System.Guid"" IL_0017: ldloc.0 IL_0018: ldnull IL_0019: call ""Sub Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, String, System.Guid, Byte())"" IL_001e: ldstr ""y"" IL_0023: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress(Of Object)(String) As Object"" IL_0028: ldarg.0 IL_0029: box ""T"" IL_002e: stind.ref IL_002f: ret }") End Sub) End Sub <WorkItem(1101237, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1101237")> <Fact> Public Sub TypeChar() Const source = "Module M Sub M() End Sub End Module" Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(MakeSources(source, assemblyName:=ExpressionCompilerUtilities.GenerateUniqueName()), options:=TestOptions.DebugDll) WithRuntimeInstance(comp, Sub(runtime) Dim context = CreateMethodContext(runtime, "M.M") Dim errorMessage As String = Nothing Dim testData As CompilationTestData ' Object testData = New CompilationTestData() context.CompileExpression( "x = 3", DkmEvaluationFlags.None, NoAliases, errorMessage, testData) testData.GetMethodData("<>x.<>m0").VerifyIL( "{ // Code size 48 (0x30) .maxstack 4 .locals init (System.Guid V_0) IL_0000: ldtoken ""Object"" IL_0005: call ""Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type"" IL_000a: ldstr ""x"" IL_000f: ldloca.s V_0 IL_0011: initobj ""System.Guid"" IL_0017: ldloc.0 IL_0018: ldnull IL_0019: call ""Sub Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, String, System.Guid, Byte())"" IL_001e: ldstr ""x"" IL_0023: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress(Of Object)(String) As Object"" IL_0028: ldc.i4.3 IL_0029: box ""Integer"" IL_002e: stind.ref IL_002f: ret }") ' Integer testData = New CompilationTestData() context.CompileExpression( "x% = 3", DkmEvaluationFlags.None, NoAliases, errorMessage, testData) testData.GetMethodData("<>x.<>m0").VerifyIL( "{ // Code size 43 (0x2b) .maxstack 4 .locals init (System.Guid V_0) IL_0000: ldtoken ""Integer"" IL_0005: call ""Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type"" IL_000a: ldstr ""x"" IL_000f: ldloca.s V_0 IL_0011: initobj ""System.Guid"" IL_0017: ldloc.0 IL_0018: ldnull IL_0019: call ""Sub Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, String, System.Guid, Byte())"" IL_001e: ldstr ""x"" IL_0023: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress(Of Integer)(String) As Integer"" IL_0028: ldc.i4.3 IL_0029: stind.i4 IL_002a: ret }") ' Long testData = New CompilationTestData() context.CompileExpression( "x& = 3", DkmEvaluationFlags.None, NoAliases, errorMessage, testData) testData.GetMethodData("<>x.<>m0").VerifyIL( "{ // Code size 44 (0x2c) .maxstack 4 .locals init (System.Guid V_0) IL_0000: ldtoken ""Long"" IL_0005: call ""Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type"" IL_000a: ldstr ""x"" IL_000f: ldloca.s V_0 IL_0011: initobj ""System.Guid"" IL_0017: ldloc.0 IL_0018: ldnull IL_0019: call ""Sub Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, String, System.Guid, Byte())"" IL_001e: ldstr ""x"" IL_0023: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress(Of Long)(String) As Long"" IL_0028: ldc.i4.3 IL_0029: conv.i8 IL_002a: stind.i8 IL_002b: ret }") ' Single testData = New CompilationTestData() context.CompileExpression( "x! = 3", DkmEvaluationFlags.None, NoAliases, errorMessage, testData) testData.GetMethodData("<>x.<>m0").VerifyIL( "{ // Code size 47 (0x2f) .maxstack 4 .locals init (System.Guid V_0) IL_0000: ldtoken ""Single"" IL_0005: call ""Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type"" IL_000a: ldstr ""x"" IL_000f: ldloca.s V_0 IL_0011: initobj ""System.Guid"" IL_0017: ldloc.0 IL_0018: ldnull IL_0019: call ""Sub Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, String, System.Guid, Byte())"" IL_001e: ldstr ""x"" IL_0023: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress(Of Single)(String) As Single"" IL_0028: ldc.r4 3 IL_002d: stind.r4 IL_002e: ret }") ' Double testData = New CompilationTestData() context.CompileExpression( "x# = 3", DkmEvaluationFlags.None, NoAliases, errorMessage, testData) testData.GetMethodData("<>x.<>m0").VerifyIL( "{ // Code size 51 (0x33) .maxstack 4 .locals init (System.Guid V_0) IL_0000: ldtoken ""Double"" IL_0005: call ""Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type"" IL_000a: ldstr ""x"" IL_000f: ldloca.s V_0 IL_0011: initobj ""System.Guid"" IL_0017: ldloc.0 IL_0018: ldnull IL_0019: call ""Sub Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, String, System.Guid, Byte())"" IL_001e: ldstr ""x"" IL_0023: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress(Of Double)(String) As Double"" IL_0028: ldc.r8 3 IL_0031: stind.r8 IL_0032: ret }") ' String testData = New CompilationTestData() context.CompileExpression( "x$ = 3", DkmEvaluationFlags.None, NoAliases, errorMessage, testData) testData.GetMethodData("<>x.<>m0").VerifyIL( "{ // Code size 48 (0x30) .maxstack 4 .locals init (System.Guid V_0) IL_0000: ldtoken ""String"" IL_0005: call ""Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type"" IL_000a: ldstr ""x"" IL_000f: ldloca.s V_0 IL_0011: initobj ""System.Guid"" IL_0017: ldloc.0 IL_0018: ldnull IL_0019: call ""Sub Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, String, System.Guid, Byte())"" IL_001e: ldstr ""x"" IL_0023: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress(Of String)(String) As String"" IL_0028: ldc.i4.3 IL_0029: call ""Function Microsoft.VisualBasic.CompilerServices.Conversions.ToString(Integer) As String"" IL_002e: stind.ref IL_002f: ret }") ' Decimal testData = New CompilationTestData() context.CompileExpression( "x@ = 3", DkmEvaluationFlags.None, NoAliases, errorMessage, testData) testData.GetMethodData("<>x.<>m0").VerifyIL( "{ // Code size 53 (0x35) .maxstack 4 .locals init (System.Guid V_0) IL_0000: ldtoken ""Decimal"" IL_0005: call ""Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type"" IL_000a: ldstr ""x"" IL_000f: ldloca.s V_0 IL_0011: initobj ""System.Guid"" IL_0017: ldloc.0 IL_0018: ldnull IL_0019: call ""Sub Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, String, System.Guid, Byte())"" IL_001e: ldstr ""x"" IL_0023: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress(Of Decimal)(String) As Decimal"" IL_0028: ldc.i4.3 IL_0029: conv.i8 IL_002a: newobj ""Sub Decimal..ctor(Long)"" IL_002f: stobj ""Decimal"" IL_0034: ret }") End Sub) End Sub ''' <summary> ''' Should not allow names with '$' prefix. ''' </summary> <WorkItem(1106819, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1106819")> <Fact> Public Sub NoPrefix() Const source = "Module M Sub M() End Sub End Module" Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(MakeSources(source, assemblyName:=ExpressionCompilerUtilities.GenerateUniqueName()), options:=TestOptions.DebugDll) WithRuntimeInstance(comp, Sub(runtime) Dim context = CreateMethodContext(runtime, "M.M") Dim errorMessage As String = Nothing ' $1 Dim testData = New CompilationTestData() Dim result = context.CompileExpression( "$1 = 1", DkmEvaluationFlags.None, NoAliases, errorMessage, testData) Assert.Equal(errorMessage, "error BC30037: Character is not valid.") ' $exception testData = New CompilationTestData() result = context.CompileExpression( "$1 = 2", DkmEvaluationFlags.None, NoAliases, errorMessage, testData) Assert.Equal(errorMessage, "error BC30037: Character is not valid.") ' $ReturnValue testData = New CompilationTestData() result = context.CompileExpression( "$ReturnValue = 3", DkmEvaluationFlags.None, NoAliases, errorMessage, testData) Assert.Equal(errorMessage, "error BC30037: Character is not valid.") ' $x testData = New CompilationTestData() result = context.CompileExpression( "$x = 4", DkmEvaluationFlags.None, NoAliases, errorMessage, testData) Assert.Equal(errorMessage, "error BC30037: Character is not valid.") End Sub) End Sub <WorkItem(1101243, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1101243")> <Fact> Public Sub [ReDim]() Const source = "Module M Sub M() End Sub End Module" Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(MakeSources(source, assemblyName:=ExpressionCompilerUtilities.GenerateUniqueName()), options:=TestOptions.DebugDll) WithRuntimeInstance(comp, Sub(runtime) Dim context = CreateMethodContext(runtime, "M.M") Dim errorMessage As String = Nothing Dim testData = New CompilationTestData() context.CompileExpression( "ReDim a(3)", DkmEvaluationFlags.None, NoAliases, errorMessage, testData) testData.GetMethodData("<>x.<>m0").VerifyIL( "{ // Code size 48 (0x30) .maxstack 4 .locals init (System.Guid V_0) IL_0000: ldtoken ""Object"" IL_0005: call ""Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type"" IL_000a: ldstr ""a"" IL_000f: ldloca.s V_0 IL_0011: initobj ""System.Guid"" IL_0017: ldloc.0 IL_0018: ldnull IL_0019: call ""Sub Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, String, System.Guid, Byte())"" IL_001e: ldstr ""a"" IL_0023: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress(Of Object)(String) As Object"" IL_0028: ldc.i4.4 IL_0029: newarr ""Object"" IL_002e: stind.ref IL_002f: ret }") testData = New CompilationTestData() context.CompileExpression( "ReDim Preserve a(3)", DkmEvaluationFlags.None, NoAliases, errorMessage, testData) testData.GetMethodData("<>x.<>m0").VerifyIL( "{ // Code size 68 (0x44) .maxstack 4 .locals init (System.Guid V_0) IL_0000: ldtoken ""Object"" IL_0005: call ""Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type"" IL_000a: ldstr ""a"" IL_000f: ldloca.s V_0 IL_0011: initobj ""System.Guid"" IL_0017: ldloc.0 IL_0018: ldnull IL_0019: call ""Sub Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, String, System.Guid, Byte())"" IL_001e: ldstr ""a"" IL_0023: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress(Of Object)(String) As Object"" IL_0028: ldstr ""a"" IL_002d: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(String) As Object"" IL_0032: castclass ""System.Array"" IL_0037: ldc.i4.4 IL_0038: newarr ""Object"" IL_003d: call ""Function Microsoft.VisualBasic.CompilerServices.Utils.CopyArray(System.Array, System.Array) As System.Array"" IL_0042: stind.ref IL_0043: ret }") End Sub) End Sub <WorkItem(1101318, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1101318")> <Fact> Public Sub CompoundAssignment() Const source = "Module M Sub M() End Sub End Module" Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(MakeSources(source, assemblyName:=ExpressionCompilerUtilities.GenerateUniqueName()), options:=TestOptions.DebugDll) WithRuntimeInstance(comp, Sub(runtime) Dim context = CreateMethodContext(runtime, "M.M") Dim errorMessage As String = Nothing Dim testData = New CompilationTestData() context.CompileExpression( "x += 1", DkmEvaluationFlags.None, NoAliases, errorMessage, testData) testData.GetMethodData("<>x.<>m0").VerifyIL( "{ // Code size 63 (0x3f) .maxstack 4 .locals init (System.Guid V_0) IL_0000: ldtoken ""Object"" IL_0005: call ""Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type"" IL_000a: ldstr ""x"" IL_000f: ldloca.s V_0 IL_0011: initobj ""System.Guid"" IL_0017: ldloc.0 IL_0018: ldnull IL_0019: call ""Sub Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, String, System.Guid, Byte())"" IL_001e: ldstr ""x"" IL_0023: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress(Of Object)(String) As Object"" IL_0028: ldstr ""x"" IL_002d: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(String) As Object"" IL_0032: ldc.i4.1 IL_0033: box ""Integer"" IL_0038: call ""Function Microsoft.VisualBasic.CompilerServices.Operators.AddObject(Object, Object) As Object"" IL_003d: stind.ref IL_003e: ret }") End Sub) End Sub <WorkItem(1115044, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1115044")> <Fact> Public Sub CaseSensitivity() Const source = "Class C Shared Sub M() End Sub End Class" Dim comp = CreateCompilationWithMscorlib40({source}, options:=TestOptions.DebugDll, assemblyName:=ExpressionCompilerUtilities.GenerateUniqueName()) WithRuntimeInstance(comp, Sub(runtime) Dim context = CreateMethodContext(runtime, "C.M") Dim errorMessage As String = Nothing Dim testData = New CompilationTestData() Dim result = context.CompileExpression( "X", DkmEvaluationFlags.TreatAsExpression, ImmutableArray.Create(VariableAlias("x", GetType(String))), errorMessage, testData) Assert.Null(errorMessage) testData.GetMethodData("<>x.<>m0").VerifyIL( "{ // Code size 16 (0x10) .maxstack 1 IL_0000: ldstr ""x"" IL_0005: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(String) As Object"" IL_000a: castclass ""String"" IL_000f: ret } ") End Sub) End Sub <WorkItem(1115044, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1115044")> <Fact> Public Sub CaseSensitivity_ImplicitDeclaration() Const source = "Class C Shared Sub M() End Sub End Class" Dim comp = CreateCompilationWithMscorlib40({source}, options:=TestOptions.DebugDll, assemblyName:=ExpressionCompilerUtilities.GenerateUniqueName()) WithRuntimeInstance(comp, Sub(runtime) Dim context = CreateMethodContext(runtime, "C.M") Dim errorMessage As String = Nothing Dim testData = New CompilationTestData() Dim result = context.CompileExpression( "x = X", DkmEvaluationFlags.None, NoAliases, errorMessage, testData) Assert.Null(errorMessage) ' Use before initialization is allowed in the EE. ' Note that all x's are lowercase (i.e. normalized). testData.GetMethodData("<>x.<>m0").VerifyIL( "{ // Code size 57 (0x39) .maxstack 4 .locals init (System.Guid V_0) IL_0000: ldtoken ""Object"" IL_0005: call ""Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type"" IL_000a: ldstr ""x"" IL_000f: ldloca.s V_0 IL_0011: initobj ""System.Guid"" IL_0017: ldloc.0 IL_0018: ldnull IL_0019: call ""Sub Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, String, System.Guid, Byte())"" IL_001e: ldstr ""x"" IL_0023: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress(Of Object)(String) As Object"" IL_0028: ldstr ""x"" IL_002d: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(String) As Object"" IL_0032: call ""Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"" IL_0037: stind.ref IL_0038: ret } ") End Sub) End Sub End Class End Namespace
-1
dotnet/roslyn
56,011
React to string comparison changing on .NET Core
The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
jaredpar
"2021-08-30T17:18:52Z"
"2021-08-30T20:20:04Z"
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
4d99cda6e446e77dbb302e26388c1093bd3ef569
React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
./src/Features/VisualBasic/Portable/Structure/Providers/WithBlockStructureProvider.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading Imports Microsoft.CodeAnalysis.Shared.Collections Imports Microsoft.CodeAnalysis.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Structure Friend Class WithBlockStructureProvider Inherits AbstractSyntaxNodeStructureProvider(Of WithBlockSyntax) Protected Overrides Sub CollectBlockSpans(previousToken As SyntaxToken, node As WithBlockSyntax, ByRef spans As TemporaryArray(Of BlockSpan), optionProvider As BlockStructureOptionProvider, cancellationToken As CancellationToken) spans.AddIfNotNull(CreateBlockSpanFromBlock( node, node.WithStatement, autoCollapse:=False, type:=BlockTypes.Statement, isCollapsible:=True)) End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading Imports Microsoft.CodeAnalysis.Shared.Collections Imports Microsoft.CodeAnalysis.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Structure Friend Class WithBlockStructureProvider Inherits AbstractSyntaxNodeStructureProvider(Of WithBlockSyntax) Protected Overrides Sub CollectBlockSpans(previousToken As SyntaxToken, node As WithBlockSyntax, ByRef spans As TemporaryArray(Of BlockSpan), optionProvider As BlockStructureOptionProvider, cancellationToken As CancellationToken) spans.AddIfNotNull(CreateBlockSpanFromBlock( node, node.WithStatement, autoCollapse:=False, type:=BlockTypes.Statement, isCollapsible:=True)) End Sub End Class End Namespace
-1
dotnet/roslyn
56,011
React to string comparison changing on .NET Core
The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
jaredpar
"2021-08-30T17:18:52Z"
"2021-08-30T20:20:04Z"
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
4d99cda6e446e77dbb302e26388c1093bd3ef569
React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
./src/Features/VisualBasic/Portable/ConvertAnonymousTypeToClass/VisualBasicConvertAnonymousTypeToClassCodeRefactoringProvider.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Composition Imports System.Diagnostics.CodeAnalysis Imports Microsoft.CodeAnalysis.CodeRefactorings Imports Microsoft.CodeAnalysis.ConvertAnonymousTypeToClass Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.ConvertAnonymousTypeToClass <ExtensionOrder(Before:=PredefinedCodeRefactoringProviderNames.IntroduceVariable)> <ExportCodeRefactoringProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeRefactoringProviderNames.ConvertAnonymousTypeToClass), [Shared]> Friend Class VisualBasicConvertAnonymousTypeToClassCodeRefactoringProvider Inherits AbstractConvertAnonymousTypeToClassCodeRefactoringProvider(Of ExpressionSyntax, NameSyntax, IdentifierNameSyntax, ObjectCreationExpressionSyntax, AnonymousObjectCreationExpressionSyntax, NamespaceBlockSyntax) <ImportingConstructor> <SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")> Public Sub New() End Sub Protected Overrides Function CreateObjectCreationExpression( nameNode As NameSyntax, anonymousObject As AnonymousObjectCreationExpressionSyntax) As ObjectCreationExpressionSyntax Return SyntaxFactory.ObjectCreationExpression( attributeLists:=Nothing, nameNode, CreateArgumentList(anonymousObject.Initializer), initializer:=Nothing) End Function Private Function CreateArgumentList(initializer As ObjectMemberInitializerSyntax) As ArgumentListSyntax Return SyntaxFactory.ArgumentList( SyntaxFactory.Token(SyntaxKind.OpenParenToken).WithTriviaFrom(initializer.OpenBraceToken), CreateArguments(initializer.Initializers), SyntaxFactory.Token(SyntaxKind.CloseParenToken).WithTriviaFrom(initializer.CloseBraceToken)) End Function Private Function CreateArguments(initializers As SeparatedSyntaxList(Of FieldInitializerSyntax)) As SeparatedSyntaxList(Of ArgumentSyntax) Return SyntaxFactory.SeparatedList(Of ArgumentSyntax)(CreateArguments(initializers.GetWithSeparators())) End Function Private Function CreateArguments(list As SyntaxNodeOrTokenList) As SyntaxNodeOrTokenList Return New SyntaxNodeOrTokenList(list.Select(AddressOf CreateArgumentOrComma)) End Function Private Function CreateArgumentOrComma(declOrComma As SyntaxNodeOrToken) As SyntaxNodeOrToken Return If(declOrComma.IsToken, declOrComma, CreateArgument(CType(declOrComma, FieldInitializerSyntax))) End Function Private Shared Function CreateArgument(initializer As FieldInitializerSyntax) As ArgumentSyntax Dim expression = If(TryCast(initializer, InferredFieldInitializerSyntax)?.Expression, TryCast(initializer, NamedFieldInitializerSyntax)?.Expression) Return SyntaxFactory.SimpleArgument(expression) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Composition Imports System.Diagnostics.CodeAnalysis Imports Microsoft.CodeAnalysis.CodeRefactorings Imports Microsoft.CodeAnalysis.ConvertAnonymousTypeToClass Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.ConvertAnonymousTypeToClass <ExtensionOrder(Before:=PredefinedCodeRefactoringProviderNames.IntroduceVariable)> <ExportCodeRefactoringProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeRefactoringProviderNames.ConvertAnonymousTypeToClass), [Shared]> Friend Class VisualBasicConvertAnonymousTypeToClassCodeRefactoringProvider Inherits AbstractConvertAnonymousTypeToClassCodeRefactoringProvider(Of ExpressionSyntax, NameSyntax, IdentifierNameSyntax, ObjectCreationExpressionSyntax, AnonymousObjectCreationExpressionSyntax, NamespaceBlockSyntax) <ImportingConstructor> <SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")> Public Sub New() End Sub Protected Overrides Function CreateObjectCreationExpression( nameNode As NameSyntax, anonymousObject As AnonymousObjectCreationExpressionSyntax) As ObjectCreationExpressionSyntax Return SyntaxFactory.ObjectCreationExpression( attributeLists:=Nothing, nameNode, CreateArgumentList(anonymousObject.Initializer), initializer:=Nothing) End Function Private Function CreateArgumentList(initializer As ObjectMemberInitializerSyntax) As ArgumentListSyntax Return SyntaxFactory.ArgumentList( SyntaxFactory.Token(SyntaxKind.OpenParenToken).WithTriviaFrom(initializer.OpenBraceToken), CreateArguments(initializer.Initializers), SyntaxFactory.Token(SyntaxKind.CloseParenToken).WithTriviaFrom(initializer.CloseBraceToken)) End Function Private Function CreateArguments(initializers As SeparatedSyntaxList(Of FieldInitializerSyntax)) As SeparatedSyntaxList(Of ArgumentSyntax) Return SyntaxFactory.SeparatedList(Of ArgumentSyntax)(CreateArguments(initializers.GetWithSeparators())) End Function Private Function CreateArguments(list As SyntaxNodeOrTokenList) As SyntaxNodeOrTokenList Return New SyntaxNodeOrTokenList(list.Select(AddressOf CreateArgumentOrComma)) End Function Private Function CreateArgumentOrComma(declOrComma As SyntaxNodeOrToken) As SyntaxNodeOrToken Return If(declOrComma.IsToken, declOrComma, CreateArgument(CType(declOrComma, FieldInitializerSyntax))) End Function Private Shared Function CreateArgument(initializer As FieldInitializerSyntax) As ArgumentSyntax Dim expression = If(TryCast(initializer, InferredFieldInitializerSyntax)?.Expression, TryCast(initializer, NamedFieldInitializerSyntax)?.Expression) Return SyntaxFactory.SimpleArgument(expression) End Function End Class End Namespace
-1
dotnet/roslyn
56,011
React to string comparison changing on .NET Core
The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
jaredpar
"2021-08-30T17:18:52Z"
"2021-08-30T20:20:04Z"
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
4d99cda6e446e77dbb302e26388c1093bd3ef569
React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
./src/EditorFeatures/Test2/Rename/RenameTagProducerTests.vb
' 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.ObjectModel Imports Microsoft.CodeAnalysis.Editor.Implementation.InlineRename Imports Microsoft.CodeAnalysis.Editor.Implementation.InlineRename.HighlightTags Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Text.Shared.Extensions Imports Microsoft.VisualStudio.Text Imports Microsoft.VisualStudio.Text.Editor Imports Microsoft.VisualStudio.Text.Editor.Commanding.Commands Imports Microsoft.VisualStudio.Text.Operations Imports Microsoft.VisualStudio.Text.Tagging Imports Roslyn.Utilities Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Rename <[UseExportProvider]> Public Class RenameTagProducerTests Private Shared Function CreateCommandHandler(workspace As TestWorkspace) As RenameCommandHandler Return workspace.ExportProvider.GetCommandHandler(Of RenameCommandHandler)(PredefinedCommandHandlerNames.Rename) End Function Private Shared Async Function VerifyEmptyTaggedSpans(tagType As TextMarkerTag, actualWorkspace As TestWorkspace, renameService As InlineRenameService) As Task Await VerifyTaggedSpansCore(tagType, actualWorkspace, renameService, SpecializedCollections.EmptyEnumerable(Of Span)) End Function Private Shared Async Function VerifyTaggedSpans(tagType As TextMarkerTag, actualWorkspace As TestWorkspace, renameService As InlineRenameService) As Task Dim expectedSpans = actualWorkspace.Documents.Single(Function(d) d.SelectedSpans.Any()).SelectedSpans.Select(Function(ts) ts.ToSpan()) Await VerifyTaggedSpansCore(tagType, actualWorkspace, renameService, expectedSpans) End Function Private Shared Async Function VerifyTaggedSpans(tagType As TextMarkerTag, actualWorkspace As TestWorkspace, renameService As InlineRenameService, expectedTaggedWorkspace As TestWorkspace) As Task Dim expectedSpans = expectedTaggedWorkspace.Documents.Single(Function(d) d.SelectedSpans.Any()).SelectedSpans.Select(Function(ts) ts.ToSpan()) Await VerifyTaggedSpansCore(tagType, actualWorkspace, renameService, expectedSpans) End Function Private Shared Async Function VerifyAnnotatedTaggedSpans(tagType As TextMarkerTag, annotationString As String, actualWorkspace As TestWorkspace, renameService As InlineRenameService, expectedTaggedWorkspace As TestWorkspace) As Task Dim annotatedDocument = expectedTaggedWorkspace.Documents.SingleOrDefault(Function(d) d.AnnotatedSpans.Any()) Dim expectedSpans As IEnumerable(Of Span) If annotatedDocument Is Nothing Then expectedSpans = SpecializedCollections.EmptyEnumerable(Of Span) Else expectedSpans = GetAnnotatedSpans(annotationString, annotatedDocument) End If Await VerifyTaggedSpansCore(tagType, actualWorkspace, renameService, expectedSpans) End Function Private Shared Function GetAnnotatedSpans(annotationString As String, annotatedDocument As TestHostDocument) As IEnumerable(Of Span) Return annotatedDocument.AnnotatedSpans.SelectMany(Function(kvp) If kvp.Key = annotationString Then Return kvp.Value.Select(Function(ts) ts.ToSpan()) End If Return SpecializedCollections.EmptyEnumerable(Of Span) End Function) End Function Private Shared Async Function VerifySpansBeforeConflictResolution(actualWorkspace As TestWorkspace, renameService As InlineRenameService) As Task ' Verify no fixup/resolved non-reference conflict span. Await VerifyEmptyTaggedSpans(HighlightTags.RenameFixupTag.Instance, actualWorkspace, renameService) ' Verify valid reference tags. Await VerifyTaggedSpans(HighlightTags.RenameFieldBackgroundAndBorderTag.Instance, actualWorkspace, renameService) End Function Private Shared Async Function VerifySpansAndBufferForConflictResolution(actualWorkspace As TestWorkspace, renameService As InlineRenameService, resolvedConflictWorkspace As TestWorkspace, session As IInlineRenameSession, Optional sessionCommit As Boolean = False, Optional sessionCancel As Boolean = False) As System.Threading.Tasks.Task Await WaitForRename(actualWorkspace) ' Verify fixup/resolved conflict spans. Await VerifyAnnotatedTaggedSpans(HighlightTags.RenameFixupTag.Instance, "Complexified", actualWorkspace, renameService, resolvedConflictWorkspace) ' Verify valid reference tags. Await VerifyTaggedSpans(HighlightTags.RenameFieldBackgroundAndBorderTag.Instance, actualWorkspace, renameService, resolvedConflictWorkspace) VerifyBufferContentsInWorkspace(actualWorkspace, resolvedConflictWorkspace) If sessionCommit Or sessionCancel Then Assert.True(Not sessionCommit Or Not sessionCancel) If sessionCancel Then session.Cancel() VerifyBufferContentsInWorkspace(actualWorkspace, actualWorkspace) ElseIf sessionCommit Then session.Commit() VerifyBufferContentsInWorkspace(actualWorkspace, resolvedConflictWorkspace) End If End If End Function Private Shared Async Function VerifyTaggedSpansCore(tagType As TextMarkerTag, actualWorkspace As TestWorkspace, renameService As InlineRenameService, expectedSpans As IEnumerable(Of Span)) As Task Dim taggedSpans = Await GetTagsOfType(tagType, actualWorkspace, renameService) Assert.Equal(expectedSpans, taggedSpans) End Function Private Shared Sub VerifyBufferContentsInWorkspace(actualWorkspace As TestWorkspace, expectedWorkspace As TestWorkspace) Dim actualDocs = actualWorkspace.Documents Dim expectedDocs = expectedWorkspace.Documents Assert.Equal(expectedDocs.Count, actualDocs.Count) For i = 0 To actualDocs.Count - 1 Dim actualDocument = actualDocs(i) Dim expectedDocument = expectedDocs(i) Dim actualText = actualDocument.GetTextBuffer().CurrentSnapshot.GetText().Trim() Dim expectedText = expectedDocument.GetTextBuffer().CurrentSnapshot.GetText().Trim() Assert.Equal(expectedText, actualText) Next End Sub <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function ValidTagsDuringSimpleRename(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Goo|] { void Blah() { [|Goo|] f = new [|Goo|](); } } </Document> </Project> </Workspace>, host) Dim renameService = workspace.GetService(Of InlineRenameService)() Dim session = StartSession(workspace) Await VerifyTaggedSpans(HighlightTags.RenameFieldBackgroundAndBorderTag.Instance, workspace, renameService) session.Cancel() End Using End Function <WpfTheory> <WorkItem(922197, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/922197")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function UnresolvableConflictInModifiedDocument(host As RenameTestHost) As System.Threading.Tasks.Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Program { static void Main(string[] {|conflict:args|}, int $$goo) { Goo(c => IsInt({|conflict:goo|}, c)); } private static void Goo(Func&lt;char, bool> p) { } private static void Goo(Func&lt;int, bool> p) { } private static bool IsInt(int goo, char c) { } } </Document> </Project> </Workspace>, host) Dim renameService = workspace.GetService(Of InlineRenameService)() Dim document = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue) Dim location = document.CursorPosition.Value Dim session = StartSession(workspace) document.GetTextBuffer().Replace(New Span(location, 3), "args") Await WaitForRename(workspace) Using renamedWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Program { static void Main(string[] {|conflict:args|}, int args) { Goo(c => IsInt({|conflict:args|}, c)); } private static void Goo(Func&lt;char, bool> p) { } private static void Goo(Func&lt;int, bool> p) { } private static bool IsInt(int goo, char c) { } } </Document> </Project> </Workspace>, host) Dim renamedDocument = renamedWorkspace.Documents.Single() Dim expectedSpans = GetAnnotatedSpans("conflict", renamedDocument) Dim taggedSpans = GetTagsOfType(RenameConflictTag.Instance, renameService, document.GetTextBuffer()) Assert.Equal(expectedSpans, taggedSpans) End Using End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function VerifyLinkedFiles_InterleavedResolvedConflicts(host As RenameTestHost) As System.Threading.Tasks.Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSProj" PreprocessorSymbols="Proj1"> <Document FilePath="C.cs"> public class Class1 { #if Proj2 int fieldclash; #endif int field$$; void M() { int fieldclash = 8; #if Proj1 var a = [|field|]; #elif Proj2 var a = [|field|]; #elif Proj3 var a = field; #endif #if Proj1 var b = [|field|]; #elif Proj2 var b = [|field|]; #elif Proj3 var b = field; #endif } } </Document> </Project> <Project Language="C#" CommonReferences="true" PreprocessorSymbols="Proj2"> <Document IsLinkFile="true" LinkAssemblyName="CSProj" LinkFilePath="C.cs"/> </Project> </Workspace>, host) Dim renameService = workspace.GetService(Of InlineRenameService)() Dim document = workspace.Documents.First(Function(d) d.CursorPosition.HasValue) Dim location = document.CursorPosition.Value Dim session = StartSession(workspace) document.GetTextBuffer().Insert(location, "clash") Await WaitForRename(workspace) Using renamedWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSProj" PreprocessorSymbols="Proj1"> <Document FilePath="C.cs"> public class Class1 { #if Proj2 int fieldclash; #endif int {|valid:fieldclash|}; void M() { int fieldclash = 8; #if Proj1 {|resolved:var a = this.{|valid:fieldclash|};|} #elif Proj2 var a = {|conflict:fieldclash|}; #elif Proj3 var a = field; #endif #if Proj1 {|resolved:var b = this.{|valid:fieldclash|};|} #elif Proj2 var b = {|conflict:fieldclash|}; #elif Proj3 var b = field; #endif } } </Document> </Project> <Project Language="C#" CommonReferences="true" PreprocessorSymbols="Proj2"> <Document IsLinkFile="true" LinkAssemblyName="CSProj" LinkFilePath="C.cs"/> </Project> </Workspace>, host) Dim renamedDocument = renamedWorkspace.Documents.First() Dim expectedSpans = GetAnnotatedSpans("resolved", renamedDocument) Dim taggedSpans = GetTagsOfType(RenameFixupTag.Instance, renameService, document.GetTextBuffer()) Assert.Equal(expectedSpans, taggedSpans) expectedSpans = GetAnnotatedSpans("conflict", renamedDocument) taggedSpans = GetTagsOfType(RenameConflictTag.Instance, renameService, document.GetTextBuffer()) Assert.Equal(expectedSpans, taggedSpans) expectedSpans = GetAnnotatedSpans("valid", renamedDocument) taggedSpans = GetTagsOfType(RenameFieldBackgroundAndBorderTag.Instance, renameService, document.GetTextBuffer()) Assert.Equal(expectedSpans, taggedSpans) End Using End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function VerifyLinkedFiles_UnresolvableConflictComments(host As RenameTestHost) As Task Dim originalDocument = " public class Class1 { #if Proj1 void Test(double x) { } #elif Proj2 void Test(long x) { } #endif void Tes$$(int i) { } void M() { Test(5); } }" Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSProj" PreprocessorSymbols="Proj1"> <Document FilePath="C.cs"><%= originalDocument %></Document> </Project> <Project Language="C#" CommonReferences="true" PreprocessorSymbols="Proj2"> <Document IsLinkFile="true" LinkAssemblyName="CSProj" LinkFilePath="C.cs"/> </Project> </Workspace>, host) Dim renameService = workspace.GetService(Of InlineRenameService)() Dim document = workspace.Documents.First(Function(d) d.CursorPosition.HasValue) Dim location = document.CursorPosition.Value Dim session = StartSession(workspace) document.GetTextBuffer().Insert(location, "t") Await WaitForRename(workspace) Dim expectedDocument = $" public class Class1 {{ #if Proj1 void Test(double x) {{ }} #elif Proj2 void Test(long x) {{ }} #endif void Test(int i) {{ }} void M() {{ {{|conflict:{{|conflict:/* {String.Format(WorkspacesResources.Unmerged_change_from_project_0, "CSharpAssembly1")} {WorkspacesResources.Before_colon} Test(5); {WorkspacesResources.After_colon} Test((long)5); *|}}|}}/ Test((double)5); }} }}" Using renamedWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSProj" PreprocessorSymbols="Proj1"> <Document FilePath="C.cs"><%= expectedDocument %></Document> </Project> <Project Language="C#" CommonReferences="true" PreprocessorSymbols="Proj2"> <Document IsLinkFile="true" LinkAssemblyName="CSProj" LinkFilePath="C.cs"/> </Project> </Workspace>, host) Dim renamedDocument = renamedWorkspace.Documents.First() Dim expectedSpans = GetAnnotatedSpans("conflict", renamedDocument) Dim taggedSpans = GetTagsOfType(RenameConflictTag.Instance, renameService, document.GetTextBuffer()) Assert.Equal(expectedSpans, taggedSpans) End Using End Using End Function <WpfTheory> <WorkItem(922197, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/922197")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function UnresolvableConflictInUnmodifiedDocument(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$A|] { } </Document> <Document FilePath="B.cs"> class {|conflict:B|} { } </Document> </Project> </Workspace>, host) Dim renameService = workspace.GetService(Of InlineRenameService)() Dim location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).GetTextBuffer() Dim session = StartSession(workspace) textBuffer.Replace(New Span(location, 1), "B") Await WaitForRename(workspace) Dim conflictDocument = workspace.Documents.Single(Function(d) d.FilePath = "B.cs") Dim expectedSpans = GetAnnotatedSpans("conflict", conflictDocument) Dim taggedSpans = GetTagsOfType(RenameConflictTag.Instance, renameService, conflictDocument.GetTextBuffer()) Assert.Equal(expectedSpans, taggedSpans) End Using End Function <WpfTheory> <WorkItem(847467, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/847467")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function ValidStateWithEmptyReplacementTextAfterConflictResolution(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$T|] { } </Document> </Project> </Workspace>, host) Dim renameService = workspace.GetService(Of InlineRenameService)() Dim location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() Dim session = StartSession(workspace) textBuffer.Replace(New Span(location, 1), "this") ' Verify @ escaping Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class @[|this|] { } </Document> </Project> </Workspace>, host) Await VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session) End Using textBuffer.Delete(New Span(location + 1, 4)) Await WaitForRename(workspace) ' Verify no escaping Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class { } </Document> </Project> </Workspace>, host) VerifyBufferContentsInWorkspace(workspace, resolvedConflictWorkspace) End Using session.Commit() Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class T { } </Document> </Project> </Workspace>, host) VerifyBufferContentsInWorkspace(workspace, resolvedConflictWorkspace) End Using End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(812789, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/812789")> Public Async Function RenamingEscapedIdentifiers(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void @$$as() { } } </Document> </Project> </Workspace>, host) Dim renameService = workspace.GetService(Of InlineRenameService)() Dim location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim session = StartSession(workspace) Dim textBuffer = workspace.Documents.Single().GetTextBuffer() ' Verify @ escaping is still present Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void @[|as|]() { } } </Document> </Project> </Workspace>, host) Await VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session) End Using textBuffer.Replace(New Span(location, 2), "bar") ' Verify @ escaping is removed Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void [|bar|]() { } } </Document> </Project> </Workspace>, host) Await VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session) End Using End Using End Function <WpfTheory> <WorkItem(812795, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/812795")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function BackspacingAfterConflictResolutionPreservesTrackingSpans(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void Method() { $$Bar(0); } void Goo(int i) { } void Bar(double d) { } } </Document> </Project> </Workspace>, host) Dim view = workspace.Documents.Single().GetTextView() Dim location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() Dim renameService = workspace.GetService(Of InlineRenameService)() Dim editorOperations = workspace.GetService(Of IEditorOperationsFactoryService).GetEditorOperations(view) Dim commandHandler = CreateCommandHandler(workspace) Dim session = StartSession(workspace) textBuffer.Replace(New Span(location, 3), "Goo") Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void Method() { {|Complexified:[|Goo|]((double)0);|} } void Goo(int i) { } void [|Goo|](double d) { } } </Document> </Project> </Workspace>, host) Await VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session) End Using ' Delete Goo and type "as" commandHandler.ExecuteCommand(New BackspaceKeyCommandArgs(view, view.TextBuffer), Sub() editorOperations.Backspace(), Utilities.TestCommandExecutionContext.Create()) commandHandler.ExecuteCommand(New BackspaceKeyCommandArgs(view, view.TextBuffer), Sub() editorOperations.Backspace(), Utilities.TestCommandExecutionContext.Create()) commandHandler.ExecuteCommand(New BackspaceKeyCommandArgs(view, view.TextBuffer), Sub() editorOperations.Backspace(), Utilities.TestCommandExecutionContext.Create()) commandHandler.ExecuteCommand(New TypeCharCommandArgs(view, view.TextBuffer, "a"c), Sub() editorOperations.InsertText("a"), Utilities.TestCommandExecutionContext.Create()) commandHandler.ExecuteCommand(New TypeCharCommandArgs(view, view.TextBuffer, "s"c), Sub() editorOperations.InsertText("s"), Utilities.TestCommandExecutionContext.Create()) Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void Method() { @[|as|](0); } void Goo(int i) { } void @[|as|](double d) { } } </Document> </Project> </Workspace>, host) Await VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session) End Using End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function CSharp_FixupSpanDuringResolvableConflict_NonReferenceConflict(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Goo { int bar; void M(int [|$$goo|]) { var x = [|goo|]; bar = 23; } } </Document> </Project> </Workspace>, host) Dim renameService = workspace.GetService(Of InlineRenameService)() Dim session = StartSession(workspace) Dim textBuffer = workspace.Documents.Single().GetTextBuffer() Dim location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Await VerifySpansBeforeConflictResolution(workspace, renameService) ' Apply edit so that we have a resolved non-reference conflict. textBuffer.Replace(New Span(location, 3), "bar") ' Verify fixup/resolved non-reference conflict span. Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Goo { int bar; void M(int [|bar|]) { var x = [|bar|]; {|Complexified:this.{|Resolved:bar|} = 23;|} } } </Document> </Project> </Workspace>, host) Await VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session) End Using ' Make another edit so that we have no more conflicts. location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value textBuffer.Replace(New Span(location, 3), "baR") Using newWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Goo { int bar; void M(int [|$$baR|]) { var x = [|baR|]; bar = 23; } } </Document> </Project> </Workspace>, host) Await VerifySpansAndBufferForConflictResolution(workspace, renameService, newWorkspace, session, sessionCommit:=True) End Using End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function VisualBasic_FixupSpanDuringResolvableConflict_NonReferenceConflict(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Goo Dim bar As Integer Sub M([|$$goo|] As Integer) Dim x = [|goo|] BAR = 23 End Sub End Class </Document> </Project> </Workspace>, host) Dim renameService = workspace.GetService(Of InlineRenameService)() Dim session = StartSession(workspace) Dim textBuffer = workspace.Documents.Single().GetTextBuffer() Dim location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Await VerifySpansBeforeConflictResolution(workspace, renameService) ' Apply edit so that we have a resolved non-reference conflict. textBuffer.Replace(New Span(location, 3), "bar") ' Verify fixup/resolved non-reference conflict span. Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Goo Dim bar As Integer Sub M([|bar|] As Integer) Dim x = [|bar|] {|Complexified:Me.{|Resolved:BAR|} = 23|} End Sub End Class </Document> </Project> </Workspace>, host) Await VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session) End Using ' Make another edit so that we have no more conflicts. location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value textBuffer.Replace(New Span(location, 3), "boo") Using newWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Goo Dim bar As Integer Sub M([|$$boo|] As Integer) Dim x = [|boo|] BAR = 23 End Sub End Class </Document> </Project> </Workspace>, host) Await VerifySpansAndBufferForConflictResolution(workspace, renameService, newWorkspace, session, sessionCommit:=True) End Using End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function CSharp_FixupSpanDuringResolvableConflict_ReferenceConflict(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Goo { int [|$$goo|]; void M(int bar) { [|goo|] = [|goo|] + bar; } } </Document> </Project> </Workspace>, host) Dim renameService = workspace.GetService(Of InlineRenameService)() Dim session = StartSession(workspace) Dim textBuffer = workspace.Documents.Single().GetTextBuffer() Dim location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Await VerifySpansBeforeConflictResolution(workspace, renameService) ' Apply edit so that we have a resolved reference conflict. textBuffer.Replace(New Span(location, 3), "bar") ' Verify fixup/resolved conflict span. Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Goo { int [|bar|]; void M(int bar) { {|Complexified:this.{|Resolved:[|bar|]|} = this.{|Resolved:[|bar|]|} + bar;|} } } </Document> </Project> </Workspace>, host) Await VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session) End Using textBuffer.Replace(New Span(location, 3), "ba") Using newWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Goo { int [|$$ba|]; void M(int bar) { [|ba|] = [|ba|] + bar; } } </Document> </Project> </Workspace>, host) Await VerifySpansAndBufferForConflictResolution(workspace, renameService, newWorkspace, session, sessionCancel:=True) End Using End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function VisualBasic_FixupSpanDuringResolvableConflict_ReferenceConflict(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Goo Dim [|$$goo|] As Integer Sub M(bar As Integer) [|goo|] = [|goo|] + bar End Sub End Class </Document> </Project> </Workspace>, host) Dim renameService = workspace.GetService(Of InlineRenameService)() Dim session = StartSession(workspace) Dim textBuffer = workspace.Documents.Single().GetTextBuffer() Dim location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Await VerifySpansBeforeConflictResolution(workspace, renameService) ' Apply edit so that we have a resolved reference conflict. textBuffer.Replace(New Span(location, 3), "bar") ' Verify fixup/resolved conflict span. Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Goo Dim [|bar|] As Integer Sub M(bar As Integer) {|Complexified:Me.{|Resolved:[|bar|]|} = Me.{|Resolved:[|bar|]|} + bar|} End Sub End Class </Document> </Project> </Workspace>, host) Await VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session) End Using ' Make another edit so that we have no more conflicts. textBuffer.Replace(New Span(location, 3), "ba") Using newWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Goo Dim [|$$ba|] As Integer Sub M(bar As Integer) [|ba|] = [|ba|] + bar End Sub End Class </Document> </Project> </Workspace>, host) Await VerifySpansAndBufferForConflictResolution(workspace, renameService, newWorkspace, session, sessionCancel:=True) End Using End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function CSharp_FixupSpanDuringResolvableConflict_NeedsEscaping(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Goo { int @int; void M(int [|$$goo|]) { var x = [|goo|]; @int = 23; } } </Document> </Project> </Workspace>, host) Dim renameService = workspace.GetService(Of InlineRenameService)() Dim session = StartSession(workspace) Dim textBuffer = workspace.Documents.Single().GetTextBuffer() Dim location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Await VerifySpansBeforeConflictResolution(workspace, renameService) ' Apply edit so that we have a resolved escaping conflict. textBuffer.Replace(New Span(location, 3), "int") ' Verify fixup/resolved conflict span. Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Goo { int @int; void M(int {|Resolved:@[|int|]|}) { var x = {|Resolved:@[|int|]|}; {|Complexified:this.{|Resolved:@int|} = 23;|} } } </Document> </Project> </Workspace>, host) Await VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session) End Using ' Make another edit to change "int" to "@in" so that we have no more conflicts, just escaping. textBuffer.Replace(New Span(location + 1, 3), "in") ' Verify resolved escaping conflict spans. Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Goo { int @int; void M(int {|Resolved:@[|in|]|}) { var x = {|Resolved:@[|in|]|}; @int = 23; } } </Document> </Project> </Workspace>, host) Await VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session, sessionCommit:=True) End Using End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function VisualBasic_FixupSpanDuringResolvableConflict_NeedsEscaping(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Goo Dim [New] As Integer Sub M([|$$goo|] As Integer) Dim x = [|goo|] [NEW] = 23 End Sub End Class </Document> </Project> </Workspace>, host) Dim renameService = workspace.GetService(Of InlineRenameService)() Dim session = StartSession(workspace) Dim textBuffer = workspace.Documents.Single().GetTextBuffer() Dim location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Await VerifySpansBeforeConflictResolution(workspace, renameService) ' Apply edit so that we have a resolved escaping conflict. textBuffer.Replace(New Span(location, 3), "New") ' Verify fixup/resolved conflict span. Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Goo Dim [New] As Integer Sub M({|Resolved:[[|New|]]|} As Integer) Dim x = {|Resolved:[[|New|]]|} {|Complexified:Me.{|Resolved:[NEW]|} = 23|} End Sub End Class </Document> </Project> </Workspace>, host) Await VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session) End Using ' Make another edit to change "New" to "[Do]" so that we have no more conflicts, just escaping. textBuffer.Replace(New Span(location + 1, 3), "Do") ' Verify resolved escaping conflict spans. Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Goo Dim [New] As Integer Sub M({|Resolved:[[|Do|]]|} As Integer) Dim x = {|Resolved:[[|Do|]]|} [NEW] = 23 End Sub End Class </Document> </Project> </Workspace>, host) Await VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session, sessionCommit:=True) End Using End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function FixupSpanDuringResolvableConflict_VerifyCaret(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Goo Sub [|N$$w|](goo As Integer) End Sub End Class </Document> </Project> </Workspace>, host) Dim view = workspace.Documents.Single().GetTextView() Dim editorOperations = workspace.GetService(Of IEditorOperationsFactoryService).GetEditorOperations(view) Dim commandHandler = CreateCommandHandler(workspace) Dim textViewService = Assert.IsType(Of TextBufferAssociatedViewService)(workspace.ExportProvider.GetExportedValue(Of ITextBufferAssociatedViewService)()) Dim buffers = New Collection(Of ITextBuffer) buffers.Add(view.TextBuffer) DirectCast(textViewService, ITextViewConnectionListener).SubjectBuffersConnected(view, ConnectionReason.TextViewLifetime, buffers) Dim renameService = workspace.GetService(Of InlineRenameService)() Dim session = StartSession(workspace) Await VerifySpansBeforeConflictResolution(workspace, renameService) ' Type first in the main identifier view.Selection.Clear() view.Caret.MoveTo(New SnapshotPoint(view.TextBuffer.CurrentSnapshot, workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value)) commandHandler.ExecuteCommand(New TypeCharCommandArgs(view, view.TextBuffer, "e"c), Sub() editorOperations.InsertText("e"), Utilities.TestCommandExecutionContext.Create()) ' Verify fixup/resolved conflict span. Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Goo Sub [[|Ne$$w|]](goo As Integer) End Sub End Class </Document> </Project> </Workspace>, host) Await VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session) Dim location = view.Caret.Position.BufferPosition.Position Dim expectedLocation = resolvedConflictWorkspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Assert.Equal(expectedLocation, location) End Using ' Make another edit to change "New" to "Nexw" so that we have no more conflicts or escaping. commandHandler.ExecuteCommand(New TypeCharCommandArgs(view, view.TextBuffer, "x"c), Sub() editorOperations.InsertText("x"), Utilities.TestCommandExecutionContext.Create()) ' Verify resolved escaping conflict spans. Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Goo Sub [|Nex$$w|](goo As Integer) End Sub End Class </Document> </Project> </Workspace>, host) Await VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session) Dim location = view.Caret.Position.BufferPosition.Position Dim expectedLocation = resolvedConflictWorkspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Assert.Equal(expectedLocation, location) End Using End Using End Function <WpfTheory> <WorkItem(771743, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/771743")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function VerifyNoSelectionAfterCommit(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Goo Sub [|M$$ain|](goo As Integer) End Sub End Class </Document> </Project> </Workspace>, host) Dim view = workspace.Documents.Single().GetTextView() Dim editorOperations = workspace.GetService(Of IEditorOperationsFactoryService).GetEditorOperations(view) Dim commandHandler = CreateCommandHandler(workspace) Dim textViewService = Assert.IsType(Of TextBufferAssociatedViewService)(workspace.ExportProvider.GetExportedValue(Of ITextBufferAssociatedViewService)()) Dim buffers = New Collection(Of ITextBuffer) buffers.Add(view.TextBuffer) DirectCast(textViewService, ITextViewConnectionListener).SubjectBuffersConnected(view, ConnectionReason.TextViewLifetime, buffers) Dim location = view.Caret.Position.BufferPosition.Position view.Selection.Select(New SnapshotSpan(view.Caret.Position.BufferPosition, 2), False) Dim renameService = workspace.GetService(Of InlineRenameService)() Dim session = StartSession(workspace) Await VerifySpansBeforeConflictResolution(workspace, renameService) ' Type few characters. view.Caret.MoveTo(New SnapshotPoint(view.TextBuffer.CurrentSnapshot, workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value)) commandHandler.ExecuteCommand(New TypeCharCommandArgs(view, view.TextBuffer, "e"c), Sub() editorOperations.InsertText("e"), Utilities.TestCommandExecutionContext.Create()) commandHandler.ExecuteCommand(New TypeCharCommandArgs(view, view.TextBuffer, "f"c), Sub() editorOperations.InsertText("f"), Utilities.TestCommandExecutionContext.Create()) commandHandler.ExecuteCommand(New TypeCharCommandArgs(view, view.TextBuffer, "g"c), Sub() editorOperations.InsertText("g"), Utilities.TestCommandExecutionContext.Create()) session.Commit() Dim selectionLength = view.Selection.End.Position - view.Selection.Start.Position Assert.Equal(0, selectionLength) End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function CSharp_FixupSpanDuringResolvableConflict_ComplexificationOutsideConflict(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Program { static void Main(string[] args) { int x = [|$$Bar|](Goo([|Bar|](0))); } static int Goo(int i) { return 0; } static int [|Bar|](double d) { return 1; } } </Document> </Project> </Workspace>, host) Dim renameService = workspace.GetService(Of InlineRenameService)() Dim session = StartSession(workspace) Dim textBuffer = workspace.Documents.Single().GetTextBuffer() Dim location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Await VerifySpansBeforeConflictResolution(workspace, renameService) ' Apply edit so that we have a resolved reference conflict. textBuffer.Replace(New Span(location, 3), "Goo") ' Verify fixup/resolved conflict span. Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Program { static void Main(string[] args) { {|Complexified:int x = {|Resolved:[|Goo|]|}((double)Goo({|Resolved:[|Goo|]|}((double)0)));|} } static int Goo(int i) { return 0; } static int [|Goo|](double d) { return 1; } } </Document> </Project> </Workspace>, host) Await VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session) End Using ' Make another edit so that we have no more conflicts. textBuffer.Replace(New Span(location, 3), "GOO") Using newWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Program { static void Main(string[] args) { int x = [|$$GOO|](Goo([|GOO|](0))); } static int Goo(int i) { return 0; } static int [|GOO|](double d) { return 1; } } </Document> </Project> </Workspace>, host) Await VerifySpansAndBufferForConflictResolution(workspace, renameService, newWorkspace, session, sessionCommit:=True) End Using End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function CSharp_FixupSpanDuringResolvableConflict_ContainedComplexifiedSpan(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ using System; namespace N { class A<T> { public virtual void Goo(T x) { } class B<S> : A<B<S>> { class [|$$C|]<U> : B<[|C|]<U>> // Rename C to A { public override void Goo(A<A<T>.B<S>>.B<A<T>.B<S>.[|C|]<U>> x) { } } } } } ]]> </Document> </Project> </Workspace>, host) Dim renameService = workspace.GetService(Of InlineRenameService)() Dim session = StartSession(workspace) Dim textBuffer = workspace.Documents.Single().GetTextBuffer() Dim location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Await VerifySpansBeforeConflictResolution(workspace, renameService) ' Apply edit so that we have a resolved reference conflict. textBuffer.Replace(New Span(location, 1), "A") ' Verify fixup/resolved conflict span. Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ using System; namespace N { class A<T> { public virtual void Goo(T x) { } class B<S> : A<B<S>> { class [|A|]<U> : B<[|A|]<U>> // Rename C to A { public override void Goo({|Complexified:N.{|Resolved:A|}<N.{|Resolved:A|}<T>.B<S>>|}.B<{|Complexified:N.{|Resolved:A|}<T>|}.B<S>.[|A|]<U>> x) { } } } } } ]]> </Document> </Project> </Workspace>, host) Await VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session, sessionCommit:=True) End Using End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(8334, "https://github.com/dotnet/roslyn/issues/8334")> Public Async Function CSharp_FixupSpanDuringResolvableConflict_ComplexificationReordersReferenceSpans(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> static class E { public static C [|$$Goo|](this C x, int tag) { return new C(); } } class C { C Bar(int tag) { return this.[|Goo|](1).[|Goo|](2); } } </Document> </Project> </Workspace>, host) Dim renameService = workspace.GetService(Of InlineRenameService)() Dim session = StartSession(workspace) Dim textBuffer = workspace.Documents.Single().GetTextBuffer() Dim location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Await VerifySpansBeforeConflictResolution(workspace, renameService) ' Apply edit so that we have a resolved reference conflict. textBuffer.Replace(New Span(location, 3), "Bar") ' Verify fixup/resolved conflict span. Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> static class E { public static C [|Bar|](this C x, int tag) { return new C(); } } class C { C Bar(int tag) { {|Complexified:return E.{|Resolved:[|Bar|]|}(E.{|Resolved:[|Bar|]|}(this, 1), 2);|} } } </Document> </Project> </Workspace>, host) Await VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session, sessionCommit:=True) End Using End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function CSharp_FixupSpanDuringResolvableConflict_WithinCrefs(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ using System; using F = N; namespace N { interface I { void Goo(); } } class C { class E : F.I { /// <summary> /// This is a function <see cref="F.I.Goo"/> /// </summary> public void Goo() { } } class [|$$K|] { } } ]]> </Document> </Project> </Workspace>, host) Dim renameService = workspace.GetService(Of InlineRenameService)() Dim session = StartSession(workspace) Dim textBuffer = workspace.Documents.Single().GetTextBuffer() Dim location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Await VerifySpansBeforeConflictResolution(workspace, renameService) ' Apply edit so that we have a resolved reference conflict. textBuffer.Replace(New Span(location, 1), "F") ' Verify fixup/resolved conflict span. Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ using System; using F = N; namespace N { interface I { void Goo(); } } class C { class E : {|Complexified:{|Resolved:N|}|}.I { /// <summary> /// This is a function <see cref="{|Complexified:{|Resolved:N|}|}.I.Goo"/> /// </summary> public void Goo() { } } class [|$$F|] { } } ]]> </Document> </Project> </Workspace>, host) Await VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session, sessionCommit:=True) End Using End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function CSharp_FixupSpanDuringResolvableConflict_OverLoadResolutionChangesInEnclosingInvocations(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ using System; static class C { static void Ex(this string x) { } static void Outer(Action<string> x, object y) { Console.WriteLine(1); } static void Outer(Action<int> x, int y) { Console.WriteLine(2); } static void Inner(Action<string> x, string y) { } static void Inner(Action<string> x, int y) { } static void Inner(Action<int> x, int y) { } static void Main() { Outer(y => Inner(x => x.Ex(), y), 0); } } static class E { public static void [|$$Ex|](this int x) { } // Rename Ex to Goo } ]]> </Document> </Project> </Workspace>, host) Dim renameService = workspace.GetService(Of InlineRenameService)() Dim session = StartSession(workspace) Dim textBuffer = workspace.Documents.Single().GetTextBuffer() Dim location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Await VerifySpansBeforeConflictResolution(workspace, renameService) ' Apply edit so that we have a resolved reference conflict. textBuffer.Replace(New Span(location, 2), "Goo") ' Verify fixup/resolved conflict span. Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ using System; static class C { static void Ex(this string x) { } static void Outer(Action<string> x, object y) { Console.WriteLine(1); } static void Outer(Action<int> x, int y) { Console.WriteLine(2); } static void Inner(Action<string> x, string y) { } static void Inner(Action<string> x, int y) { } static void Inner(Action<int> x, int y) { } static void Main() { {|Complexified:{|Resolved:Outer|}((string y) => {|Resolved:Inner|}(x => x.Ex(), y), 0);|} } } static class E { public static void [|Goo|](this int x) { } // Rename Ex to Goo } ]]> </Document> </Project> </Workspace>, host) Await VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session, sessionCommit:=True) End Using End Using End Function <WpfTheory> <WorkItem(530817, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530817")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function CSharpShowDeclarationConflictsImmediately(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Program { static void Main(string[] args) { const int {|valid:$$V|} = 5; int {|conflict:V|} = 99; } } </Document> </Project> </Workspace>, host) Dim renameService = workspace.GetService(Of InlineRenameService)() Dim session = StartSession(workspace) Dim validTaggedSpans = Await GetTagsOfType(HighlightTags.RenameFieldBackgroundAndBorderTag.Instance, workspace, renameService) Dim validExpectedSpans = workspace.Documents.Single(Function(d) d.AnnotatedSpans.Count > 0).AnnotatedSpans("valid").Select(Function(ts) ts.ToSpan()) Dim conflictTaggedSpans = Await GetTagsOfType(RenameConflictTag.Instance, workspace, renameService) Dim conflictExpectedSpans = workspace.Documents.Single(Function(d) d.AnnotatedSpans.Count > 0).AnnotatedSpans("conflict").Select(Function(ts) ts.ToSpan()) session.Cancel() AssertEx.Equal(validExpectedSpans, validTaggedSpans) AssertEx.Equal(conflictExpectedSpans, conflictTaggedSpans) End Using End Function <WpfTheory> <WorkItem(530817, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530817")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function VBShowDeclarationConflictsImmediately(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Goo Sub Bar() Dim {|valid:$$V|} as Integer Dim {|conflict:V|} as String End Sub End Class </Document> </Project> </Workspace>, host) Dim renameService = workspace.GetService(Of InlineRenameService)() Dim session = StartSession(workspace) Dim validTaggedSpans = Await GetTagsOfType(HighlightTags.RenameFieldBackgroundAndBorderTag.Instance, workspace, renameService) Dim validExpectedSpans = workspace.Documents.Single(Function(d) d.AnnotatedSpans.Count > 0).AnnotatedSpans("valid").Select(Function(ts) ts.ToSpan()) Dim conflictTaggedSpans = Await GetTagsOfType(RenameConflictTag.Instance, workspace, renameService) Dim conflictExpectedSpans = workspace.Documents.Single(Function(d) d.AnnotatedSpans.Count > 0).AnnotatedSpans("conflict").Select(Function(ts) ts.ToSpan()) session.Cancel() AssertEx.Equal(validExpectedSpans, validTaggedSpans) AssertEx.Equal(conflictExpectedSpans, conflictTaggedSpans) End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function ActiveSpanInSecondaryView(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class [|$$Goo|] End Class </Document> <Document> ' [|Goo|] </Document> </Project> </Workspace>, host) Dim renameService = workspace.GetService(Of InlineRenameService)() Dim location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents(0).GetTextBuffer() Dim session = StartSession(workspace) session.RefreshRenameSessionWithOptionsChanged(CodeAnalysis.Rename.RenameOptions.RenameInComments, newValue:=True) Await WaitForRename(workspace) session.RefreshRenameSessionWithOptionsChanged(CodeAnalysis.Rename.RenameOptions.RenameInComments, newValue:=False) Await WaitForRename(workspace) textBuffer.Replace(New Span(location, 3), "Bar") Await WaitForRename(workspace) End Using End Function Private Shared Async Function GetTagsOfType(expectedTagType As ITextMarkerTag, workspace As TestWorkspace, renameService As InlineRenameService) As Task(Of IEnumerable(Of Span)) Dim textBuffer = workspace.Documents.Single().GetTextBuffer() Await WaitForRename(workspace) Return GetTagsOfType(expectedTagType, renameService, textBuffer) End Function Private Shared Function GetTagsOfType(expectedTagType As ITextMarkerTag, renameService As InlineRenameService, textBuffer As ITextBuffer) As IEnumerable(Of Span) Dim tagger = New RenameTagger(textBuffer, renameService) Dim tags = tagger.GetTags(textBuffer.CurrentSnapshot.GetSnapshotSpanCollection()) Return (From tag In tags Where tag.Tag Is expectedTagType Order By tag.Span.Start Select tag.Span.Span).ToList() End Function End Class End Namespace
' 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.ObjectModel Imports Microsoft.CodeAnalysis.Editor.Implementation.InlineRename Imports Microsoft.CodeAnalysis.Editor.Implementation.InlineRename.HighlightTags Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Text.Shared.Extensions Imports Microsoft.VisualStudio.Text Imports Microsoft.VisualStudio.Text.Editor Imports Microsoft.VisualStudio.Text.Editor.Commanding.Commands Imports Microsoft.VisualStudio.Text.Operations Imports Microsoft.VisualStudio.Text.Tagging Imports Roslyn.Utilities Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Rename <[UseExportProvider]> Public Class RenameTagProducerTests Private Shared Function CreateCommandHandler(workspace As TestWorkspace) As RenameCommandHandler Return workspace.ExportProvider.GetCommandHandler(Of RenameCommandHandler)(PredefinedCommandHandlerNames.Rename) End Function Private Shared Async Function VerifyEmptyTaggedSpans(tagType As TextMarkerTag, actualWorkspace As TestWorkspace, renameService As InlineRenameService) As Task Await VerifyTaggedSpansCore(tagType, actualWorkspace, renameService, SpecializedCollections.EmptyEnumerable(Of Span)) End Function Private Shared Async Function VerifyTaggedSpans(tagType As TextMarkerTag, actualWorkspace As TestWorkspace, renameService As InlineRenameService) As Task Dim expectedSpans = actualWorkspace.Documents.Single(Function(d) d.SelectedSpans.Any()).SelectedSpans.Select(Function(ts) ts.ToSpan()) Await VerifyTaggedSpansCore(tagType, actualWorkspace, renameService, expectedSpans) End Function Private Shared Async Function VerifyTaggedSpans(tagType As TextMarkerTag, actualWorkspace As TestWorkspace, renameService As InlineRenameService, expectedTaggedWorkspace As TestWorkspace) As Task Dim expectedSpans = expectedTaggedWorkspace.Documents.Single(Function(d) d.SelectedSpans.Any()).SelectedSpans.Select(Function(ts) ts.ToSpan()) Await VerifyTaggedSpansCore(tagType, actualWorkspace, renameService, expectedSpans) End Function Private Shared Async Function VerifyAnnotatedTaggedSpans(tagType As TextMarkerTag, annotationString As String, actualWorkspace As TestWorkspace, renameService As InlineRenameService, expectedTaggedWorkspace As TestWorkspace) As Task Dim annotatedDocument = expectedTaggedWorkspace.Documents.SingleOrDefault(Function(d) d.AnnotatedSpans.Any()) Dim expectedSpans As IEnumerable(Of Span) If annotatedDocument Is Nothing Then expectedSpans = SpecializedCollections.EmptyEnumerable(Of Span) Else expectedSpans = GetAnnotatedSpans(annotationString, annotatedDocument) End If Await VerifyTaggedSpansCore(tagType, actualWorkspace, renameService, expectedSpans) End Function Private Shared Function GetAnnotatedSpans(annotationString As String, annotatedDocument As TestHostDocument) As IEnumerable(Of Span) Return annotatedDocument.AnnotatedSpans.SelectMany(Function(kvp) If kvp.Key = annotationString Then Return kvp.Value.Select(Function(ts) ts.ToSpan()) End If Return SpecializedCollections.EmptyEnumerable(Of Span) End Function) End Function Private Shared Async Function VerifySpansBeforeConflictResolution(actualWorkspace As TestWorkspace, renameService As InlineRenameService) As Task ' Verify no fixup/resolved non-reference conflict span. Await VerifyEmptyTaggedSpans(HighlightTags.RenameFixupTag.Instance, actualWorkspace, renameService) ' Verify valid reference tags. Await VerifyTaggedSpans(HighlightTags.RenameFieldBackgroundAndBorderTag.Instance, actualWorkspace, renameService) End Function Private Shared Async Function VerifySpansAndBufferForConflictResolution(actualWorkspace As TestWorkspace, renameService As InlineRenameService, resolvedConflictWorkspace As TestWorkspace, session As IInlineRenameSession, Optional sessionCommit As Boolean = False, Optional sessionCancel As Boolean = False) As System.Threading.Tasks.Task Await WaitForRename(actualWorkspace) ' Verify fixup/resolved conflict spans. Await VerifyAnnotatedTaggedSpans(HighlightTags.RenameFixupTag.Instance, "Complexified", actualWorkspace, renameService, resolvedConflictWorkspace) ' Verify valid reference tags. Await VerifyTaggedSpans(HighlightTags.RenameFieldBackgroundAndBorderTag.Instance, actualWorkspace, renameService, resolvedConflictWorkspace) VerifyBufferContentsInWorkspace(actualWorkspace, resolvedConflictWorkspace) If sessionCommit Or sessionCancel Then Assert.True(Not sessionCommit Or Not sessionCancel) If sessionCancel Then session.Cancel() VerifyBufferContentsInWorkspace(actualWorkspace, actualWorkspace) ElseIf sessionCommit Then session.Commit() VerifyBufferContentsInWorkspace(actualWorkspace, resolvedConflictWorkspace) End If End If End Function Private Shared Async Function VerifyTaggedSpansCore(tagType As TextMarkerTag, actualWorkspace As TestWorkspace, renameService As InlineRenameService, expectedSpans As IEnumerable(Of Span)) As Task Dim taggedSpans = Await GetTagsOfType(tagType, actualWorkspace, renameService) Assert.Equal(expectedSpans, taggedSpans) End Function Private Shared Sub VerifyBufferContentsInWorkspace(actualWorkspace As TestWorkspace, expectedWorkspace As TestWorkspace) Dim actualDocs = actualWorkspace.Documents Dim expectedDocs = expectedWorkspace.Documents Assert.Equal(expectedDocs.Count, actualDocs.Count) For i = 0 To actualDocs.Count - 1 Dim actualDocument = actualDocs(i) Dim expectedDocument = expectedDocs(i) Dim actualText = actualDocument.GetTextBuffer().CurrentSnapshot.GetText().Trim() Dim expectedText = expectedDocument.GetTextBuffer().CurrentSnapshot.GetText().Trim() Assert.Equal(expectedText, actualText) Next End Sub <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function ValidTagsDuringSimpleRename(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Goo|] { void Blah() { [|Goo|] f = new [|Goo|](); } } </Document> </Project> </Workspace>, host) Dim renameService = workspace.GetService(Of InlineRenameService)() Dim session = StartSession(workspace) Await VerifyTaggedSpans(HighlightTags.RenameFieldBackgroundAndBorderTag.Instance, workspace, renameService) session.Cancel() End Using End Function <WpfTheory> <WorkItem(922197, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/922197")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function UnresolvableConflictInModifiedDocument(host As RenameTestHost) As System.Threading.Tasks.Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Program { static void Main(string[] {|conflict:args|}, int $$goo) { Goo(c => IsInt({|conflict:goo|}, c)); } private static void Goo(Func&lt;char, bool> p) { } private static void Goo(Func&lt;int, bool> p) { } private static bool IsInt(int goo, char c) { } } </Document> </Project> </Workspace>, host) Dim renameService = workspace.GetService(Of InlineRenameService)() Dim document = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue) Dim location = document.CursorPosition.Value Dim session = StartSession(workspace) document.GetTextBuffer().Replace(New Span(location, 3), "args") Await WaitForRename(workspace) Using renamedWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Program { static void Main(string[] {|conflict:args|}, int args) { Goo(c => IsInt({|conflict:args|}, c)); } private static void Goo(Func&lt;char, bool> p) { } private static void Goo(Func&lt;int, bool> p) { } private static bool IsInt(int goo, char c) { } } </Document> </Project> </Workspace>, host) Dim renamedDocument = renamedWorkspace.Documents.Single() Dim expectedSpans = GetAnnotatedSpans("conflict", renamedDocument) Dim taggedSpans = GetTagsOfType(RenameConflictTag.Instance, renameService, document.GetTextBuffer()) Assert.Equal(expectedSpans, taggedSpans) End Using End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function VerifyLinkedFiles_InterleavedResolvedConflicts(host As RenameTestHost) As System.Threading.Tasks.Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSProj" PreprocessorSymbols="Proj1"> <Document FilePath="C.cs"> public class Class1 { #if Proj2 int fieldclash; #endif int field$$; void M() { int fieldclash = 8; #if Proj1 var a = [|field|]; #elif Proj2 var a = [|field|]; #elif Proj3 var a = field; #endif #if Proj1 var b = [|field|]; #elif Proj2 var b = [|field|]; #elif Proj3 var b = field; #endif } } </Document> </Project> <Project Language="C#" CommonReferences="true" PreprocessorSymbols="Proj2"> <Document IsLinkFile="true" LinkAssemblyName="CSProj" LinkFilePath="C.cs"/> </Project> </Workspace>, host) Dim renameService = workspace.GetService(Of InlineRenameService)() Dim document = workspace.Documents.First(Function(d) d.CursorPosition.HasValue) Dim location = document.CursorPosition.Value Dim session = StartSession(workspace) document.GetTextBuffer().Insert(location, "clash") Await WaitForRename(workspace) Using renamedWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSProj" PreprocessorSymbols="Proj1"> <Document FilePath="C.cs"> public class Class1 { #if Proj2 int fieldclash; #endif int {|valid:fieldclash|}; void M() { int fieldclash = 8; #if Proj1 {|resolved:var a = this.{|valid:fieldclash|};|} #elif Proj2 var a = {|conflict:fieldclash|}; #elif Proj3 var a = field; #endif #if Proj1 {|resolved:var b = this.{|valid:fieldclash|};|} #elif Proj2 var b = {|conflict:fieldclash|}; #elif Proj3 var b = field; #endif } } </Document> </Project> <Project Language="C#" CommonReferences="true" PreprocessorSymbols="Proj2"> <Document IsLinkFile="true" LinkAssemblyName="CSProj" LinkFilePath="C.cs"/> </Project> </Workspace>, host) Dim renamedDocument = renamedWorkspace.Documents.First() Dim expectedSpans = GetAnnotatedSpans("resolved", renamedDocument) Dim taggedSpans = GetTagsOfType(RenameFixupTag.Instance, renameService, document.GetTextBuffer()) Assert.Equal(expectedSpans, taggedSpans) expectedSpans = GetAnnotatedSpans("conflict", renamedDocument) taggedSpans = GetTagsOfType(RenameConflictTag.Instance, renameService, document.GetTextBuffer()) Assert.Equal(expectedSpans, taggedSpans) expectedSpans = GetAnnotatedSpans("valid", renamedDocument) taggedSpans = GetTagsOfType(RenameFieldBackgroundAndBorderTag.Instance, renameService, document.GetTextBuffer()) Assert.Equal(expectedSpans, taggedSpans) End Using End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function VerifyLinkedFiles_UnresolvableConflictComments(host As RenameTestHost) As Task Dim originalDocument = " public class Class1 { #if Proj1 void Test(double x) { } #elif Proj2 void Test(long x) { } #endif void Tes$$(int i) { } void M() { Test(5); } }" Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSProj" PreprocessorSymbols="Proj1"> <Document FilePath="C.cs"><%= originalDocument %></Document> </Project> <Project Language="C#" CommonReferences="true" PreprocessorSymbols="Proj2"> <Document IsLinkFile="true" LinkAssemblyName="CSProj" LinkFilePath="C.cs"/> </Project> </Workspace>, host) Dim renameService = workspace.GetService(Of InlineRenameService)() Dim document = workspace.Documents.First(Function(d) d.CursorPosition.HasValue) Dim location = document.CursorPosition.Value Dim session = StartSession(workspace) document.GetTextBuffer().Insert(location, "t") Await WaitForRename(workspace) Dim expectedDocument = $" public class Class1 {{ #if Proj1 void Test(double x) {{ }} #elif Proj2 void Test(long x) {{ }} #endif void Test(int i) {{ }} void M() {{ {{|conflict:{{|conflict:/* {String.Format(WorkspacesResources.Unmerged_change_from_project_0, "CSharpAssembly1")} {WorkspacesResources.Before_colon} Test(5); {WorkspacesResources.After_colon} Test((long)5); *|}}|}}/ Test((double)5); }} }}" Using renamedWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSProj" PreprocessorSymbols="Proj1"> <Document FilePath="C.cs"><%= expectedDocument %></Document> </Project> <Project Language="C#" CommonReferences="true" PreprocessorSymbols="Proj2"> <Document IsLinkFile="true" LinkAssemblyName="CSProj" LinkFilePath="C.cs"/> </Project> </Workspace>, host) Dim renamedDocument = renamedWorkspace.Documents.First() Dim expectedSpans = GetAnnotatedSpans("conflict", renamedDocument) Dim taggedSpans = GetTagsOfType(RenameConflictTag.Instance, renameService, document.GetTextBuffer()) Assert.Equal(expectedSpans, taggedSpans) End Using End Using End Function <WpfTheory> <WorkItem(922197, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/922197")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function UnresolvableConflictInUnmodifiedDocument(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$A|] { } </Document> <Document FilePath="B.cs"> class {|conflict:B|} { } </Document> </Project> </Workspace>, host) Dim renameService = workspace.GetService(Of InlineRenameService)() Dim location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).GetTextBuffer() Dim session = StartSession(workspace) textBuffer.Replace(New Span(location, 1), "B") Await WaitForRename(workspace) Dim conflictDocument = workspace.Documents.Single(Function(d) d.FilePath = "B.cs") Dim expectedSpans = GetAnnotatedSpans("conflict", conflictDocument) Dim taggedSpans = GetTagsOfType(RenameConflictTag.Instance, renameService, conflictDocument.GetTextBuffer()) Assert.Equal(expectedSpans, taggedSpans) End Using End Function <WpfTheory> <WorkItem(847467, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/847467")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function ValidStateWithEmptyReplacementTextAfterConflictResolution(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$T|] { } </Document> </Project> </Workspace>, host) Dim renameService = workspace.GetService(Of InlineRenameService)() Dim location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() Dim session = StartSession(workspace) textBuffer.Replace(New Span(location, 1), "this") ' Verify @ escaping Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class @[|this|] { } </Document> </Project> </Workspace>, host) Await VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session) End Using textBuffer.Delete(New Span(location + 1, 4)) Await WaitForRename(workspace) ' Verify no escaping Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class { } </Document> </Project> </Workspace>, host) VerifyBufferContentsInWorkspace(workspace, resolvedConflictWorkspace) End Using session.Commit() Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class T { } </Document> </Project> </Workspace>, host) VerifyBufferContentsInWorkspace(workspace, resolvedConflictWorkspace) End Using End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(812789, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/812789")> Public Async Function RenamingEscapedIdentifiers(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void @$$as() { } } </Document> </Project> </Workspace>, host) Dim renameService = workspace.GetService(Of InlineRenameService)() Dim location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim session = StartSession(workspace) Dim textBuffer = workspace.Documents.Single().GetTextBuffer() ' Verify @ escaping is still present Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void @[|as|]() { } } </Document> </Project> </Workspace>, host) Await VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session) End Using textBuffer.Replace(New Span(location, 2), "bar") ' Verify @ escaping is removed Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void [|bar|]() { } } </Document> </Project> </Workspace>, host) Await VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session) End Using End Using End Function <WpfTheory> <WorkItem(812795, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/812795")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function BackspacingAfterConflictResolutionPreservesTrackingSpans(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void Method() { $$Bar(0); } void Goo(int i) { } void Bar(double d) { } } </Document> </Project> </Workspace>, host) Dim view = workspace.Documents.Single().GetTextView() Dim location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() Dim renameService = workspace.GetService(Of InlineRenameService)() Dim editorOperations = workspace.GetService(Of IEditorOperationsFactoryService).GetEditorOperations(view) Dim commandHandler = CreateCommandHandler(workspace) Dim session = StartSession(workspace) textBuffer.Replace(New Span(location, 3), "Goo") Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void Method() { {|Complexified:[|Goo|]((double)0);|} } void Goo(int i) { } void [|Goo|](double d) { } } </Document> </Project> </Workspace>, host) Await VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session) End Using ' Delete Goo and type "as" commandHandler.ExecuteCommand(New BackspaceKeyCommandArgs(view, view.TextBuffer), Sub() editorOperations.Backspace(), Utilities.TestCommandExecutionContext.Create()) commandHandler.ExecuteCommand(New BackspaceKeyCommandArgs(view, view.TextBuffer), Sub() editorOperations.Backspace(), Utilities.TestCommandExecutionContext.Create()) commandHandler.ExecuteCommand(New BackspaceKeyCommandArgs(view, view.TextBuffer), Sub() editorOperations.Backspace(), Utilities.TestCommandExecutionContext.Create()) commandHandler.ExecuteCommand(New TypeCharCommandArgs(view, view.TextBuffer, "a"c), Sub() editorOperations.InsertText("a"), Utilities.TestCommandExecutionContext.Create()) commandHandler.ExecuteCommand(New TypeCharCommandArgs(view, view.TextBuffer, "s"c), Sub() editorOperations.InsertText("s"), Utilities.TestCommandExecutionContext.Create()) Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void Method() { @[|as|](0); } void Goo(int i) { } void @[|as|](double d) { } } </Document> </Project> </Workspace>, host) Await VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session) End Using End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function CSharp_FixupSpanDuringResolvableConflict_NonReferenceConflict(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Goo { int bar; void M(int [|$$goo|]) { var x = [|goo|]; bar = 23; } } </Document> </Project> </Workspace>, host) Dim renameService = workspace.GetService(Of InlineRenameService)() Dim session = StartSession(workspace) Dim textBuffer = workspace.Documents.Single().GetTextBuffer() Dim location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Await VerifySpansBeforeConflictResolution(workspace, renameService) ' Apply edit so that we have a resolved non-reference conflict. textBuffer.Replace(New Span(location, 3), "bar") ' Verify fixup/resolved non-reference conflict span. Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Goo { int bar; void M(int [|bar|]) { var x = [|bar|]; {|Complexified:this.{|Resolved:bar|} = 23;|} } } </Document> </Project> </Workspace>, host) Await VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session) End Using ' Make another edit so that we have no more conflicts. location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value textBuffer.Replace(New Span(location, 3), "baR") Using newWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Goo { int bar; void M(int [|$$baR|]) { var x = [|baR|]; bar = 23; } } </Document> </Project> </Workspace>, host) Await VerifySpansAndBufferForConflictResolution(workspace, renameService, newWorkspace, session, sessionCommit:=True) End Using End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function VisualBasic_FixupSpanDuringResolvableConflict_NonReferenceConflict(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Goo Dim bar As Integer Sub M([|$$goo|] As Integer) Dim x = [|goo|] BAR = 23 End Sub End Class </Document> </Project> </Workspace>, host) Dim renameService = workspace.GetService(Of InlineRenameService)() Dim session = StartSession(workspace) Dim textBuffer = workspace.Documents.Single().GetTextBuffer() Dim location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Await VerifySpansBeforeConflictResolution(workspace, renameService) ' Apply edit so that we have a resolved non-reference conflict. textBuffer.Replace(New Span(location, 3), "bar") ' Verify fixup/resolved non-reference conflict span. Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Goo Dim bar As Integer Sub M([|bar|] As Integer) Dim x = [|bar|] {|Complexified:Me.{|Resolved:BAR|} = 23|} End Sub End Class </Document> </Project> </Workspace>, host) Await VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session) End Using ' Make another edit so that we have no more conflicts. location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value textBuffer.Replace(New Span(location, 3), "boo") Using newWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Goo Dim bar As Integer Sub M([|$$boo|] As Integer) Dim x = [|boo|] BAR = 23 End Sub End Class </Document> </Project> </Workspace>, host) Await VerifySpansAndBufferForConflictResolution(workspace, renameService, newWorkspace, session, sessionCommit:=True) End Using End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function CSharp_FixupSpanDuringResolvableConflict_ReferenceConflict(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Goo { int [|$$goo|]; void M(int bar) { [|goo|] = [|goo|] + bar; } } </Document> </Project> </Workspace>, host) Dim renameService = workspace.GetService(Of InlineRenameService)() Dim session = StartSession(workspace) Dim textBuffer = workspace.Documents.Single().GetTextBuffer() Dim location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Await VerifySpansBeforeConflictResolution(workspace, renameService) ' Apply edit so that we have a resolved reference conflict. textBuffer.Replace(New Span(location, 3), "bar") ' Verify fixup/resolved conflict span. Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Goo { int [|bar|]; void M(int bar) { {|Complexified:this.{|Resolved:[|bar|]|} = this.{|Resolved:[|bar|]|} + bar;|} } } </Document> </Project> </Workspace>, host) Await VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session) End Using textBuffer.Replace(New Span(location, 3), "ba") Using newWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Goo { int [|$$ba|]; void M(int bar) { [|ba|] = [|ba|] + bar; } } </Document> </Project> </Workspace>, host) Await VerifySpansAndBufferForConflictResolution(workspace, renameService, newWorkspace, session, sessionCancel:=True) End Using End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function VisualBasic_FixupSpanDuringResolvableConflict_ReferenceConflict(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Goo Dim [|$$goo|] As Integer Sub M(bar As Integer) [|goo|] = [|goo|] + bar End Sub End Class </Document> </Project> </Workspace>, host) Dim renameService = workspace.GetService(Of InlineRenameService)() Dim session = StartSession(workspace) Dim textBuffer = workspace.Documents.Single().GetTextBuffer() Dim location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Await VerifySpansBeforeConflictResolution(workspace, renameService) ' Apply edit so that we have a resolved reference conflict. textBuffer.Replace(New Span(location, 3), "bar") ' Verify fixup/resolved conflict span. Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Goo Dim [|bar|] As Integer Sub M(bar As Integer) {|Complexified:Me.{|Resolved:[|bar|]|} = Me.{|Resolved:[|bar|]|} + bar|} End Sub End Class </Document> </Project> </Workspace>, host) Await VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session) End Using ' Make another edit so that we have no more conflicts. textBuffer.Replace(New Span(location, 3), "ba") Using newWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Goo Dim [|$$ba|] As Integer Sub M(bar As Integer) [|ba|] = [|ba|] + bar End Sub End Class </Document> </Project> </Workspace>, host) Await VerifySpansAndBufferForConflictResolution(workspace, renameService, newWorkspace, session, sessionCancel:=True) End Using End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function CSharp_FixupSpanDuringResolvableConflict_NeedsEscaping(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Goo { int @int; void M(int [|$$goo|]) { var x = [|goo|]; @int = 23; } } </Document> </Project> </Workspace>, host) Dim renameService = workspace.GetService(Of InlineRenameService)() Dim session = StartSession(workspace) Dim textBuffer = workspace.Documents.Single().GetTextBuffer() Dim location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Await VerifySpansBeforeConflictResolution(workspace, renameService) ' Apply edit so that we have a resolved escaping conflict. textBuffer.Replace(New Span(location, 3), "int") ' Verify fixup/resolved conflict span. Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Goo { int @int; void M(int {|Resolved:@[|int|]|}) { var x = {|Resolved:@[|int|]|}; {|Complexified:this.{|Resolved:@int|} = 23;|} } } </Document> </Project> </Workspace>, host) Await VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session) End Using ' Make another edit to change "int" to "@in" so that we have no more conflicts, just escaping. textBuffer.Replace(New Span(location + 1, 3), "in") ' Verify resolved escaping conflict spans. Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Goo { int @int; void M(int {|Resolved:@[|in|]|}) { var x = {|Resolved:@[|in|]|}; @int = 23; } } </Document> </Project> </Workspace>, host) Await VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session, sessionCommit:=True) End Using End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function VisualBasic_FixupSpanDuringResolvableConflict_NeedsEscaping(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Goo Dim [New] As Integer Sub M([|$$goo|] As Integer) Dim x = [|goo|] [NEW] = 23 End Sub End Class </Document> </Project> </Workspace>, host) Dim renameService = workspace.GetService(Of InlineRenameService)() Dim session = StartSession(workspace) Dim textBuffer = workspace.Documents.Single().GetTextBuffer() Dim location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Await VerifySpansBeforeConflictResolution(workspace, renameService) ' Apply edit so that we have a resolved escaping conflict. textBuffer.Replace(New Span(location, 3), "New") ' Verify fixup/resolved conflict span. Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Goo Dim [New] As Integer Sub M({|Resolved:[[|New|]]|} As Integer) Dim x = {|Resolved:[[|New|]]|} {|Complexified:Me.{|Resolved:[NEW]|} = 23|} End Sub End Class </Document> </Project> </Workspace>, host) Await VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session) End Using ' Make another edit to change "New" to "[Do]" so that we have no more conflicts, just escaping. textBuffer.Replace(New Span(location + 1, 3), "Do") ' Verify resolved escaping conflict spans. Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Goo Dim [New] As Integer Sub M({|Resolved:[[|Do|]]|} As Integer) Dim x = {|Resolved:[[|Do|]]|} [NEW] = 23 End Sub End Class </Document> </Project> </Workspace>, host) Await VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session, sessionCommit:=True) End Using End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function FixupSpanDuringResolvableConflict_VerifyCaret(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Goo Sub [|N$$w|](goo As Integer) End Sub End Class </Document> </Project> </Workspace>, host) Dim view = workspace.Documents.Single().GetTextView() Dim editorOperations = workspace.GetService(Of IEditorOperationsFactoryService).GetEditorOperations(view) Dim commandHandler = CreateCommandHandler(workspace) Dim textViewService = Assert.IsType(Of TextBufferAssociatedViewService)(workspace.ExportProvider.GetExportedValue(Of ITextBufferAssociatedViewService)()) Dim buffers = New Collection(Of ITextBuffer) buffers.Add(view.TextBuffer) DirectCast(textViewService, ITextViewConnectionListener).SubjectBuffersConnected(view, ConnectionReason.TextViewLifetime, buffers) Dim renameService = workspace.GetService(Of InlineRenameService)() Dim session = StartSession(workspace) Await VerifySpansBeforeConflictResolution(workspace, renameService) ' Type first in the main identifier view.Selection.Clear() view.Caret.MoveTo(New SnapshotPoint(view.TextBuffer.CurrentSnapshot, workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value)) commandHandler.ExecuteCommand(New TypeCharCommandArgs(view, view.TextBuffer, "e"c), Sub() editorOperations.InsertText("e"), Utilities.TestCommandExecutionContext.Create()) ' Verify fixup/resolved conflict span. Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Goo Sub [[|Ne$$w|]](goo As Integer) End Sub End Class </Document> </Project> </Workspace>, host) Await VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session) Dim location = view.Caret.Position.BufferPosition.Position Dim expectedLocation = resolvedConflictWorkspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Assert.Equal(expectedLocation, location) End Using ' Make another edit to change "New" to "Nexw" so that we have no more conflicts or escaping. commandHandler.ExecuteCommand(New TypeCharCommandArgs(view, view.TextBuffer, "x"c), Sub() editorOperations.InsertText("x"), Utilities.TestCommandExecutionContext.Create()) ' Verify resolved escaping conflict spans. Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Goo Sub [|Nex$$w|](goo As Integer) End Sub End Class </Document> </Project> </Workspace>, host) Await VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session) Dim location = view.Caret.Position.BufferPosition.Position Dim expectedLocation = resolvedConflictWorkspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Assert.Equal(expectedLocation, location) End Using End Using End Function <WpfTheory> <WorkItem(771743, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/771743")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function VerifyNoSelectionAfterCommit(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Goo Sub [|M$$ain|](goo As Integer) End Sub End Class </Document> </Project> </Workspace>, host) Dim view = workspace.Documents.Single().GetTextView() Dim editorOperations = workspace.GetService(Of IEditorOperationsFactoryService).GetEditorOperations(view) Dim commandHandler = CreateCommandHandler(workspace) Dim textViewService = Assert.IsType(Of TextBufferAssociatedViewService)(workspace.ExportProvider.GetExportedValue(Of ITextBufferAssociatedViewService)()) Dim buffers = New Collection(Of ITextBuffer) buffers.Add(view.TextBuffer) DirectCast(textViewService, ITextViewConnectionListener).SubjectBuffersConnected(view, ConnectionReason.TextViewLifetime, buffers) Dim location = view.Caret.Position.BufferPosition.Position view.Selection.Select(New SnapshotSpan(view.Caret.Position.BufferPosition, 2), False) Dim renameService = workspace.GetService(Of InlineRenameService)() Dim session = StartSession(workspace) Await VerifySpansBeforeConflictResolution(workspace, renameService) ' Type few characters. view.Caret.MoveTo(New SnapshotPoint(view.TextBuffer.CurrentSnapshot, workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value)) commandHandler.ExecuteCommand(New TypeCharCommandArgs(view, view.TextBuffer, "e"c), Sub() editorOperations.InsertText("e"), Utilities.TestCommandExecutionContext.Create()) commandHandler.ExecuteCommand(New TypeCharCommandArgs(view, view.TextBuffer, "f"c), Sub() editorOperations.InsertText("f"), Utilities.TestCommandExecutionContext.Create()) commandHandler.ExecuteCommand(New TypeCharCommandArgs(view, view.TextBuffer, "g"c), Sub() editorOperations.InsertText("g"), Utilities.TestCommandExecutionContext.Create()) session.Commit() Dim selectionLength = view.Selection.End.Position - view.Selection.Start.Position Assert.Equal(0, selectionLength) End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function CSharp_FixupSpanDuringResolvableConflict_ComplexificationOutsideConflict(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Program { static void Main(string[] args) { int x = [|$$Bar|](Goo([|Bar|](0))); } static int Goo(int i) { return 0; } static int [|Bar|](double d) { return 1; } } </Document> </Project> </Workspace>, host) Dim renameService = workspace.GetService(Of InlineRenameService)() Dim session = StartSession(workspace) Dim textBuffer = workspace.Documents.Single().GetTextBuffer() Dim location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Await VerifySpansBeforeConflictResolution(workspace, renameService) ' Apply edit so that we have a resolved reference conflict. textBuffer.Replace(New Span(location, 3), "Goo") ' Verify fixup/resolved conflict span. Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Program { static void Main(string[] args) { {|Complexified:int x = {|Resolved:[|Goo|]|}((double)Goo({|Resolved:[|Goo|]|}((double)0)));|} } static int Goo(int i) { return 0; } static int [|Goo|](double d) { return 1; } } </Document> </Project> </Workspace>, host) Await VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session) End Using ' Make another edit so that we have no more conflicts. textBuffer.Replace(New Span(location, 3), "GOO") Using newWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Program { static void Main(string[] args) { int x = [|$$GOO|](Goo([|GOO|](0))); } static int Goo(int i) { return 0; } static int [|GOO|](double d) { return 1; } } </Document> </Project> </Workspace>, host) Await VerifySpansAndBufferForConflictResolution(workspace, renameService, newWorkspace, session, sessionCommit:=True) End Using End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function CSharp_FixupSpanDuringResolvableConflict_ContainedComplexifiedSpan(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ using System; namespace N { class A<T> { public virtual void Goo(T x) { } class B<S> : A<B<S>> { class [|$$C|]<U> : B<[|C|]<U>> // Rename C to A { public override void Goo(A<A<T>.B<S>>.B<A<T>.B<S>.[|C|]<U>> x) { } } } } } ]]> </Document> </Project> </Workspace>, host) Dim renameService = workspace.GetService(Of InlineRenameService)() Dim session = StartSession(workspace) Dim textBuffer = workspace.Documents.Single().GetTextBuffer() Dim location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Await VerifySpansBeforeConflictResolution(workspace, renameService) ' Apply edit so that we have a resolved reference conflict. textBuffer.Replace(New Span(location, 1), "A") ' Verify fixup/resolved conflict span. Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ using System; namespace N { class A<T> { public virtual void Goo(T x) { } class B<S> : A<B<S>> { class [|A|]<U> : B<[|A|]<U>> // Rename C to A { public override void Goo({|Complexified:N.{|Resolved:A|}<N.{|Resolved:A|}<T>.B<S>>|}.B<{|Complexified:N.{|Resolved:A|}<T>|}.B<S>.[|A|]<U>> x) { } } } } } ]]> </Document> </Project> </Workspace>, host) Await VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session, sessionCommit:=True) End Using End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(8334, "https://github.com/dotnet/roslyn/issues/8334")> Public Async Function CSharp_FixupSpanDuringResolvableConflict_ComplexificationReordersReferenceSpans(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> static class E { public static C [|$$Goo|](this C x, int tag) { return new C(); } } class C { C Bar(int tag) { return this.[|Goo|](1).[|Goo|](2); } } </Document> </Project> </Workspace>, host) Dim renameService = workspace.GetService(Of InlineRenameService)() Dim session = StartSession(workspace) Dim textBuffer = workspace.Documents.Single().GetTextBuffer() Dim location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Await VerifySpansBeforeConflictResolution(workspace, renameService) ' Apply edit so that we have a resolved reference conflict. textBuffer.Replace(New Span(location, 3), "Bar") ' Verify fixup/resolved conflict span. Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> static class E { public static C [|Bar|](this C x, int tag) { return new C(); } } class C { C Bar(int tag) { {|Complexified:return E.{|Resolved:[|Bar|]|}(E.{|Resolved:[|Bar|]|}(this, 1), 2);|} } } </Document> </Project> </Workspace>, host) Await VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session, sessionCommit:=True) End Using End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function CSharp_FixupSpanDuringResolvableConflict_WithinCrefs(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ using System; using F = N; namespace N { interface I { void Goo(); } } class C { class E : F.I { /// <summary> /// This is a function <see cref="F.I.Goo"/> /// </summary> public void Goo() { } } class [|$$K|] { } } ]]> </Document> </Project> </Workspace>, host) Dim renameService = workspace.GetService(Of InlineRenameService)() Dim session = StartSession(workspace) Dim textBuffer = workspace.Documents.Single().GetTextBuffer() Dim location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Await VerifySpansBeforeConflictResolution(workspace, renameService) ' Apply edit so that we have a resolved reference conflict. textBuffer.Replace(New Span(location, 1), "F") ' Verify fixup/resolved conflict span. Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ using System; using F = N; namespace N { interface I { void Goo(); } } class C { class E : {|Complexified:{|Resolved:N|}|}.I { /// <summary> /// This is a function <see cref="{|Complexified:{|Resolved:N|}|}.I.Goo"/> /// </summary> public void Goo() { } } class [|$$F|] { } } ]]> </Document> </Project> </Workspace>, host) Await VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session, sessionCommit:=True) End Using End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function CSharp_FixupSpanDuringResolvableConflict_OverLoadResolutionChangesInEnclosingInvocations(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ using System; static class C { static void Ex(this string x) { } static void Outer(Action<string> x, object y) { Console.WriteLine(1); } static void Outer(Action<int> x, int y) { Console.WriteLine(2); } static void Inner(Action<string> x, string y) { } static void Inner(Action<string> x, int y) { } static void Inner(Action<int> x, int y) { } static void Main() { Outer(y => Inner(x => x.Ex(), y), 0); } } static class E { public static void [|$$Ex|](this int x) { } // Rename Ex to Goo } ]]> </Document> </Project> </Workspace>, host) Dim renameService = workspace.GetService(Of InlineRenameService)() Dim session = StartSession(workspace) Dim textBuffer = workspace.Documents.Single().GetTextBuffer() Dim location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Await VerifySpansBeforeConflictResolution(workspace, renameService) ' Apply edit so that we have a resolved reference conflict. textBuffer.Replace(New Span(location, 2), "Goo") ' Verify fixup/resolved conflict span. Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ using System; static class C { static void Ex(this string x) { } static void Outer(Action<string> x, object y) { Console.WriteLine(1); } static void Outer(Action<int> x, int y) { Console.WriteLine(2); } static void Inner(Action<string> x, string y) { } static void Inner(Action<string> x, int y) { } static void Inner(Action<int> x, int y) { } static void Main() { {|Complexified:{|Resolved:Outer|}((string y) => {|Resolved:Inner|}(x => x.Ex(), y), 0);|} } } static class E { public static void [|Goo|](this int x) { } // Rename Ex to Goo } ]]> </Document> </Project> </Workspace>, host) Await VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session, sessionCommit:=True) End Using End Using End Function <WpfTheory> <WorkItem(530817, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530817")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function CSharpShowDeclarationConflictsImmediately(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Program { static void Main(string[] args) { const int {|valid:$$V|} = 5; int {|conflict:V|} = 99; } } </Document> </Project> </Workspace>, host) Dim renameService = workspace.GetService(Of InlineRenameService)() Dim session = StartSession(workspace) Dim validTaggedSpans = Await GetTagsOfType(HighlightTags.RenameFieldBackgroundAndBorderTag.Instance, workspace, renameService) Dim validExpectedSpans = workspace.Documents.Single(Function(d) d.AnnotatedSpans.Count > 0).AnnotatedSpans("valid").Select(Function(ts) ts.ToSpan()) Dim conflictTaggedSpans = Await GetTagsOfType(RenameConflictTag.Instance, workspace, renameService) Dim conflictExpectedSpans = workspace.Documents.Single(Function(d) d.AnnotatedSpans.Count > 0).AnnotatedSpans("conflict").Select(Function(ts) ts.ToSpan()) session.Cancel() AssertEx.Equal(validExpectedSpans, validTaggedSpans) AssertEx.Equal(conflictExpectedSpans, conflictTaggedSpans) End Using End Function <WpfTheory> <WorkItem(530817, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530817")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function VBShowDeclarationConflictsImmediately(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Goo Sub Bar() Dim {|valid:$$V|} as Integer Dim {|conflict:V|} as String End Sub End Class </Document> </Project> </Workspace>, host) Dim renameService = workspace.GetService(Of InlineRenameService)() Dim session = StartSession(workspace) Dim validTaggedSpans = Await GetTagsOfType(HighlightTags.RenameFieldBackgroundAndBorderTag.Instance, workspace, renameService) Dim validExpectedSpans = workspace.Documents.Single(Function(d) d.AnnotatedSpans.Count > 0).AnnotatedSpans("valid").Select(Function(ts) ts.ToSpan()) Dim conflictTaggedSpans = Await GetTagsOfType(RenameConflictTag.Instance, workspace, renameService) Dim conflictExpectedSpans = workspace.Documents.Single(Function(d) d.AnnotatedSpans.Count > 0).AnnotatedSpans("conflict").Select(Function(ts) ts.ToSpan()) session.Cancel() AssertEx.Equal(validExpectedSpans, validTaggedSpans) AssertEx.Equal(conflictExpectedSpans, conflictTaggedSpans) End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function ActiveSpanInSecondaryView(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class [|$$Goo|] End Class </Document> <Document> ' [|Goo|] </Document> </Project> </Workspace>, host) Dim renameService = workspace.GetService(Of InlineRenameService)() Dim location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents(0).GetTextBuffer() Dim session = StartSession(workspace) session.RefreshRenameSessionWithOptionsChanged(CodeAnalysis.Rename.RenameOptions.RenameInComments, newValue:=True) Await WaitForRename(workspace) session.RefreshRenameSessionWithOptionsChanged(CodeAnalysis.Rename.RenameOptions.RenameInComments, newValue:=False) Await WaitForRename(workspace) textBuffer.Replace(New Span(location, 3), "Bar") Await WaitForRename(workspace) End Using End Function Private Shared Async Function GetTagsOfType(expectedTagType As ITextMarkerTag, workspace As TestWorkspace, renameService As InlineRenameService) As Task(Of IEnumerable(Of Span)) Dim textBuffer = workspace.Documents.Single().GetTextBuffer() Await WaitForRename(workspace) Return GetTagsOfType(expectedTagType, renameService, textBuffer) End Function Private Shared Function GetTagsOfType(expectedTagType As ITextMarkerTag, renameService As InlineRenameService, textBuffer As ITextBuffer) As IEnumerable(Of Span) Dim tagger = New RenameTagger(textBuffer, renameService) Dim tags = tagger.GetTags(textBuffer.CurrentSnapshot.GetSnapshotSpanCollection()) Return (From tag In tags Where tag.Tag Is expectedTagType Order By tag.Span.Start Select tag.Span.Span).ToList() End Function End Class End Namespace
-1
dotnet/roslyn
56,011
React to string comparison changing on .NET Core
The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
jaredpar
"2021-08-30T17:18:52Z"
"2021-08-30T20:20:04Z"
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
4d99cda6e446e77dbb302e26388c1093bd3ef569
React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
./src/Features/VisualBasic/Portable/Completion/KeywordRecommenders/OnErrorStatements/NextKeywordRecommender.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis.Completion.Providers Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.OnErrorStatements ''' <summary> ''' Recommends "Next" after "On Error Resume" or after the "Resume" statement ''' </summary> Friend Class NextKeywordRecommender Inherits AbstractKeywordRecommender Private Shared ReadOnly s_keywords As ImmutableArray(Of RecommendedKeyword) = ImmutableArray.Create(New RecommendedKeyword("Next", VBFeaturesResources.When_a_run_time_error_occurs_execution_transfers_to_the_statement_following_the_statement_or_procedure_call_that_resulted_in_the_error)) Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword) If context.FollowsEndOfStatement Then Return ImmutableArray(Of RecommendedKeyword).Empty End If Dim targetToken = context.TargetToken Return If(targetToken.IsKind(SyntaxKind.ResumeKeyword) AndAlso Not context.IsInLambda AndAlso targetToken.Parent.IsKind(SyntaxKind.OnErrorResumeNextStatement, SyntaxKind.ResumeStatement, SyntaxKind.ResumeNextStatement), s_keywords, ImmutableArray(Of RecommendedKeyword).Empty) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis.Completion.Providers Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.OnErrorStatements ''' <summary> ''' Recommends "Next" after "On Error Resume" or after the "Resume" statement ''' </summary> Friend Class NextKeywordRecommender Inherits AbstractKeywordRecommender Private Shared ReadOnly s_keywords As ImmutableArray(Of RecommendedKeyword) = ImmutableArray.Create(New RecommendedKeyword("Next", VBFeaturesResources.When_a_run_time_error_occurs_execution_transfers_to_the_statement_following_the_statement_or_procedure_call_that_resulted_in_the_error)) Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword) If context.FollowsEndOfStatement Then Return ImmutableArray(Of RecommendedKeyword).Empty End If Dim targetToken = context.TargetToken Return If(targetToken.IsKind(SyntaxKind.ResumeKeyword) AndAlso Not context.IsInLambda AndAlso targetToken.Parent.IsKind(SyntaxKind.OnErrorResumeNextStatement, SyntaxKind.ResumeStatement, SyntaxKind.ResumeNextStatement), s_keywords, ImmutableArray(Of RecommendedKeyword).Empty) End Function End Class End Namespace
-1
dotnet/roslyn
56,011
React to string comparison changing on .NET Core
The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
jaredpar
"2021-08-30T17:18:52Z"
"2021-08-30T20:20:04Z"
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
4d99cda6e446e77dbb302e26388c1093bd3ef569
React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
./src/Compilers/VisualBasic/Portable/Symbols/Wrapped/WrappedPropertySymbol.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Globalization Imports System.Threading Imports Microsoft.Cci Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ''' <summary> ''' Represents a property that is based on another property. ''' When inheriting from this class, one shouldn't assume that ''' the default behavior it has is appropriate for every case. ''' That behavior should be carefully reviewed and derived type ''' should override behavior as appropriate. ''' </summary> Friend MustInherit Class WrappedPropertySymbol Inherits PropertySymbol Protected _underlyingProperty As PropertySymbol Public ReadOnly Property UnderlyingProperty As PropertySymbol Get Return Me._underlyingProperty End Get End Property Public Overrides ReadOnly Property IsImplicitlyDeclared As Boolean Get Return Me._underlyingProperty.IsImplicitlyDeclared End Get End Property Public Overrides ReadOnly Property ReturnsByRef As Boolean Get Return Me._underlyingProperty.ReturnsByRef End Get End Property Public Overrides ReadOnly Property IsDefault As Boolean Get Return Me._underlyingProperty.IsDefault End Get End Property Friend Overrides ReadOnly Property CallingConvention As CallingConvention Get Return Me._underlyingProperty.CallingConvention End Get End Property Public Overrides ReadOnly Property Name As String Get Return Me._underlyingProperty.Name End Get End Property Friend Overrides ReadOnly Property HasSpecialName As Boolean Get Return Me._underlyingProperty.HasSpecialName End Get End Property Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location) Get Return Me._underlyingProperty.Locations End Get End Property Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Get Return Me._underlyingProperty.DeclaringSyntaxReferences End Get End Property Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility Get Return Me._underlyingProperty.DeclaredAccessibility End Get End Property Public Overrides ReadOnly Property IsShared As Boolean Get Return Me._underlyingProperty.IsShared End Get End Property Public Overrides ReadOnly Property IsOverridable As Boolean Get Return Me._underlyingProperty.IsOverridable End Get End Property Public Overrides ReadOnly Property IsOverrides As Boolean Get Return Me._underlyingProperty.IsOverrides End Get End Property Public Overrides ReadOnly Property IsMustOverride As Boolean Get Return Me._underlyingProperty.IsMustOverride End Get End Property Public Overrides ReadOnly Property IsNotOverridable As Boolean Get Return Me._underlyingProperty.IsNotOverridable End Get End Property Friend Overrides ReadOnly Property ObsoleteAttributeData As ObsoleteAttributeData Get Return Me._underlyingProperty.ObsoleteAttributeData End Get End Property Public Overrides ReadOnly Property MetadataName As String Get Return Me._underlyingProperty.MetadataName End Get End Property Friend Overrides ReadOnly Property HasRuntimeSpecialName As Boolean Get Return Me._underlyingProperty.HasRuntimeSpecialName End Get End Property Public Sub New(underlyingProperty As PropertySymbol) Debug.Assert(underlyingProperty IsNot Nothing) Me._underlyingProperty = underlyingProperty End Sub Public Overrides Function GetDocumentationCommentXml(Optional preferredCulture As CultureInfo = Nothing, Optional expandIncludes As Boolean = False, Optional cancellationToken As CancellationToken = Nothing) As String Return Me._underlyingProperty.GetDocumentationCommentXml(preferredCulture, expandIncludes, cancellationToken) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Globalization Imports System.Threading Imports Microsoft.Cci Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ''' <summary> ''' Represents a property that is based on another property. ''' When inheriting from this class, one shouldn't assume that ''' the default behavior it has is appropriate for every case. ''' That behavior should be carefully reviewed and derived type ''' should override behavior as appropriate. ''' </summary> Friend MustInherit Class WrappedPropertySymbol Inherits PropertySymbol Protected _underlyingProperty As PropertySymbol Public ReadOnly Property UnderlyingProperty As PropertySymbol Get Return Me._underlyingProperty End Get End Property Public Overrides ReadOnly Property IsImplicitlyDeclared As Boolean Get Return Me._underlyingProperty.IsImplicitlyDeclared End Get End Property Public Overrides ReadOnly Property ReturnsByRef As Boolean Get Return Me._underlyingProperty.ReturnsByRef End Get End Property Public Overrides ReadOnly Property IsDefault As Boolean Get Return Me._underlyingProperty.IsDefault End Get End Property Friend Overrides ReadOnly Property CallingConvention As CallingConvention Get Return Me._underlyingProperty.CallingConvention End Get End Property Public Overrides ReadOnly Property Name As String Get Return Me._underlyingProperty.Name End Get End Property Friend Overrides ReadOnly Property HasSpecialName As Boolean Get Return Me._underlyingProperty.HasSpecialName End Get End Property Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location) Get Return Me._underlyingProperty.Locations End Get End Property Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Get Return Me._underlyingProperty.DeclaringSyntaxReferences End Get End Property Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility Get Return Me._underlyingProperty.DeclaredAccessibility End Get End Property Public Overrides ReadOnly Property IsShared As Boolean Get Return Me._underlyingProperty.IsShared End Get End Property Public Overrides ReadOnly Property IsOverridable As Boolean Get Return Me._underlyingProperty.IsOverridable End Get End Property Public Overrides ReadOnly Property IsOverrides As Boolean Get Return Me._underlyingProperty.IsOverrides End Get End Property Public Overrides ReadOnly Property IsMustOverride As Boolean Get Return Me._underlyingProperty.IsMustOverride End Get End Property Public Overrides ReadOnly Property IsNotOverridable As Boolean Get Return Me._underlyingProperty.IsNotOverridable End Get End Property Friend Overrides ReadOnly Property ObsoleteAttributeData As ObsoleteAttributeData Get Return Me._underlyingProperty.ObsoleteAttributeData End Get End Property Public Overrides ReadOnly Property MetadataName As String Get Return Me._underlyingProperty.MetadataName End Get End Property Friend Overrides ReadOnly Property HasRuntimeSpecialName As Boolean Get Return Me._underlyingProperty.HasRuntimeSpecialName End Get End Property Public Sub New(underlyingProperty As PropertySymbol) Debug.Assert(underlyingProperty IsNot Nothing) Me._underlyingProperty = underlyingProperty End Sub Public Overrides Function GetDocumentationCommentXml(Optional preferredCulture As CultureInfo = Nothing, Optional expandIncludes As Boolean = False, Optional cancellationToken As CancellationToken = Nothing) As String Return Me._underlyingProperty.GetDocumentationCommentXml(preferredCulture, expandIncludes, cancellationToken) End Function End Class End Namespace
-1
dotnet/roslyn
56,011
React to string comparison changing on .NET Core
The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
jaredpar
"2021-08-30T17:18:52Z"
"2021-08-30T20:20:04Z"
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
4d99cda6e446e77dbb302e26388c1093bd3ef569
React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
./src/Compilers/VisualBasic/Portable/Symbols/UnsupportedMetadataTypeSymbol.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Generic Imports System.Collections.ObjectModel Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports System.Reflection.Metadata Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Friend NotInheritable Class UnsupportedMetadataTypeSymbol Inherits ErrorTypeSymbol Private ReadOnly _mrEx As BadImageFormatException Public Sub New(Optional mrEx As BadImageFormatException = Nothing) _mrEx = mrEx End Sub Public Sub New(explanation As String) ' TODO: Do we want to do anything with the "explanation". C# uses it in error messages ' TODO: and it seems worth no losing it in cases. ' TODO: If so, we need to go back and fill in cases that call the parameterless ' TODO: constructor. End Sub Friend Overrides ReadOnly Property MangleName As Boolean Get Return False End Get End Property Friend Overrides ReadOnly Property ErrorInfo As DiagnosticInfo Get Return ErrorFactory.ErrorInfo(ERRID.ERR_UnsupportedType1, String.Empty) End Get End Property End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Generic Imports System.Collections.ObjectModel Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports System.Reflection.Metadata Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Friend NotInheritable Class UnsupportedMetadataTypeSymbol Inherits ErrorTypeSymbol Private ReadOnly _mrEx As BadImageFormatException Public Sub New(Optional mrEx As BadImageFormatException = Nothing) _mrEx = mrEx End Sub Public Sub New(explanation As String) ' TODO: Do we want to do anything with the "explanation". C# uses it in error messages ' TODO: and it seems worth no losing it in cases. ' TODO: If so, we need to go back and fill in cases that call the parameterless ' TODO: constructor. End Sub Friend Overrides ReadOnly Property MangleName As Boolean Get Return False End Get End Property Friend Overrides ReadOnly Property ErrorInfo As DiagnosticInfo Get Return ErrorFactory.ErrorInfo(ERRID.ERR_UnsupportedType1, String.Empty) End Get End Property End Class End Namespace
-1
dotnet/roslyn
56,011
React to string comparison changing on .NET Core
The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
jaredpar
"2021-08-30T17:18:52Z"
"2021-08-30T20:20:04Z"
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
4d99cda6e446e77dbb302e26388c1093bd3ef569
React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
./src/Compilers/VisualBasic/Test/Emit/Attributes/AttributeTests_MarshalAs.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System Imports System.Collections.Generic Imports System.Runtime.InteropServices Imports System.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.Test.Utilities Imports Roslyn.Test.Utilities Imports Roslyn.Utilities Imports Xunit Imports TypeKind = Microsoft.CodeAnalysis.TypeKind Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Public Class AttributeTests_MarshalAs Inherits BasicTestBase #Region "Helpers" Private Sub VerifyFieldMetadataDecoding(verifier As CompilationVerifier, blobs As Dictionary(Of String, Byte())) Dim count = 0 Using assembly = AssemblyMetadata.CreateFromImage(verifier.EmittedAssemblyData) Dim c = VisualBasicCompilation.Create("c", syntaxTrees:=New VisualBasicSyntaxTree() {}, references:={assembly.GetReference()}) For Each typeSym As NamedTypeSymbol In c.GlobalNamespace.GetMembers().Where(Function(s) s.Kind = SymbolKind.NamedType) Dim fields = typeSym.GetMembers().Where(Function(s) s.Kind = SymbolKind.Field) For Each field As FieldSymbol In fields Assert.Null(field.MarshallingInformation) Dim blob = blobs(field.Name) If blob IsNot Nothing AndAlso blob(0) <= &H50 Then Assert.Equal(CType(blob(0), UnmanagedType), field.MarshallingType) Else Assert.Equal(CType(0, UnmanagedType), field.MarshallingType) End If count = count + 1 Next Next End Using Assert.True(count > 0, "Expected at least one field") End Sub Private Sub VerifyParameterMetadataDecoding(verifier As CompilationVerifier, blobs As Dictionary(Of String, Byte())) Dim count = 0 Using assembly = AssemblyMetadata.CreateFromImage(verifier.EmittedAssemblyData) Dim c = VisualBasicCompilation.Create("c", syntaxTrees:=New VisualBasicSyntaxTree() {}, references:={assembly.GetReference()}) For Each typeSym As NamedTypeSymbol In c.GlobalNamespace.GetMembers().Where(Function(s) s.Kind = SymbolKind.NamedType) Dim methods = typeSym.GetMembers().Where(Function(s) s.Kind = SymbolKind.Method) For Each method As MethodSymbol In methods For Each parameter In method.Parameters Assert.Null(parameter.MarshallingInformation) Dim blob = blobs(method.Name & ":" & parameter.Name) If blob IsNot Nothing AndAlso blob(0) <= &H50 Then Assert.Equal(CType(blob(0), UnmanagedType), parameter.MarshallingType) Else Assert.Equal(CType(0, UnmanagedType), parameter.MarshallingType) End If count = count + 1 Next Next Next End Using Assert.True(count > 0, "Expected at least one parameter") End Sub #End Region ''' <summary> ''' type only, others ignored, field type ignored ''' </summary> <Fact> Public Sub SimpleTypes() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Public Class X <MarshalAs(CShort(0))> Public ZeroShort As X <MarshalAs(DirectCast(0, UnmanagedType))> Public Zero As X <MarshalAs(DirectCast(&H1FFFFFFF, UnmanagedType))> Public MaxValue As X <MarshalAs(DirectCast((&H123456), UnmanagedType))> Public _0x123456 As X <MarshalAs(DirectCast((&H1000), UnmanagedType))> Public _0x1000 As X <MarshalAs(UnmanagedType.AnsiBStr, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public AnsiBStr As X <MarshalAs(UnmanagedType.AsAny, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public AsAny As Double <MarshalAs(UnmanagedType.Bool, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public Bool As X <MarshalAs(UnmanagedType.BStr, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public BStr As X <MarshalAs(UnmanagedType.Currency, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public Currency As Integer <MarshalAs(UnmanagedType.[Error], ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public [Error] As Integer <MarshalAs(UnmanagedType.FunctionPtr, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public FunctionPtr As Integer <MarshalAs(UnmanagedType.I1, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public I1 As Integer <MarshalAs(UnmanagedType.I2, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public I2 As Integer <MarshalAs(UnmanagedType.I4, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public I4 As Integer <MarshalAs(UnmanagedType.I8, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public I8 As Integer <MarshalAs(UnmanagedType.LPStr, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public LPStr As Integer <MarshalAs(UnmanagedType.LPStruct, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public LPStruct As Integer <MarshalAs(UnmanagedType.LPTStr, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public LPTStr As Integer <MarshalAs(UnmanagedType.LPWStr, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public LPWStr As Integer <MarshalAs(UnmanagedType.R4, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public R4 As Integer <MarshalAs(UnmanagedType.R8, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public R8 As Integer <MarshalAs(UnmanagedType.Struct, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public Struct As Integer <MarshalAs(UnmanagedType.SysInt, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public SysInt As Decimal <MarshalAs(UnmanagedType.SysUInt, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public SysUInt As Integer() <MarshalAs(UnmanagedType.TBStr, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public TBStr As Object() <MarshalAs(UnmanagedType.U1, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public U1 As Integer <MarshalAs(UnmanagedType.U2, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public U2 As Double <MarshalAs(UnmanagedType.U4, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public U4 As Boolean <MarshalAs(UnmanagedType.U8, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public U8 As String <MarshalAs(UnmanagedType.VariantBool, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public VariantBool As Integer End Class ]]> </file> </compilation> Dim blobs = New Dictionary(Of String, Byte()) From { {"ZeroShort", New Byte() {&H0}}, {"Zero", New Byte() {&H0}}, {"MaxValue", New Byte() {&HDF, &HFF, &HFF, &HFF}}, {"_0x1000", New Byte() {&H90, &H0}}, {"_0x123456", New Byte() {&HC0, &H12, &H34, &H56}}, {"AnsiBStr", New Byte() {&H23}}, {"AsAny", New Byte() {&H28}}, {"Bool", New Byte() {&H2}}, {"BStr", New Byte() {&H13}}, {"Currency", New Byte() {&HF}}, {"Error", New Byte() {&H2D}}, {"FunctionPtr", New Byte() {&H26}}, {"I1", New Byte() {&H3}}, {"I2", New Byte() {&H5}}, {"I4", New Byte() {&H7}}, {"I8", New Byte() {&H9}}, {"LPStr", New Byte() {&H14}}, {"LPStruct", New Byte() {&H2B}}, {"LPTStr", New Byte() {&H16}}, {"LPWStr", New Byte() {&H15}}, {"R4", New Byte() {&HB}}, {"R8", New Byte() {&HC}}, {"Struct", New Byte() {&H1B}}, {"SysInt", New Byte() {&H1F}}, {"SysUInt", New Byte() {&H20}}, {"TBStr", New Byte() {&H24}}, {"U1", New Byte() {&H4}}, {"U2", New Byte() {&H6}}, {"U4", New Byte() {&H8}}, {"U8", New Byte() {&HA}}, {"VariantBool", New Byte() {&H25}} } Dim verifier = CompileAndVerifyFieldMarshal(source, blobs) VerifyFieldMetadataDecoding(verifier, blobs) End Sub <Fact()> Public Sub SimpleTypes_Errors() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System.Runtime.InteropServices Class X <MarshalAs(CType(-1, UnmanagedType))> Dim MinValue_1 As X <MarshalAs(CType(&H20000000, UnmanagedType))> Dim MaxValue_1 As X End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40(source).VerifyDiagnostics( Diagnostic(ERRID.ERR_BadAttribute1, "CType(-1, UnmanagedType)").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute"), Diagnostic(ERRID.ERR_BadAttribute1, "CType(&H20000000, UnmanagedType)").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute")) End Sub ''' <summary> ''' (type, IidParamIndex), others ignored, field type ignored ''' </summary> <Fact> Public Sub ComInterfaces() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Public Class X <MarshalAs(UnmanagedType.IDispatch, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=0, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public IDispatch As Byte <MarshalAs(UnmanagedType.[Interface], ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public [Interface] As X <MarshalAs(UnmanagedType.IUnknown, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=2, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public IUnknown As X() <MarshalAs(UnmanagedType.IUnknown, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=&H1FFFFFFF, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public MaxValue As Integer <MarshalAs(UnmanagedType.IUnknown, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=&H123456, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public m_123456 As Integer <MarshalAs(UnmanagedType.IUnknown, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=&H1000, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public m_0x1000 As X <MarshalAs(UnmanagedType.IDispatch)> Public [Default] As Integer End Class ]]> </file> </compilation> Dim blobs = New Dictionary(Of String, Byte()) From { {"IDispatch", New Byte() {&H1A, &H0}}, {"Interface", New Byte() {&H1C, &H1}}, {"IUnknown", New Byte() {&H19, &H2}}, {"MaxValue", New Byte() {&H19, &HDF, &HFF, &HFF, &HFF}}, {"m_123456", New Byte() {&H19, &HC0, &H12, &H34, &H56}}, {"m_0x1000", New Byte() {&H19, &H90, &H0}}, {"Default", New Byte() {&H1A}} } Dim verifier = CompileAndVerifyFieldMarshal(source, blobs) VerifyFieldMetadataDecoding(verifier, blobs) End Sub <Fact()> Public Sub ComInterfaces_Errors() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System.Runtime.InteropServices Class X <MarshalAs(UnmanagedType.IDispatch, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Dim IDispatch_MinValue_1 As Integer <MarshalAs(UnmanagedType.[Interface], ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Dim Interface_MinValue_1 As Integer <MarshalAs(UnmanagedType.IUnknown, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Dim IUnknown_MinValue_1 As Integer <MarshalAs(UnmanagedType.IUnknown, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=&H20000000, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Dim IUnknown_MaxValue_1 As Integer End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40(source).VerifyDiagnostics( Diagnostic(ERRID.ERR_BadAttribute1, "IidParameterIndex:=-1").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute"), Diagnostic(ERRID.ERR_BadAttribute1, "IidParameterIndex:=-1").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute"), Diagnostic(ERRID.ERR_BadAttribute1, "IidParameterIndex:=-1").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute"), Diagnostic(ERRID.ERR_BadAttribute1, "IidParameterIndex:=&H20000000").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute")) End Sub ''' <summary> ''' (ArraySubType, SizeConst, SizeParamIndex), SafeArraySubType not allowed, others ignored ''' </summary> <Fact> Public Sub NativeTypeArray() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Public Class X <MarshalAs(UnmanagedType.LPArray)> Public LPArray0 As Integer <MarshalAs(UnmanagedType.LPArray, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArrayUserDefinedSubType:=Nothing)> Public LPArray1 As Integer <MarshalAs(UnmanagedType.LPArray, ArraySubType:=UnmanagedType.ByValTStr, SizeConst:=0, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArrayUserDefinedSubType:=Nothing)> Public LPArray2 As Integer <MarshalAs(UnmanagedType.LPArray, ArraySubType:=UnmanagedType.ByValTStr, SizeConst:=&H1FFFFFFF, SizeParamIndex:=Short.MaxValue, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArrayUserDefinedSubType:=Nothing)> Public LPArray3 As Integer <MarshalAs(UnmanagedType.LPArray, ArraySubType:=DirectCast(&H50, UnmanagedType))> Public LPArray4 As Integer <MarshalAs(UnmanagedType.LPArray, ArraySubType:=DirectCast(&H1FFFFFFF, UnmanagedType))> Public LPArray5 As Integer <MarshalAs(UnmanagedType.LPArray, ArraySubType:=DirectCast(0, UnmanagedType))> Public LPArray6 As Integer End Class ]]> </file> </compilation> Dim blobs = New Dictionary(Of String, Byte()) From { {"LPArray0", New Byte() {&H2A, &H50}}, {"LPArray1", New Byte() {&H2A, &H17}}, {"LPArray2", New Byte() {&H2A, &H17, &H0, &H0, &H0}}, {"LPArray3", New Byte() {&H2A, &H17, &HC0, &H0, &H7F, &HFF, &HDF, &HFF, &HFF, &HFF, &H1}}, {"LPArray4", New Byte() {&H2A, &H50}}, {"LPArray5", New Byte() {&H2A, &HDF, &HFF, &HFF, &HFF}}, {"LPArray6", New Byte() {&H2A, &H0}} } Dim verifier = CompileAndVerifyFieldMarshal(source, blobs) VerifyFieldMetadataDecoding(verifier, blobs) End Sub <Fact()> Public Sub NativeTypeArray_ElementTypes() Dim source As StringBuilder = New StringBuilder(<text> Imports System Imports System.Runtime.InteropServices Class X </text>.Value) Dim expectedBlobs = New Dictionary(Of String, Byte())() For i = 0 To SByte.MaxValue If i <> DirectCast(UnmanagedType.CustomMarshaler, Integer) Then Dim fldName As String = String.Format("m_{0:X}", i) source.AppendLine(String.Format("<MarshalAs(UnmanagedType.LPArray, ArraySubType := CType(&H{0:X}, UnmanagedType))>Dim {1} As Integer", i, fldName)) expectedBlobs.Add(fldName, New Byte() {&H2A, CByte(i)}) End If Next source.AppendLine("End Class") CompileAndVerifyFieldMarshal(source.ToString(), expectedBlobs) End Sub <Fact()> Public Sub NativeTypeArray_Errors() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Class X <MarshalAs(UnmanagedType.LPArray, ArraySubType:=UnmanagedType.ByValTStr, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Dim LPArray_e0 As Integer <MarshalAs(UnmanagedType.LPArray, ArraySubType:=UnmanagedType.ByValTStr, SizeConst:=-1)> Dim LPArray_e1 As Integer <MarshalAs(UnmanagedType.LPArray, ArraySubType:=UnmanagedType.ByValTStr, SizeConst:=0, SizeParamIndex:=-1)> Dim LPArray_e2 As Integer <MarshalAs(UnmanagedType.LPArray, ArraySubType:=UnmanagedType.ByValTStr, SizeConst:=Int32.MaxValue, SizeParamIndex:=Int16.MaxValue)> Dim LPArray_e3 As Integer <MarshalAs(UnmanagedType.LPArray, ArraySubType:=UnmanagedType.U8, SizeConst:=Int32.MaxValue / 4 + 1, SizeParamIndex:=Int16.MaxValue)> Dim LPArray_e4 As Integer <MarshalAs(UnmanagedType.LPArray, ArraySubType:=UnmanagedType.CustomMarshaler)> Dim LPArray_e5 As Integer <MarshalAs(UnmanagedType.LPArray, SafeArraySubType:=VarEnum.VT_I1)> Dim LPArray_e6 As Integer <MarshalAs(UnmanagedType.LPArray, ArraySubType:=DirectCast(&H20000000, UnmanagedType))> Dim LPArray_e7 As Integer <MarshalAs(UnmanagedType.LPArray, ArraySubType:=DirectCast((-1), UnmanagedType))> Dim LPArray_e8 As Integer End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40(source).VerifyDiagnostics( Diagnostic(ERRID.ERR_ParameterNotValidForType, "SafeArraySubType:=VarEnum.VT_BSTR"), Diagnostic(ERRID.ERR_BadAttribute1, "SizeConst:=-1").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute"), Diagnostic(ERRID.ERR_BadAttribute1, "SizeParamIndex:=-1").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute"), Diagnostic(ERRID.ERR_BadAttribute1, "SizeConst:=-1").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute"), Diagnostic(ERRID.ERR_BadAttribute1, "SizeParamIndex:=-1").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute"), Diagnostic(ERRID.ERR_BadAttribute1, "SizeConst:=Int32.MaxValue").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute"), Diagnostic(ERRID.ERR_BadAttribute1, "SizeConst:=Int32.MaxValue / 4 + 1").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute"), Diagnostic(ERRID.ERR_BadAttribute1, "ArraySubType:=UnmanagedType.CustomMarshaler").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute"), Diagnostic(ERRID.ERR_ParameterNotValidForType, "SafeArraySubType:=VarEnum.VT_I1"), Diagnostic(ERRID.ERR_BadAttribute1, "ArraySubType:=DirectCast(&H20000000, UnmanagedType)").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute"), Diagnostic(ERRID.ERR_BadAttribute1, "ArraySubType:=DirectCast((-1), UnmanagedType)").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute")) End Sub ''' <summary> ''' (ArraySubType, SizeConst), (SizeParamIndex, SafeArraySubType) not allowed, others ignored ''' </summary> <Fact> Public Sub NativeTypeFixedArray() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Public Class X <MarshalAs(UnmanagedType.ByValArray)> Public ByValArray0 As Integer <MarshalAs(UnmanagedType.ByValArray, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArrayUserDefinedSubType:=Nothing)> Public ByValArray1 As Integer <MarshalAs(UnmanagedType.ByValArray, ArraySubType:=UnmanagedType.ByValTStr, SizeConst:=0, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArrayUserDefinedSubType:=Nothing)> Public ByValArray2 As Integer <MarshalAs(UnmanagedType.ByValArray, ArraySubType:=UnmanagedType.ByValTStr, SizeConst:=(Int32.MaxValue - 3) / 4, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArrayUserDefinedSubType:=Nothing)> Public ByValArray3 As Integer <MarshalAs(UnmanagedType.ByValArray, ArraySubType:=UnmanagedType.AsAny)> Public ByValArray4 As Integer <MarshalAs(UnmanagedType.ByValArray, ArraySubType:=UnmanagedType.CustomMarshaler)> Public ByValArray5 As Integer End Class ]]> </file> </compilation> Dim blobs = New Dictionary(Of String, Byte()) From { {"ByValArray0", New Byte() {&H1E, &H1}}, {"ByValArray1", New Byte() {&H1E, &H1, &H17}}, {"ByValArray2", New Byte() {&H1E, &H0, &H17}}, {"ByValArray3", New Byte() {&H1E, &HDF, &HFF, &HFF, &HFF, &H17}}, {"ByValArray4", New Byte() {&H1E, &H1, &H28}}, {"ByValArray5", New Byte() {&H1E, &H1, &H2C}} } Dim verifier = CompileAndVerifyFieldMarshal(source, blobs) VerifyFieldMetadataDecoding(verifier, blobs) End Sub <Fact()> Public Sub NativeTypeFixedArray_ElementTypes() Dim source As StringBuilder = New StringBuilder(<text> Imports System Imports System.Runtime.InteropServices Class X </text>.Value) Dim expectedBlobs = New Dictionary(Of String, Byte())() Dim i As Integer = 0 While i < SByte.MaxValue Dim fldName As String = String.Format("m_{0:X}", i) source.AppendLine(String.Format("<MarshalAs(UnmanagedType.ByValArray, ArraySubType := CType(&H{0:X}, UnmanagedType))>Dim {1} As Integer", i, fldName)) expectedBlobs.Add(fldName, New Byte() {&H1E, &H1, CByte(i)}) i = i + 1 End While source.AppendLine("End Class") CompileAndVerifyFieldMarshal(source.ToString(), expectedBlobs) End Sub <Fact()> Public Sub NativeTypeFixedArray_Errors() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Public Class X <MarshalAs(UnmanagedType.ByValArray, ArraySubType:=UnmanagedType.ByValTStr, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Dim ByValArray_e1 As Integer <MarshalAs(UnmanagedType.ByValArray, SizeParamIndex:=Int16.MaxValue)> Dim ByValArray_e2 As Integer <MarshalAs(UnmanagedType.ByValArray, SafeArraySubType:=VarEnum.VT_I2)> Dim ByValArray_e3 As Integer <MarshalAs(UnmanagedType.ByValArray, ArraySubType:=UnmanagedType.ByValTStr, SizeConst:=&H20000000)> Dim ByValArray_e4 As Integer End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40(source).VerifyDiagnostics( Diagnostic(ERRID.ERR_ParameterNotValidForType, "SafeArraySubType:=VarEnum.VT_BSTR"), Diagnostic(ERRID.ERR_BadAttribute1, "SizeConst:=-1").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute"), Diagnostic(ERRID.ERR_ParameterNotValidForType, "SizeParamIndex:=-1"), Diagnostic(ERRID.ERR_ParameterNotValidForType, "SizeParamIndex:=Int16.MaxValue"), Diagnostic(ERRID.ERR_ParameterNotValidForType, "SafeArraySubType:=VarEnum.VT_I2"), Diagnostic(ERRID.ERR_BadAttribute1, "SizeConst:=&H20000000").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute")) End Sub ''' <summary> ''' (SafeArraySubType, SafeArrayUserDefinedSubType), (ArraySubType, SizeConst, SizeParamIndex) not allowed, ''' (SafeArraySubType, SafeArrayUserDefinedSubType) not allowed together unless VT_DISPATCH, VT_UNKNOWN, VT_RECORD; others ignored. ''' </summary> <Fact> Public Sub NativeTypeSafeArray() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Runtime.InteropServices Public Class X <MarshalAs(UnmanagedType.SafeArray)> Public SafeArray0 As Integer <MarshalAs(UnmanagedType.SafeArray, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR)> Public SafeArray1 As Integer <MarshalAs(UnmanagedType.SafeArray, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArrayUserDefinedSubType:=GetType(X))> Public SafeArray2 As Integer <MarshalAs(UnmanagedType.SafeArray, SafeArrayUserDefinedSubType:=Nothing)> Public SafeArray3 As Integer <MarshalAs(UnmanagedType.SafeArray, SafeArrayUserDefinedSubType:=GetType(Void))> Public SafeArray4 As Integer <MarshalAs(UnmanagedType.SafeArray, SafeArraySubType:=VarEnum.VT_EMPTY)> Public SafeArray8 As Integer <MarshalAs(UnmanagedType.SafeArray, SafeArraySubType:=VarEnum.VT_RECORD, SafeArrayUserDefinedSubType:=GetType(Integer()()))> Public SafeArray9 As Integer <MarshalAs(UnmanagedType.SafeArray, SafeArraySubType:=VarEnum.VT_RECORD, SafeArrayUserDefinedSubType:=GetType(Nullable(Of)))> Public SafeArray10 As Integer End Class ]]> </file> </compilation> Dim aqn = Encoding.ASCII.GetBytes("System.Int32[][], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089") Dim openGenericAqn = Encoding.ASCII.GetBytes("System.Nullable`1, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089") Dim blobs = New Dictionary(Of String, Byte()) From { {"SafeArray0", New Byte() {&H1D}}, {"SafeArray1", New Byte() {&H1D, &H8}}, {"SafeArray2", New Byte() {&H1D}}, {"SafeArray3", New Byte() {&H1D}}, {"SafeArray4", New Byte() {&H1D}}, {"SafeArray8", New Byte() {&H1D, &H0}}, {"SafeArray9", New Byte() {&H1D, &H24, CByte(aqn.Length)}.Append(aqn)}, {"SafeArray10", New Byte() {&H1D, &H24, CByte(openGenericAqn.Length)}.Append(openGenericAqn)} } Dim verifier = CompileAndVerifyFieldMarshal(source, blobs) VerifyFieldMetadataDecoding(verifier, blobs) End Sub <Fact> Public Sub NativeTypeSafeArray_CCIOnly() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Runtime.InteropServices Public Class C(Of T) Public Class D(Of S) Public Class E End Class End Class End Class Public Class X <MarshalAs(UnmanagedType.SafeArray, SafeArraySubType:=VarEnum.VT_RECORD, SafeArrayUserDefinedSubType:=GetType(C(Of Integer).D(Of Boolean).E))> Public SafeArray11 As Integer End Class ]]> </file> </compilation> Dim nestedAqn = Encoding.ASCII.GetBytes("C`1+D`1+E[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]") Dim blobs = New Dictionary(Of String, Byte()) From { {"SafeArray11", New Byte() {&H1D, &H24, &H80, &HC4}.Append(nestedAqn)} } ' RefEmit has slightly different encoding of the type name Dim verifier = CompileAndVerifyFieldMarshal(source, blobs) VerifyFieldMetadataDecoding(verifier, blobs) End Sub <Fact()> Public Sub NativeTypeSafeArray_RefEmitDiffers() Dim source = <![CDATA[ Imports System Imports System.Collections.Generic Imports System.Runtime.InteropServices Public Class X <MarshalAs(UnmanagedType.SafeArray, SafeArraySubType:=VarEnum.VT_DISPATCH, SafeArrayUserDefinedSubType:=GetType(List(Of X)()()))> Dim SafeArray5 As Integer <MarshalAs(UnmanagedType.SafeArray, SafeArraySubType:=VarEnum.VT_UNKNOWN, SafeArrayUserDefinedSubType:=GetType(X))> Dim SafeArray6 As Integer <MarshalAs(UnmanagedType.SafeArray, SafeArraySubType:=VarEnum.VT_RECORD, SafeArrayUserDefinedSubType:=GetType(X))> Dim SafeArray7 As Integer End Class ]]>.Value Dim e = Encoding.ASCII Dim cciBlobs = New Dictionary(Of String, Byte()) From { {"SafeArray5", New Byte() {&H1D, &H9, &H75}.Append(e.GetBytes("System.Collections.Generic.List`1[X][][], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"))}, {"SafeArray6", New Byte() {&H1D, &HD, &H1, &H58}}, {"SafeArray7", New Byte() {&H1D, &H24, &H1, &H58}} } CompileAndVerifyFieldMarshal(source, cciBlobs) End Sub <Fact()> Public Sub NativeTypeSafeArray_Errors() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System.Runtime.InteropServices Public Class X <MarshalAs(UnmanagedType.SafeArray, ArraySubType:=UnmanagedType.ByValTStr, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Dim SafeArray_e1 As Integer <MarshalAs(UnmanagedType.SafeArray, ArraySubType:=UnmanagedType.ByValTStr)> Dim SafeArray_e2 As Integer <MarshalAs(UnmanagedType.SafeArray, SizeConst:=1)> Dim SafeArray_e3 As Integer <MarshalAs(UnmanagedType.SafeArray, SizeParamIndex:=1)> Dim SafeArray_e4 As Integer <MarshalAs(UnmanagedType.SafeArray, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing)> Dim SafeArray_e5 As Integer <MarshalAs(UnmanagedType.SafeArray, SafeArrayUserDefinedSubType:=Nothing, SafeArraySubType:=VarEnum.VT_BLOB)> Dim SafeArray_e6 As Integer <MarshalAs(UnmanagedType.SafeArray, SafeArrayUserDefinedSubType:=GetType(Integer), SafeArraySubType:=0)> Dim SafeArray_e7 As Integer End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40(source).VerifyDiagnostics( Diagnostic(ERRID.ERR_ParameterNotValidForType, "ArraySubType:=UnmanagedType.ByValTStr"), Diagnostic(ERRID.ERR_ParameterNotValidForType, "SizeConst:=-1"), Diagnostic(ERRID.ERR_ParameterNotValidForType, "SizeParamIndex:=-1"), Diagnostic(ERRID.ERR_ParameterNotValidForType, "SafeArrayUserDefinedSubType:=Nothing"), Diagnostic(ERRID.ERR_ParameterNotValidForType, "ArraySubType:=UnmanagedType.ByValTStr"), Diagnostic(ERRID.ERR_ParameterNotValidForType, "SizeConst:=1"), Diagnostic(ERRID.ERR_ParameterNotValidForType, "SizeParamIndex:=1"), Diagnostic(ERRID.ERR_ParameterNotValidForType, "SafeArrayUserDefinedSubType:=Nothing"), Diagnostic(ERRID.ERR_ParameterNotValidForType, "SafeArrayUserDefinedSubType:=Nothing"), Diagnostic(ERRID.ERR_ParameterNotValidForType, "SafeArrayUserDefinedSubType:=GetType(Integer)")) End Sub ''' <summary> ''' (SizeConst - required), (SizeParamIndex, ArraySubType) not allowed ''' </summary> <Fact> Public Sub NativeTypeFixedSysString() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Public Class X <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=1)> Public ByValTStr1 As Integer <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=&H1FFFFFFF, SafeArrayUserDefinedSubType:=GetType(Integer), IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing)> Public ByValTStr2 As Integer End Class ]]> </file> </compilation> Dim blobs = New Dictionary(Of String, Byte()) From { {"ByValTStr1", New Byte() {&H17, &H1}}, {"ByValTStr2", New Byte() {&H17, &HDF, &HFF, &HFF, &HFF}} } Dim verifier = CompileAndVerifyFieldMarshal(source, blobs) VerifyFieldMetadataDecoding(verifier, blobs) End Sub <Fact()> Public Sub NativeTypeFixedSysString_Errors() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Public Class X <MarshalAs(UnmanagedType.ByValTStr, ArraySubType:=UnmanagedType.ByValTStr, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Dim ByValTStr_e1 As Integer <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=-1)> Dim ByValTStr_e2 As Integer <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=(Int32.MaxValue - 3) / 4 + 1)> Dim ByValTStr_e3 As Integer <MarshalAs(UnmanagedType.ByValTStr)> Dim ByValTStr_e4 As Integer <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=1, SizeParamIndex:=1)> Dim ByValTStr_e5 As Integer <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=1, ArraySubType:=UnmanagedType.ByValTStr)> Dim ByValTStr_e6 As Integer <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=1, SafeArraySubType:=VarEnum.VT_BSTR)> Dim ByValTStr_e7 As Integer End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40(source).VerifyDiagnostics( Diagnostic(ERRID.ERR_ParameterNotValidForType, "ArraySubType:=UnmanagedType.ByValTStr"), Diagnostic(ERRID.ERR_BadAttribute1, "SizeConst:=-1").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute"), Diagnostic(ERRID.ERR_ParameterNotValidForType, "SizeParamIndex:=-1"), Diagnostic(ERRID.ERR_AttributeParameterRequired1, "MarshalAs").WithArguments("SizeConst"), Diagnostic(ERRID.ERR_BadAttribute1, "SizeConst:=-1").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute"), Diagnostic(ERRID.ERR_AttributeParameterRequired1, "MarshalAs").WithArguments("SizeConst"), Diagnostic(ERRID.ERR_BadAttribute1, "SizeConst:=(Int32.MaxValue - 3) / 4 + 1").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute"), Diagnostic(ERRID.ERR_AttributeParameterRequired1, "MarshalAs").WithArguments("SizeConst"), Diagnostic(ERRID.ERR_ParameterNotValidForType, "SizeParamIndex:=1"), Diagnostic(ERRID.ERR_ParameterNotValidForType, "ArraySubType:=UnmanagedType.ByValTStr")) End Sub ''' <summary> ''' Custom (MarshalType, MarshalTypeRef, MarshalCookie) one of {MarshalType, MarshalTypeRef} required, others ignored ''' </summary> <Fact> Public Sub CustomMarshal() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Imports Microsoft.VisualBasic.Strings Public Class X <MarshalAs(UnmanagedType.CustomMarshaler, MarshalType:=Nothing)> Public CustomMarshaler1 As Integer <MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef:=Nothing)> Public CustomMarshaler2 As Integer <MarshalAs(UnmanagedType.CustomMarshaler, MarshalType:="foo", MarshalTypeRef:=GetType(Integer))> Public CustomMarshaler3 As Integer <MarshalAs(UnmanagedType.CustomMarshaler, MarshalType:=ChrW(&H1234) & "f" & ChrW(0) & "oozzz")> Public CustomMarshaler4 As Integer <MarshalAs(UnmanagedType.CustomMarshaler, MarshalType:="f" & ChrW(0) & "oozzz")> Public CustomMarshaler5 As Integer <MarshalAs(UnmanagedType.CustomMarshaler, MarshalType:="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")> Public CustomMarshaler6 As Integer <MarshalAs(UnmanagedType.CustomMarshaler, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public CustomMarshaler7 As Integer <MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef:=GetType(Integer))> Public CustomMarshaler8 As Integer <MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef:=GetType(Integer), MarshalType:="foo", MarshalCookie:="hello" & ChrW(0) & "world(" & ChrW(&H1234) & ")")> Public CustomMarshaler9 As Integer <MarshalAs(UnmanagedType.CustomMarshaler, MarshalType:=Nothing, MarshalTypeRef:=GetType(Integer))> Public CustomMarshaler10 As Integer <MarshalAs(UnmanagedType.CustomMarshaler, MarshalType:="foo", MarshalTypeRef:=Nothing)> Public CustomMarshaler11 As Integer <MarshalAs(UnmanagedType.CustomMarshaler, MarshalType:=Nothing, MarshalTypeRef:=Nothing)> Public CustomMarshaler12 As Integer <MarshalAs(UnmanagedType.CustomMarshaler, MarshalType:="aaa" & ChrW(0) & "bbb", MarshalCookie:="ccc" & ChrW(0) & "ddd")> Public CustomMarshaler13 As Integer <MarshalAs(UnmanagedType.CustomMarshaler, MarshalType:=ChrW(&HD869) & ChrW(&HDED6), MarshalCookie:=ChrW(&HD869) & ChrW(&HDED6))> Public CustomMarshaler14 As Integer End Class ]]> </file> </compilation> Dim blobs = New Dictionary(Of String, Byte()) From { {"CustomMarshaler1", New Byte() {&H2C, &H0, &H0, &H0, &H0}}, {"CustomMarshaler2", New Byte() {&H2C, &H0, &H0, &H0, &H0}}, {"CustomMarshaler3", New Byte() {&H2C, &H0, &H0, &H3, &H66, &H6F, &H6F, &H0}}, {"CustomMarshaler4", New Byte() {&H2C, &H0, &H0, &HA, &HE1, &H88, &HB4, &H66, &H0, &H6F, &H6F, &H7A, &H7A, &H7A, &H0}}, {"CustomMarshaler5", New Byte() {&H2C, &H0, &H0, &H7, &H66, &H0, &H6F, &H6F, &H7A, &H7A, &H7A, &H0}}, {"CustomMarshaler6", New Byte() {&H2C, &H0, &H0, &H60}.Append(Encoding.UTF8.GetBytes("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" & ChrW(0)))}, {"CustomMarshaler7", New Byte() {&H2C, &H0, &H0, &H0, &H0}}, {"CustomMarshaler8", New Byte() {&H2C, &H0, &H0, &H59}.Append(Encoding.UTF8.GetBytes("System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" & ChrW(0)))}, {"CustomMarshaler9", New Byte() {&H2C, &H0, &H0, &H3, &H66, &H6F, &H6F, &H10, &H68, &H65, &H6C, &H6C, &H6F, &H0, &H77, &H6F, &H72, &H6C, &H64, &H28, &HE1, &H88, &HB4, &H29}}, {"CustomMarshaler10", New Byte() {&H2C, &H0, &H0, &H0, &H0}}, {"CustomMarshaler11", New Byte() {&H2C, &H0, &H0, &H3, &H66, &H6F, &H6F, &H0}}, {"CustomMarshaler12", New Byte() {&H2C, &H0, &H0, &H0, &H0}}, {"CustomMarshaler13", New Byte() {&H2C, &H0, &H0, &H7, &H61, &H61, &H61, &H0, &H62, &H62, &H62, &H7, &H63, &H63, &H63, &H0, &H64, &H64, &H64}}, {"CustomMarshaler14", New Byte() {&H2C, &H0, &H0, &H4, &HF0, &HAA, &H9B, &H96, &H4, &HF0, &HAA, &H9B, &H96}} } Dim verifier = CompileAndVerifyFieldMarshal(source, blobs) VerifyFieldMetadataDecoding(verifier, blobs) End Sub <Fact()> Public Sub CustomMarshal_Errors() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System.Runtime.InteropServices Imports Microsoft.VisualBasic.Strings Public Class X <MarshalAs(UnmanagedType.CustomMarshaler)> Dim CustomMarshaler_e0 As Integer <MarshalAs(UnmanagedType.CustomMarshaler, MarshalType:="a" & ChrW(&HDC00) & "b", MarshalCookie:="b")> Dim CustomMarshaler_e1 As Integer <MarshalAs(UnmanagedType.CustomMarshaler, MarshalType:="x", MarshalCookie:="y" & ChrW(&HDC00))> Dim CustomMarshaler_e2 As Integer End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics( Diagnostic(ERRID.ERR_AttributeParameterRequired2, "MarshalAs").WithArguments("MarshalType", "MarshalTypeRef"), Diagnostic(ERRID.ERR_BadAttribute1, "MarshalType:=""a"" & ChrW(&HDC00) & ""b""").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute"), Diagnostic(ERRID.ERR_BadAttribute1, "MarshalCookie:=""y"" & ChrW(&HDC00)").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute")) End Sub <Fact()> Public Sub Events_Error() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Class C <MarshalAs(UnmanagedType.Bool)> Event e As Action End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40(source).VerifyDiagnostics( Diagnostic(ERRID.ERR_InvalidAttributeUsage2, "MarshalAs").WithArguments("MarshalAsAttribute", "e")) End Sub <Fact()> Public Sub MarshalAs_AllFieldTargets() Dim source = <compilation><file><![CDATA[ Imports System Imports System.Runtime.InteropServices Class Z <MarshalAs(UnmanagedType.Bool)> Dim f As Integer End Class Module M <MarshalAs(UnmanagedType.Bool)> Public WithEvents we As New Z End Module Enum En <MarshalAs(UnmanagedType.Bool)> A = 1 <MarshalAs(UnmanagedType.Bool)> B End Enum ]]></file></compilation> CompileAndVerifyFieldMarshal(source, Function(name, _omitted1) Return If(name = "f" Or name = "_we" Or name = "A" Or name = "B", New Byte() {&H2}, Nothing) End Function) End Sub <Fact()> Public Sub Parameters() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Imports Microsoft.VisualBasic.Strings Class X Public Shared Function foo(<MarshalAs(UnmanagedType.IDispatch)> ByRef IDispatch As Integer, <MarshalAs(UnmanagedType.LPArray)> ByRef LPArray0 As Integer, <MarshalAs(UnmanagedType.SafeArray, SafeArraySubType:=VarEnum.VT_EMPTY)> SafeArray8 As Integer, <MarshalAs(UnmanagedType.CustomMarshaler, MarshalType:="aaa" & ChrW(0) & "bbb", MarshalCookie:="ccc" & ChrW(0) & "ddd")> CustomMarshaler13 As Integer) As <MarshalAs(UnmanagedType.LPStr)> X Return Nothing End Function End Class ]]> </file> </compilation> Dim blobs = New Dictionary(Of String, Byte())() From { {"foo:", New Byte() {&H14}}, {"foo:IDispatch", New Byte() {&H1A}}, {"foo:LPArray0", New Byte() {&H2A, &H50}}, {"foo:SafeArray8", New Byte() {&H1D, &H0}}, {"foo:CustomMarshaler13", New Byte() {&H2C, &H0, &H0, &H7, &H61, &H61, &H61, &H0, &H62, &H62, &H62, &H7, &H63, &H63, &H63, &H0, &H64, &H64, &H64}} } Dim verifier = CompileAndVerifyFieldMarshal(source, blobs, isField:=False) VerifyParameterMetadataDecoding(verifier, blobs) End Sub <Fact> Public Sub MarshalAs_AllParameterTargets_Events() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Module X Custom Event E As Action AddHandler(<MarshalAs(UnmanagedType.BStr)> eAdd As Action) End AddHandler RemoveHandler(<MarshalAs(UnmanagedType.BStr)> eRemove As Action) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Module ]]> </file> </compilation> Dim blobs = New Dictionary(Of String, Byte())() From { {"add_E:eAdd", New Byte() {&H13}}, {"remove_E:eRemove", New Byte() {&H13}} } Dim verifier = CompileAndVerifyFieldMarshal(source, blobs, isField:=False) VerifyParameterMetadataDecoding(verifier, blobs) End Sub <Fact> Public Sub MarshalAs_AllParameterTargets_Properties() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Module C Property P(<MarshalAs(UnmanagedType.I2)> pIndex As Integer) As <MarshalAs(UnmanagedType.I4)> Integer Get Return 0 End Get Set(<MarshalAs(UnmanagedType.I8)> pValue As Integer) End Set End Property Property Q As <MarshalAs(UnmanagedType.I4)> Integer Get Return 0 End Get Set(qValue As Integer) End Set End Property Property CRW As <MarshalAs(UnmanagedType.I4)> Integer WriteOnly Property CW As <MarshalAs(UnmanagedType.I4)> Integer Set(sValue As Integer) End Set End Property ReadOnly Property CR As <MarshalAs(UnmanagedType.I4)> Integer Get Return 0 End Get End Property End Module Interface I Property IRW As <MarshalAs(UnmanagedType.I4)> Integer ReadOnly Property IR As <MarshalAs(UnmanagedType.I4)> Integer WriteOnly Property IW As <MarshalAs(UnmanagedType.I4)> Integer Property IRW2(a As Integer, b As Integer) As <MarshalAs(UnmanagedType.I4)> Integer ReadOnly Property IR2(a As Integer, b As Integer) As <MarshalAs(UnmanagedType.I4)> Integer WriteOnly Property IW2(a As Integer, b As Integer) As <MarshalAs(UnmanagedType.I4)> Integer End Interface ]]> </file> </compilation> Dim i2 = New Byte() {&H5} Dim i4 = New Byte() {&H7} Dim i8 = New Byte() {&H9} ' Dev11 incorrectly applies return-type MarshalAs on the first parameter of an interface property. Dim blobs = New Dictionary(Of String, Byte())() From { {"get_P:", i4}, {"get_P:pIndex", i2}, {"set_P:pIndex", i2}, {"set_P:pValue", i8}, {"get_Q:", i4}, {"set_Q:qValue", Nothing}, {"get_CRW:", i4}, {"set_CRW:AutoPropertyValue", Nothing}, {"set_CW:sValue", Nothing}, {"get_CR:", i4}, {"get_IRW:", i4}, {"set_IRW:Value", i4}, {"get_IR:", i4}, {"set_IW:Value", i4}, {"get_IRW2:", i4}, {"get_IRW2:a", Nothing}, {"get_IRW2:b", Nothing}, {"set_IRW2:a", Nothing}, {"set_IRW2:b", Nothing}, {"set_IRW2:Value", i4}, {"get_IR2:", i4}, {"get_IR2:a", Nothing}, {"get_IR2:b", Nothing}, {"set_IW2:a", Nothing}, {"set_IW2:b", Nothing}, {"set_IW2:Value", i4} } Dim verifier = CompileAndVerifyFieldMarshal(source, blobs, isField:=False) CompilationUtils.AssertTheseDiagnostics(verifier.Compilation, <errors><![CDATA[ BC42364: Attributes applied on a return type of a WriteOnly Property have no effect. WriteOnly Property CW As <MarshalAs(UnmanagedType.I4)> Integer ~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></errors>) VerifyParameterMetadataDecoding(verifier, blobs) End Sub <Fact> Public Sub MarshalAs_PropertyReturnType_MissingAccessors() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Module C Property Q As <MarshalAs(UnmanagedType.I4)> Integer End Property End Module ]]> </file> </compilation> Dim c = CreateCompilationWithMscorlib40AndVBRuntime(source) CompilationUtils.AssertTheseDiagnostics(c, <errors><![CDATA[ BC30124: Property without a 'ReadOnly' or 'WriteOnly' specifier must provide both a 'Get' and a 'Set'. Property Q As <MarshalAs(UnmanagedType.I4)> Integer ~ ]]></errors>) End Sub <Fact> Public Sub MarshalAs_AllParameterTargets_PartialSubs() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Partial Class X Private Partial Sub F(<MarshalAs(UnmanagedType.BStr)> pf As Integer) End Sub Private Sub F(pf As Integer) End Sub Private Partial Sub G(pg As Integer) End Sub Private Sub G(<MarshalAs(UnmanagedType.BStr)> pg As Integer) End Sub Private Sub H(<MarshalAs(UnmanagedType.BStr)> ph As Integer) End Sub Private Partial Sub H(ph As Integer) End Sub Private Sub I(pi As Integer) End Sub Private Partial Sub I(<MarshalAs(UnmanagedType.BStr)> pi As Integer) End Sub End Class ]]> </file> </compilation> Dim blobs = New Dictionary(Of String, Byte())() From { {"F:pf", New Byte() {&H13}}, {"G:pg", New Byte() {&H13}}, {"H:ph", New Byte() {&H13}}, {"I:pi", New Byte() {&H13}} } CompileAndVerifyFieldMarshal(source, blobs, isField:=False) End Sub <Fact> Public Sub MarshalAs_AllParameterTargets_Delegate() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Delegate Function D(<MarshalAs(UnmanagedType.BStr)>p As Integer, <MarshalAs(UnmanagedType.BStr)>ByRef q As Integer) As <MarshalAs(UnmanagedType.BStr)> Integer ]]> </file> </compilation> Dim blobs = New Dictionary(Of String, Byte())() From { {".ctor:TargetObject", Nothing}, {".ctor:TargetMethod", Nothing}, {"BeginInvoke:p", New Byte() {&H13}}, {"BeginInvoke:q", New Byte() {&H13}}, {"BeginInvoke:DelegateCallback", Nothing}, {"BeginInvoke:DelegateAsyncState", Nothing}, {"EndInvoke:p", New Byte() {&H13}}, {"EndInvoke:q", New Byte() {&H13}}, {"EndInvoke:DelegateAsyncResult", Nothing}, {"Invoke:", New Byte() {&H13}}, {"Invoke:p", New Byte() {&H13}}, {"Invoke:q", New Byte() {&H13}} } Dim verifier = CompileAndVerifyFieldMarshal(source, blobs, isField:=False) VerifyParameterMetadataDecoding(verifier, blobs) End Sub <Fact> Public Sub MarshalAs_AllParameterTargets_Declare() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Module M Declare Function Foo Lib "foo" ( <MarshalAs(UnmanagedType.BStr)> explicitInt As Integer, <MarshalAs(UnmanagedType.BStr)> ByRef explicitByRefInt As Integer, <MarshalAs(UnmanagedType.Bool)> explicitString As String, <MarshalAs(UnmanagedType.Bool)> ByRef explicitByRefString As String, pString As String, ByRef pByRefString As String, pInt As Integer, ByRef pByRefInt As Integer ) As <MarshalAs(UnmanagedType.BStr)> Integer End Module ]]> </file> </compilation> Const bstr = &H13 Const bool = &H2 Const byvalstr = &H22 Const ansi_bstr = &H23 Dim blobs = New Dictionary(Of String, Byte())() From { {"Foo:", New Byte() {bstr}}, {"Foo:explicitInt", New Byte() {bstr}}, {"Foo:explicitByRefInt", New Byte() {bstr}}, {"Foo:explicitString", New Byte() {bool}}, {"Foo:explicitByRefString", New Byte() {bool}}, {"Foo:pString", New Byte() {byvalstr}}, {"Foo:pByRefString", New Byte() {ansi_bstr}}, {"Foo:pInt", Nothing}, {"Foo:pByRefInt", Nothing} } Dim verifier = CompileAndVerifyFieldMarshal(source, blobs, isField:=False, expectedSignatures:= { Signature("M", "Foo", ".method [System.Runtime.InteropServices.DllImportAttribute(""foo"", EntryPoint = ""Foo"", CharSet = 2, ExactSpelling = True, SetLastError = True, PreserveSig = True, CallingConvention = 1, BestFitMapping = False, ThrowOnUnmappableChar = False)] " & "[System.Runtime.InteropServices.PreserveSigAttribute()] " & "public static pinvokeimpl System.Int32 Foo(" & "System.Int32 explicitInt, " & "System.Int32& explicitByRefInt, " & "System.String explicitString, " & "System.String& explicitByRefString, " & "System.String& pString, " & "System.String& pByRefString, " & "System.Int32 pInt, " & "System.Int32& pByRefInt" & ") cil managed preservesig") }) VerifyParameterMetadataDecoding(verifier, blobs) End Sub <Fact()> Public Sub Parameters_Errors() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System.Runtime.InteropServices Class X Public Shared Sub f1(<MarshalAs(UnmanagedType.ByValArray)> ByValArray As Integer, <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=1)> ByValTStr As Integer) End Sub Public Shared Function f2() As <MarshalAs(UnmanagedType.ByValArray)> Integer Return 0 End Function Public Shared Function f3() As <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=1)> Integer Return 0 End Function <MarshalAs(UnmanagedType.VBByRefStr)> Public field As Integer End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40(source).VerifyDiagnostics( Diagnostic(ERRID.ERR_MarshalUnmanagedTypeOnlyValidForFields, "UnmanagedType.ByValArray").WithArguments("ByValArray"), Diagnostic(ERRID.ERR_MarshalUnmanagedTypeOnlyValidForFields, "UnmanagedType.ByValTStr").WithArguments("ByValTStr"), Diagnostic(ERRID.ERR_MarshalUnmanagedTypeOnlyValidForFields, "UnmanagedType.ByValArray").WithArguments("ByValArray"), Diagnostic(ERRID.ERR_MarshalUnmanagedTypeOnlyValidForFields, "UnmanagedType.ByValTStr").WithArguments("ByValTStr"), Diagnostic(ERRID.ERR_MarshalUnmanagedTypeNotValidForFields, "UnmanagedType.VBByRefStr").WithArguments("VBByRefStr")) End Sub ''' <summary> ''' type only, only on parameters ''' </summary> <Fact> Public Sub NativeTypeByValStr() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Class X Shared Function f( <MarshalAs(UnmanagedType.VBByRefStr, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> ByRef VBByRefStr_e1 As Integer, _ <MarshalAs(UnmanagedType.VBByRefStr, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> VBByRefStr_e2 As Char(), _ <MarshalAs(UnmanagedType.VBByRefStr, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> VBByRefStr_e3 As Integer) _ As <MarshalAs(UnmanagedType.VBByRefStr, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Integer Return 0 End Function End Class ]]> </file> </compilation> Dim blobs = New Dictionary(Of String, Byte()) From { {"f:", New Byte() {&H22}}, {"f:VBByRefStr_e1", New Byte() {&H22}}, {"f:VBByRefStr_e2", New Byte() {&H22}}, {"f:VBByRefStr_e3", New Byte() {&H22}} } Dim verifier = CompileAndVerifyFieldMarshal(source, blobs, isField:=False) VerifyParameterMetadataDecoding(verifier, blobs) End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System Imports System.Collections.Generic Imports System.Runtime.InteropServices Imports System.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.Test.Utilities Imports Roslyn.Test.Utilities Imports Roslyn.Utilities Imports Xunit Imports TypeKind = Microsoft.CodeAnalysis.TypeKind Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Public Class AttributeTests_MarshalAs Inherits BasicTestBase #Region "Helpers" Private Sub VerifyFieldMetadataDecoding(verifier As CompilationVerifier, blobs As Dictionary(Of String, Byte())) Dim count = 0 Using assembly = AssemblyMetadata.CreateFromImage(verifier.EmittedAssemblyData) Dim c = VisualBasicCompilation.Create("c", syntaxTrees:=New VisualBasicSyntaxTree() {}, references:={assembly.GetReference()}) For Each typeSym As NamedTypeSymbol In c.GlobalNamespace.GetMembers().Where(Function(s) s.Kind = SymbolKind.NamedType) Dim fields = typeSym.GetMembers().Where(Function(s) s.Kind = SymbolKind.Field) For Each field As FieldSymbol In fields Assert.Null(field.MarshallingInformation) Dim blob = blobs(field.Name) If blob IsNot Nothing AndAlso blob(0) <= &H50 Then Assert.Equal(CType(blob(0), UnmanagedType), field.MarshallingType) Else Assert.Equal(CType(0, UnmanagedType), field.MarshallingType) End If count = count + 1 Next Next End Using Assert.True(count > 0, "Expected at least one field") End Sub Private Sub VerifyParameterMetadataDecoding(verifier As CompilationVerifier, blobs As Dictionary(Of String, Byte())) Dim count = 0 Using assembly = AssemblyMetadata.CreateFromImage(verifier.EmittedAssemblyData) Dim c = VisualBasicCompilation.Create("c", syntaxTrees:=New VisualBasicSyntaxTree() {}, references:={assembly.GetReference()}) For Each typeSym As NamedTypeSymbol In c.GlobalNamespace.GetMembers().Where(Function(s) s.Kind = SymbolKind.NamedType) Dim methods = typeSym.GetMembers().Where(Function(s) s.Kind = SymbolKind.Method) For Each method As MethodSymbol In methods For Each parameter In method.Parameters Assert.Null(parameter.MarshallingInformation) Dim blob = blobs(method.Name & ":" & parameter.Name) If blob IsNot Nothing AndAlso blob(0) <= &H50 Then Assert.Equal(CType(blob(0), UnmanagedType), parameter.MarshallingType) Else Assert.Equal(CType(0, UnmanagedType), parameter.MarshallingType) End If count = count + 1 Next Next Next End Using Assert.True(count > 0, "Expected at least one parameter") End Sub #End Region ''' <summary> ''' type only, others ignored, field type ignored ''' </summary> <Fact> Public Sub SimpleTypes() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Public Class X <MarshalAs(CShort(0))> Public ZeroShort As X <MarshalAs(DirectCast(0, UnmanagedType))> Public Zero As X <MarshalAs(DirectCast(&H1FFFFFFF, UnmanagedType))> Public MaxValue As X <MarshalAs(DirectCast((&H123456), UnmanagedType))> Public _0x123456 As X <MarshalAs(DirectCast((&H1000), UnmanagedType))> Public _0x1000 As X <MarshalAs(UnmanagedType.AnsiBStr, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public AnsiBStr As X <MarshalAs(UnmanagedType.AsAny, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public AsAny As Double <MarshalAs(UnmanagedType.Bool, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public Bool As X <MarshalAs(UnmanagedType.BStr, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public BStr As X <MarshalAs(UnmanagedType.Currency, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public Currency As Integer <MarshalAs(UnmanagedType.[Error], ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public [Error] As Integer <MarshalAs(UnmanagedType.FunctionPtr, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public FunctionPtr As Integer <MarshalAs(UnmanagedType.I1, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public I1 As Integer <MarshalAs(UnmanagedType.I2, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public I2 As Integer <MarshalAs(UnmanagedType.I4, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public I4 As Integer <MarshalAs(UnmanagedType.I8, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public I8 As Integer <MarshalAs(UnmanagedType.LPStr, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public LPStr As Integer <MarshalAs(UnmanagedType.LPStruct, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public LPStruct As Integer <MarshalAs(UnmanagedType.LPTStr, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public LPTStr As Integer <MarshalAs(UnmanagedType.LPWStr, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public LPWStr As Integer <MarshalAs(UnmanagedType.R4, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public R4 As Integer <MarshalAs(UnmanagedType.R8, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public R8 As Integer <MarshalAs(UnmanagedType.Struct, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public Struct As Integer <MarshalAs(UnmanagedType.SysInt, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public SysInt As Decimal <MarshalAs(UnmanagedType.SysUInt, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public SysUInt As Integer() <MarshalAs(UnmanagedType.TBStr, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public TBStr As Object() <MarshalAs(UnmanagedType.U1, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public U1 As Integer <MarshalAs(UnmanagedType.U2, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public U2 As Double <MarshalAs(UnmanagedType.U4, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public U4 As Boolean <MarshalAs(UnmanagedType.U8, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public U8 As String <MarshalAs(UnmanagedType.VariantBool, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public VariantBool As Integer End Class ]]> </file> </compilation> Dim blobs = New Dictionary(Of String, Byte()) From { {"ZeroShort", New Byte() {&H0}}, {"Zero", New Byte() {&H0}}, {"MaxValue", New Byte() {&HDF, &HFF, &HFF, &HFF}}, {"_0x1000", New Byte() {&H90, &H0}}, {"_0x123456", New Byte() {&HC0, &H12, &H34, &H56}}, {"AnsiBStr", New Byte() {&H23}}, {"AsAny", New Byte() {&H28}}, {"Bool", New Byte() {&H2}}, {"BStr", New Byte() {&H13}}, {"Currency", New Byte() {&HF}}, {"Error", New Byte() {&H2D}}, {"FunctionPtr", New Byte() {&H26}}, {"I1", New Byte() {&H3}}, {"I2", New Byte() {&H5}}, {"I4", New Byte() {&H7}}, {"I8", New Byte() {&H9}}, {"LPStr", New Byte() {&H14}}, {"LPStruct", New Byte() {&H2B}}, {"LPTStr", New Byte() {&H16}}, {"LPWStr", New Byte() {&H15}}, {"R4", New Byte() {&HB}}, {"R8", New Byte() {&HC}}, {"Struct", New Byte() {&H1B}}, {"SysInt", New Byte() {&H1F}}, {"SysUInt", New Byte() {&H20}}, {"TBStr", New Byte() {&H24}}, {"U1", New Byte() {&H4}}, {"U2", New Byte() {&H6}}, {"U4", New Byte() {&H8}}, {"U8", New Byte() {&HA}}, {"VariantBool", New Byte() {&H25}} } Dim verifier = CompileAndVerifyFieldMarshal(source, blobs) VerifyFieldMetadataDecoding(verifier, blobs) End Sub <Fact()> Public Sub SimpleTypes_Errors() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System.Runtime.InteropServices Class X <MarshalAs(CType(-1, UnmanagedType))> Dim MinValue_1 As X <MarshalAs(CType(&H20000000, UnmanagedType))> Dim MaxValue_1 As X End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40(source).VerifyDiagnostics( Diagnostic(ERRID.ERR_BadAttribute1, "CType(-1, UnmanagedType)").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute"), Diagnostic(ERRID.ERR_BadAttribute1, "CType(&H20000000, UnmanagedType)").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute")) End Sub ''' <summary> ''' (type, IidParamIndex), others ignored, field type ignored ''' </summary> <Fact> Public Sub ComInterfaces() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Public Class X <MarshalAs(UnmanagedType.IDispatch, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=0, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public IDispatch As Byte <MarshalAs(UnmanagedType.[Interface], ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public [Interface] As X <MarshalAs(UnmanagedType.IUnknown, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=2, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public IUnknown As X() <MarshalAs(UnmanagedType.IUnknown, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=&H1FFFFFFF, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public MaxValue As Integer <MarshalAs(UnmanagedType.IUnknown, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=&H123456, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public m_123456 As Integer <MarshalAs(UnmanagedType.IUnknown, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=&H1000, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public m_0x1000 As X <MarshalAs(UnmanagedType.IDispatch)> Public [Default] As Integer End Class ]]> </file> </compilation> Dim blobs = New Dictionary(Of String, Byte()) From { {"IDispatch", New Byte() {&H1A, &H0}}, {"Interface", New Byte() {&H1C, &H1}}, {"IUnknown", New Byte() {&H19, &H2}}, {"MaxValue", New Byte() {&H19, &HDF, &HFF, &HFF, &HFF}}, {"m_123456", New Byte() {&H19, &HC0, &H12, &H34, &H56}}, {"m_0x1000", New Byte() {&H19, &H90, &H0}}, {"Default", New Byte() {&H1A}} } Dim verifier = CompileAndVerifyFieldMarshal(source, blobs) VerifyFieldMetadataDecoding(verifier, blobs) End Sub <Fact()> Public Sub ComInterfaces_Errors() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System.Runtime.InteropServices Class X <MarshalAs(UnmanagedType.IDispatch, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Dim IDispatch_MinValue_1 As Integer <MarshalAs(UnmanagedType.[Interface], ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Dim Interface_MinValue_1 As Integer <MarshalAs(UnmanagedType.IUnknown, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Dim IUnknown_MinValue_1 As Integer <MarshalAs(UnmanagedType.IUnknown, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=&H20000000, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Dim IUnknown_MaxValue_1 As Integer End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40(source).VerifyDiagnostics( Diagnostic(ERRID.ERR_BadAttribute1, "IidParameterIndex:=-1").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute"), Diagnostic(ERRID.ERR_BadAttribute1, "IidParameterIndex:=-1").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute"), Diagnostic(ERRID.ERR_BadAttribute1, "IidParameterIndex:=-1").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute"), Diagnostic(ERRID.ERR_BadAttribute1, "IidParameterIndex:=&H20000000").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute")) End Sub ''' <summary> ''' (ArraySubType, SizeConst, SizeParamIndex), SafeArraySubType not allowed, others ignored ''' </summary> <Fact> Public Sub NativeTypeArray() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Public Class X <MarshalAs(UnmanagedType.LPArray)> Public LPArray0 As Integer <MarshalAs(UnmanagedType.LPArray, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArrayUserDefinedSubType:=Nothing)> Public LPArray1 As Integer <MarshalAs(UnmanagedType.LPArray, ArraySubType:=UnmanagedType.ByValTStr, SizeConst:=0, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArrayUserDefinedSubType:=Nothing)> Public LPArray2 As Integer <MarshalAs(UnmanagedType.LPArray, ArraySubType:=UnmanagedType.ByValTStr, SizeConst:=&H1FFFFFFF, SizeParamIndex:=Short.MaxValue, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArrayUserDefinedSubType:=Nothing)> Public LPArray3 As Integer <MarshalAs(UnmanagedType.LPArray, ArraySubType:=DirectCast(&H50, UnmanagedType))> Public LPArray4 As Integer <MarshalAs(UnmanagedType.LPArray, ArraySubType:=DirectCast(&H1FFFFFFF, UnmanagedType))> Public LPArray5 As Integer <MarshalAs(UnmanagedType.LPArray, ArraySubType:=DirectCast(0, UnmanagedType))> Public LPArray6 As Integer End Class ]]> </file> </compilation> Dim blobs = New Dictionary(Of String, Byte()) From { {"LPArray0", New Byte() {&H2A, &H50}}, {"LPArray1", New Byte() {&H2A, &H17}}, {"LPArray2", New Byte() {&H2A, &H17, &H0, &H0, &H0}}, {"LPArray3", New Byte() {&H2A, &H17, &HC0, &H0, &H7F, &HFF, &HDF, &HFF, &HFF, &HFF, &H1}}, {"LPArray4", New Byte() {&H2A, &H50}}, {"LPArray5", New Byte() {&H2A, &HDF, &HFF, &HFF, &HFF}}, {"LPArray6", New Byte() {&H2A, &H0}} } Dim verifier = CompileAndVerifyFieldMarshal(source, blobs) VerifyFieldMetadataDecoding(verifier, blobs) End Sub <Fact()> Public Sub NativeTypeArray_ElementTypes() Dim source As StringBuilder = New StringBuilder(<text> Imports System Imports System.Runtime.InteropServices Class X </text>.Value) Dim expectedBlobs = New Dictionary(Of String, Byte())() For i = 0 To SByte.MaxValue If i <> DirectCast(UnmanagedType.CustomMarshaler, Integer) Then Dim fldName As String = String.Format("m_{0:X}", i) source.AppendLine(String.Format("<MarshalAs(UnmanagedType.LPArray, ArraySubType := CType(&H{0:X}, UnmanagedType))>Dim {1} As Integer", i, fldName)) expectedBlobs.Add(fldName, New Byte() {&H2A, CByte(i)}) End If Next source.AppendLine("End Class") CompileAndVerifyFieldMarshal(source.ToString(), expectedBlobs) End Sub <Fact()> Public Sub NativeTypeArray_Errors() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Class X <MarshalAs(UnmanagedType.LPArray, ArraySubType:=UnmanagedType.ByValTStr, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Dim LPArray_e0 As Integer <MarshalAs(UnmanagedType.LPArray, ArraySubType:=UnmanagedType.ByValTStr, SizeConst:=-1)> Dim LPArray_e1 As Integer <MarshalAs(UnmanagedType.LPArray, ArraySubType:=UnmanagedType.ByValTStr, SizeConst:=0, SizeParamIndex:=-1)> Dim LPArray_e2 As Integer <MarshalAs(UnmanagedType.LPArray, ArraySubType:=UnmanagedType.ByValTStr, SizeConst:=Int32.MaxValue, SizeParamIndex:=Int16.MaxValue)> Dim LPArray_e3 As Integer <MarshalAs(UnmanagedType.LPArray, ArraySubType:=UnmanagedType.U8, SizeConst:=Int32.MaxValue / 4 + 1, SizeParamIndex:=Int16.MaxValue)> Dim LPArray_e4 As Integer <MarshalAs(UnmanagedType.LPArray, ArraySubType:=UnmanagedType.CustomMarshaler)> Dim LPArray_e5 As Integer <MarshalAs(UnmanagedType.LPArray, SafeArraySubType:=VarEnum.VT_I1)> Dim LPArray_e6 As Integer <MarshalAs(UnmanagedType.LPArray, ArraySubType:=DirectCast(&H20000000, UnmanagedType))> Dim LPArray_e7 As Integer <MarshalAs(UnmanagedType.LPArray, ArraySubType:=DirectCast((-1), UnmanagedType))> Dim LPArray_e8 As Integer End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40(source).VerifyDiagnostics( Diagnostic(ERRID.ERR_ParameterNotValidForType, "SafeArraySubType:=VarEnum.VT_BSTR"), Diagnostic(ERRID.ERR_BadAttribute1, "SizeConst:=-1").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute"), Diagnostic(ERRID.ERR_BadAttribute1, "SizeParamIndex:=-1").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute"), Diagnostic(ERRID.ERR_BadAttribute1, "SizeConst:=-1").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute"), Diagnostic(ERRID.ERR_BadAttribute1, "SizeParamIndex:=-1").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute"), Diagnostic(ERRID.ERR_BadAttribute1, "SizeConst:=Int32.MaxValue").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute"), Diagnostic(ERRID.ERR_BadAttribute1, "SizeConst:=Int32.MaxValue / 4 + 1").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute"), Diagnostic(ERRID.ERR_BadAttribute1, "ArraySubType:=UnmanagedType.CustomMarshaler").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute"), Diagnostic(ERRID.ERR_ParameterNotValidForType, "SafeArraySubType:=VarEnum.VT_I1"), Diagnostic(ERRID.ERR_BadAttribute1, "ArraySubType:=DirectCast(&H20000000, UnmanagedType)").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute"), Diagnostic(ERRID.ERR_BadAttribute1, "ArraySubType:=DirectCast((-1), UnmanagedType)").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute")) End Sub ''' <summary> ''' (ArraySubType, SizeConst), (SizeParamIndex, SafeArraySubType) not allowed, others ignored ''' </summary> <Fact> Public Sub NativeTypeFixedArray() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Public Class X <MarshalAs(UnmanagedType.ByValArray)> Public ByValArray0 As Integer <MarshalAs(UnmanagedType.ByValArray, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArrayUserDefinedSubType:=Nothing)> Public ByValArray1 As Integer <MarshalAs(UnmanagedType.ByValArray, ArraySubType:=UnmanagedType.ByValTStr, SizeConst:=0, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArrayUserDefinedSubType:=Nothing)> Public ByValArray2 As Integer <MarshalAs(UnmanagedType.ByValArray, ArraySubType:=UnmanagedType.ByValTStr, SizeConst:=(Int32.MaxValue - 3) / 4, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArrayUserDefinedSubType:=Nothing)> Public ByValArray3 As Integer <MarshalAs(UnmanagedType.ByValArray, ArraySubType:=UnmanagedType.AsAny)> Public ByValArray4 As Integer <MarshalAs(UnmanagedType.ByValArray, ArraySubType:=UnmanagedType.CustomMarshaler)> Public ByValArray5 As Integer End Class ]]> </file> </compilation> Dim blobs = New Dictionary(Of String, Byte()) From { {"ByValArray0", New Byte() {&H1E, &H1}}, {"ByValArray1", New Byte() {&H1E, &H1, &H17}}, {"ByValArray2", New Byte() {&H1E, &H0, &H17}}, {"ByValArray3", New Byte() {&H1E, &HDF, &HFF, &HFF, &HFF, &H17}}, {"ByValArray4", New Byte() {&H1E, &H1, &H28}}, {"ByValArray5", New Byte() {&H1E, &H1, &H2C}} } Dim verifier = CompileAndVerifyFieldMarshal(source, blobs) VerifyFieldMetadataDecoding(verifier, blobs) End Sub <Fact()> Public Sub NativeTypeFixedArray_ElementTypes() Dim source As StringBuilder = New StringBuilder(<text> Imports System Imports System.Runtime.InteropServices Class X </text>.Value) Dim expectedBlobs = New Dictionary(Of String, Byte())() Dim i As Integer = 0 While i < SByte.MaxValue Dim fldName As String = String.Format("m_{0:X}", i) source.AppendLine(String.Format("<MarshalAs(UnmanagedType.ByValArray, ArraySubType := CType(&H{0:X}, UnmanagedType))>Dim {1} As Integer", i, fldName)) expectedBlobs.Add(fldName, New Byte() {&H1E, &H1, CByte(i)}) i = i + 1 End While source.AppendLine("End Class") CompileAndVerifyFieldMarshal(source.ToString(), expectedBlobs) End Sub <Fact()> Public Sub NativeTypeFixedArray_Errors() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Public Class X <MarshalAs(UnmanagedType.ByValArray, ArraySubType:=UnmanagedType.ByValTStr, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Dim ByValArray_e1 As Integer <MarshalAs(UnmanagedType.ByValArray, SizeParamIndex:=Int16.MaxValue)> Dim ByValArray_e2 As Integer <MarshalAs(UnmanagedType.ByValArray, SafeArraySubType:=VarEnum.VT_I2)> Dim ByValArray_e3 As Integer <MarshalAs(UnmanagedType.ByValArray, ArraySubType:=UnmanagedType.ByValTStr, SizeConst:=&H20000000)> Dim ByValArray_e4 As Integer End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40(source).VerifyDiagnostics( Diagnostic(ERRID.ERR_ParameterNotValidForType, "SafeArraySubType:=VarEnum.VT_BSTR"), Diagnostic(ERRID.ERR_BadAttribute1, "SizeConst:=-1").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute"), Diagnostic(ERRID.ERR_ParameterNotValidForType, "SizeParamIndex:=-1"), Diagnostic(ERRID.ERR_ParameterNotValidForType, "SizeParamIndex:=Int16.MaxValue"), Diagnostic(ERRID.ERR_ParameterNotValidForType, "SafeArraySubType:=VarEnum.VT_I2"), Diagnostic(ERRID.ERR_BadAttribute1, "SizeConst:=&H20000000").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute")) End Sub ''' <summary> ''' (SafeArraySubType, SafeArrayUserDefinedSubType), (ArraySubType, SizeConst, SizeParamIndex) not allowed, ''' (SafeArraySubType, SafeArrayUserDefinedSubType) not allowed together unless VT_DISPATCH, VT_UNKNOWN, VT_RECORD; others ignored. ''' </summary> <Fact> Public Sub NativeTypeSafeArray() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Runtime.InteropServices Public Class X <MarshalAs(UnmanagedType.SafeArray)> Public SafeArray0 As Integer <MarshalAs(UnmanagedType.SafeArray, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR)> Public SafeArray1 As Integer <MarshalAs(UnmanagedType.SafeArray, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArrayUserDefinedSubType:=GetType(X))> Public SafeArray2 As Integer <MarshalAs(UnmanagedType.SafeArray, SafeArrayUserDefinedSubType:=Nothing)> Public SafeArray3 As Integer <MarshalAs(UnmanagedType.SafeArray, SafeArrayUserDefinedSubType:=GetType(Void))> Public SafeArray4 As Integer <MarshalAs(UnmanagedType.SafeArray, SafeArraySubType:=VarEnum.VT_EMPTY)> Public SafeArray8 As Integer <MarshalAs(UnmanagedType.SafeArray, SafeArraySubType:=VarEnum.VT_RECORD, SafeArrayUserDefinedSubType:=GetType(Integer()()))> Public SafeArray9 As Integer <MarshalAs(UnmanagedType.SafeArray, SafeArraySubType:=VarEnum.VT_RECORD, SafeArrayUserDefinedSubType:=GetType(Nullable(Of)))> Public SafeArray10 As Integer End Class ]]> </file> </compilation> Dim aqn = Encoding.ASCII.GetBytes("System.Int32[][], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089") Dim openGenericAqn = Encoding.ASCII.GetBytes("System.Nullable`1, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089") Dim blobs = New Dictionary(Of String, Byte()) From { {"SafeArray0", New Byte() {&H1D}}, {"SafeArray1", New Byte() {&H1D, &H8}}, {"SafeArray2", New Byte() {&H1D}}, {"SafeArray3", New Byte() {&H1D}}, {"SafeArray4", New Byte() {&H1D}}, {"SafeArray8", New Byte() {&H1D, &H0}}, {"SafeArray9", New Byte() {&H1D, &H24, CByte(aqn.Length)}.Append(aqn)}, {"SafeArray10", New Byte() {&H1D, &H24, CByte(openGenericAqn.Length)}.Append(openGenericAqn)} } Dim verifier = CompileAndVerifyFieldMarshal(source, blobs) VerifyFieldMetadataDecoding(verifier, blobs) End Sub <Fact> Public Sub NativeTypeSafeArray_CCIOnly() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Runtime.InteropServices Public Class C(Of T) Public Class D(Of S) Public Class E End Class End Class End Class Public Class X <MarshalAs(UnmanagedType.SafeArray, SafeArraySubType:=VarEnum.VT_RECORD, SafeArrayUserDefinedSubType:=GetType(C(Of Integer).D(Of Boolean).E))> Public SafeArray11 As Integer End Class ]]> </file> </compilation> Dim nestedAqn = Encoding.ASCII.GetBytes("C`1+D`1+E[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]") Dim blobs = New Dictionary(Of String, Byte()) From { {"SafeArray11", New Byte() {&H1D, &H24, &H80, &HC4}.Append(nestedAqn)} } ' RefEmit has slightly different encoding of the type name Dim verifier = CompileAndVerifyFieldMarshal(source, blobs) VerifyFieldMetadataDecoding(verifier, blobs) End Sub <Fact()> Public Sub NativeTypeSafeArray_RefEmitDiffers() Dim source = <![CDATA[ Imports System Imports System.Collections.Generic Imports System.Runtime.InteropServices Public Class X <MarshalAs(UnmanagedType.SafeArray, SafeArraySubType:=VarEnum.VT_DISPATCH, SafeArrayUserDefinedSubType:=GetType(List(Of X)()()))> Dim SafeArray5 As Integer <MarshalAs(UnmanagedType.SafeArray, SafeArraySubType:=VarEnum.VT_UNKNOWN, SafeArrayUserDefinedSubType:=GetType(X))> Dim SafeArray6 As Integer <MarshalAs(UnmanagedType.SafeArray, SafeArraySubType:=VarEnum.VT_RECORD, SafeArrayUserDefinedSubType:=GetType(X))> Dim SafeArray7 As Integer End Class ]]>.Value Dim e = Encoding.ASCII Dim cciBlobs = New Dictionary(Of String, Byte()) From { {"SafeArray5", New Byte() {&H1D, &H9, &H75}.Append(e.GetBytes("System.Collections.Generic.List`1[X][][], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"))}, {"SafeArray6", New Byte() {&H1D, &HD, &H1, &H58}}, {"SafeArray7", New Byte() {&H1D, &H24, &H1, &H58}} } CompileAndVerifyFieldMarshal(source, cciBlobs) End Sub <Fact()> Public Sub NativeTypeSafeArray_Errors() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System.Runtime.InteropServices Public Class X <MarshalAs(UnmanagedType.SafeArray, ArraySubType:=UnmanagedType.ByValTStr, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Dim SafeArray_e1 As Integer <MarshalAs(UnmanagedType.SafeArray, ArraySubType:=UnmanagedType.ByValTStr)> Dim SafeArray_e2 As Integer <MarshalAs(UnmanagedType.SafeArray, SizeConst:=1)> Dim SafeArray_e3 As Integer <MarshalAs(UnmanagedType.SafeArray, SizeParamIndex:=1)> Dim SafeArray_e4 As Integer <MarshalAs(UnmanagedType.SafeArray, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing)> Dim SafeArray_e5 As Integer <MarshalAs(UnmanagedType.SafeArray, SafeArrayUserDefinedSubType:=Nothing, SafeArraySubType:=VarEnum.VT_BLOB)> Dim SafeArray_e6 As Integer <MarshalAs(UnmanagedType.SafeArray, SafeArrayUserDefinedSubType:=GetType(Integer), SafeArraySubType:=0)> Dim SafeArray_e7 As Integer End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40(source).VerifyDiagnostics( Diagnostic(ERRID.ERR_ParameterNotValidForType, "ArraySubType:=UnmanagedType.ByValTStr"), Diagnostic(ERRID.ERR_ParameterNotValidForType, "SizeConst:=-1"), Diagnostic(ERRID.ERR_ParameterNotValidForType, "SizeParamIndex:=-1"), Diagnostic(ERRID.ERR_ParameterNotValidForType, "SafeArrayUserDefinedSubType:=Nothing"), Diagnostic(ERRID.ERR_ParameterNotValidForType, "ArraySubType:=UnmanagedType.ByValTStr"), Diagnostic(ERRID.ERR_ParameterNotValidForType, "SizeConst:=1"), Diagnostic(ERRID.ERR_ParameterNotValidForType, "SizeParamIndex:=1"), Diagnostic(ERRID.ERR_ParameterNotValidForType, "SafeArrayUserDefinedSubType:=Nothing"), Diagnostic(ERRID.ERR_ParameterNotValidForType, "SafeArrayUserDefinedSubType:=Nothing"), Diagnostic(ERRID.ERR_ParameterNotValidForType, "SafeArrayUserDefinedSubType:=GetType(Integer)")) End Sub ''' <summary> ''' (SizeConst - required), (SizeParamIndex, ArraySubType) not allowed ''' </summary> <Fact> Public Sub NativeTypeFixedSysString() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Public Class X <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=1)> Public ByValTStr1 As Integer <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=&H1FFFFFFF, SafeArrayUserDefinedSubType:=GetType(Integer), IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing)> Public ByValTStr2 As Integer End Class ]]> </file> </compilation> Dim blobs = New Dictionary(Of String, Byte()) From { {"ByValTStr1", New Byte() {&H17, &H1}}, {"ByValTStr2", New Byte() {&H17, &HDF, &HFF, &HFF, &HFF}} } Dim verifier = CompileAndVerifyFieldMarshal(source, blobs) VerifyFieldMetadataDecoding(verifier, blobs) End Sub <Fact()> Public Sub NativeTypeFixedSysString_Errors() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Public Class X <MarshalAs(UnmanagedType.ByValTStr, ArraySubType:=UnmanagedType.ByValTStr, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Dim ByValTStr_e1 As Integer <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=-1)> Dim ByValTStr_e2 As Integer <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=(Int32.MaxValue - 3) / 4 + 1)> Dim ByValTStr_e3 As Integer <MarshalAs(UnmanagedType.ByValTStr)> Dim ByValTStr_e4 As Integer <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=1, SizeParamIndex:=1)> Dim ByValTStr_e5 As Integer <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=1, ArraySubType:=UnmanagedType.ByValTStr)> Dim ByValTStr_e6 As Integer <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=1, SafeArraySubType:=VarEnum.VT_BSTR)> Dim ByValTStr_e7 As Integer End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40(source).VerifyDiagnostics( Diagnostic(ERRID.ERR_ParameterNotValidForType, "ArraySubType:=UnmanagedType.ByValTStr"), Diagnostic(ERRID.ERR_BadAttribute1, "SizeConst:=-1").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute"), Diagnostic(ERRID.ERR_ParameterNotValidForType, "SizeParamIndex:=-1"), Diagnostic(ERRID.ERR_AttributeParameterRequired1, "MarshalAs").WithArguments("SizeConst"), Diagnostic(ERRID.ERR_BadAttribute1, "SizeConst:=-1").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute"), Diagnostic(ERRID.ERR_AttributeParameterRequired1, "MarshalAs").WithArguments("SizeConst"), Diagnostic(ERRID.ERR_BadAttribute1, "SizeConst:=(Int32.MaxValue - 3) / 4 + 1").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute"), Diagnostic(ERRID.ERR_AttributeParameterRequired1, "MarshalAs").WithArguments("SizeConst"), Diagnostic(ERRID.ERR_ParameterNotValidForType, "SizeParamIndex:=1"), Diagnostic(ERRID.ERR_ParameterNotValidForType, "ArraySubType:=UnmanagedType.ByValTStr")) End Sub ''' <summary> ''' Custom (MarshalType, MarshalTypeRef, MarshalCookie) one of {MarshalType, MarshalTypeRef} required, others ignored ''' </summary> <Fact> Public Sub CustomMarshal() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Imports Microsoft.VisualBasic.Strings Public Class X <MarshalAs(UnmanagedType.CustomMarshaler, MarshalType:=Nothing)> Public CustomMarshaler1 As Integer <MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef:=Nothing)> Public CustomMarshaler2 As Integer <MarshalAs(UnmanagedType.CustomMarshaler, MarshalType:="foo", MarshalTypeRef:=GetType(Integer))> Public CustomMarshaler3 As Integer <MarshalAs(UnmanagedType.CustomMarshaler, MarshalType:=ChrW(&H1234) & "f" & ChrW(0) & "oozzz")> Public CustomMarshaler4 As Integer <MarshalAs(UnmanagedType.CustomMarshaler, MarshalType:="f" & ChrW(0) & "oozzz")> Public CustomMarshaler5 As Integer <MarshalAs(UnmanagedType.CustomMarshaler, MarshalType:="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")> Public CustomMarshaler6 As Integer <MarshalAs(UnmanagedType.CustomMarshaler, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public CustomMarshaler7 As Integer <MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef:=GetType(Integer))> Public CustomMarshaler8 As Integer <MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef:=GetType(Integer), MarshalType:="foo", MarshalCookie:="hello" & ChrW(0) & "world(" & ChrW(&H1234) & ")")> Public CustomMarshaler9 As Integer <MarshalAs(UnmanagedType.CustomMarshaler, MarshalType:=Nothing, MarshalTypeRef:=GetType(Integer))> Public CustomMarshaler10 As Integer <MarshalAs(UnmanagedType.CustomMarshaler, MarshalType:="foo", MarshalTypeRef:=Nothing)> Public CustomMarshaler11 As Integer <MarshalAs(UnmanagedType.CustomMarshaler, MarshalType:=Nothing, MarshalTypeRef:=Nothing)> Public CustomMarshaler12 As Integer <MarshalAs(UnmanagedType.CustomMarshaler, MarshalType:="aaa" & ChrW(0) & "bbb", MarshalCookie:="ccc" & ChrW(0) & "ddd")> Public CustomMarshaler13 As Integer <MarshalAs(UnmanagedType.CustomMarshaler, MarshalType:=ChrW(&HD869) & ChrW(&HDED6), MarshalCookie:=ChrW(&HD869) & ChrW(&HDED6))> Public CustomMarshaler14 As Integer End Class ]]> </file> </compilation> Dim blobs = New Dictionary(Of String, Byte()) From { {"CustomMarshaler1", New Byte() {&H2C, &H0, &H0, &H0, &H0}}, {"CustomMarshaler2", New Byte() {&H2C, &H0, &H0, &H0, &H0}}, {"CustomMarshaler3", New Byte() {&H2C, &H0, &H0, &H3, &H66, &H6F, &H6F, &H0}}, {"CustomMarshaler4", New Byte() {&H2C, &H0, &H0, &HA, &HE1, &H88, &HB4, &H66, &H0, &H6F, &H6F, &H7A, &H7A, &H7A, &H0}}, {"CustomMarshaler5", New Byte() {&H2C, &H0, &H0, &H7, &H66, &H0, &H6F, &H6F, &H7A, &H7A, &H7A, &H0}}, {"CustomMarshaler6", New Byte() {&H2C, &H0, &H0, &H60}.Append(Encoding.UTF8.GetBytes("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" & ChrW(0)))}, {"CustomMarshaler7", New Byte() {&H2C, &H0, &H0, &H0, &H0}}, {"CustomMarshaler8", New Byte() {&H2C, &H0, &H0, &H59}.Append(Encoding.UTF8.GetBytes("System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" & ChrW(0)))}, {"CustomMarshaler9", New Byte() {&H2C, &H0, &H0, &H3, &H66, &H6F, &H6F, &H10, &H68, &H65, &H6C, &H6C, &H6F, &H0, &H77, &H6F, &H72, &H6C, &H64, &H28, &HE1, &H88, &HB4, &H29}}, {"CustomMarshaler10", New Byte() {&H2C, &H0, &H0, &H0, &H0}}, {"CustomMarshaler11", New Byte() {&H2C, &H0, &H0, &H3, &H66, &H6F, &H6F, &H0}}, {"CustomMarshaler12", New Byte() {&H2C, &H0, &H0, &H0, &H0}}, {"CustomMarshaler13", New Byte() {&H2C, &H0, &H0, &H7, &H61, &H61, &H61, &H0, &H62, &H62, &H62, &H7, &H63, &H63, &H63, &H0, &H64, &H64, &H64}}, {"CustomMarshaler14", New Byte() {&H2C, &H0, &H0, &H4, &HF0, &HAA, &H9B, &H96, &H4, &HF0, &HAA, &H9B, &H96}} } Dim verifier = CompileAndVerifyFieldMarshal(source, blobs) VerifyFieldMetadataDecoding(verifier, blobs) End Sub <Fact()> Public Sub CustomMarshal_Errors() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System.Runtime.InteropServices Imports Microsoft.VisualBasic.Strings Public Class X <MarshalAs(UnmanagedType.CustomMarshaler)> Dim CustomMarshaler_e0 As Integer <MarshalAs(UnmanagedType.CustomMarshaler, MarshalType:="a" & ChrW(&HDC00) & "b", MarshalCookie:="b")> Dim CustomMarshaler_e1 As Integer <MarshalAs(UnmanagedType.CustomMarshaler, MarshalType:="x", MarshalCookie:="y" & ChrW(&HDC00))> Dim CustomMarshaler_e2 As Integer End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics( Diagnostic(ERRID.ERR_AttributeParameterRequired2, "MarshalAs").WithArguments("MarshalType", "MarshalTypeRef"), Diagnostic(ERRID.ERR_BadAttribute1, "MarshalType:=""a"" & ChrW(&HDC00) & ""b""").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute"), Diagnostic(ERRID.ERR_BadAttribute1, "MarshalCookie:=""y"" & ChrW(&HDC00)").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute")) End Sub <Fact()> Public Sub Events_Error() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Class C <MarshalAs(UnmanagedType.Bool)> Event e As Action End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40(source).VerifyDiagnostics( Diagnostic(ERRID.ERR_InvalidAttributeUsage2, "MarshalAs").WithArguments("MarshalAsAttribute", "e")) End Sub <Fact()> Public Sub MarshalAs_AllFieldTargets() Dim source = <compilation><file><![CDATA[ Imports System Imports System.Runtime.InteropServices Class Z <MarshalAs(UnmanagedType.Bool)> Dim f As Integer End Class Module M <MarshalAs(UnmanagedType.Bool)> Public WithEvents we As New Z End Module Enum En <MarshalAs(UnmanagedType.Bool)> A = 1 <MarshalAs(UnmanagedType.Bool)> B End Enum ]]></file></compilation> CompileAndVerifyFieldMarshal(source, Function(name, _omitted1) Return If(name = "f" Or name = "_we" Or name = "A" Or name = "B", New Byte() {&H2}, Nothing) End Function) End Sub <Fact()> Public Sub Parameters() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Imports Microsoft.VisualBasic.Strings Class X Public Shared Function foo(<MarshalAs(UnmanagedType.IDispatch)> ByRef IDispatch As Integer, <MarshalAs(UnmanagedType.LPArray)> ByRef LPArray0 As Integer, <MarshalAs(UnmanagedType.SafeArray, SafeArraySubType:=VarEnum.VT_EMPTY)> SafeArray8 As Integer, <MarshalAs(UnmanagedType.CustomMarshaler, MarshalType:="aaa" & ChrW(0) & "bbb", MarshalCookie:="ccc" & ChrW(0) & "ddd")> CustomMarshaler13 As Integer) As <MarshalAs(UnmanagedType.LPStr)> X Return Nothing End Function End Class ]]> </file> </compilation> Dim blobs = New Dictionary(Of String, Byte())() From { {"foo:", New Byte() {&H14}}, {"foo:IDispatch", New Byte() {&H1A}}, {"foo:LPArray0", New Byte() {&H2A, &H50}}, {"foo:SafeArray8", New Byte() {&H1D, &H0}}, {"foo:CustomMarshaler13", New Byte() {&H2C, &H0, &H0, &H7, &H61, &H61, &H61, &H0, &H62, &H62, &H62, &H7, &H63, &H63, &H63, &H0, &H64, &H64, &H64}} } Dim verifier = CompileAndVerifyFieldMarshal(source, blobs, isField:=False) VerifyParameterMetadataDecoding(verifier, blobs) End Sub <Fact> Public Sub MarshalAs_AllParameterTargets_Events() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Module X Custom Event E As Action AddHandler(<MarshalAs(UnmanagedType.BStr)> eAdd As Action) End AddHandler RemoveHandler(<MarshalAs(UnmanagedType.BStr)> eRemove As Action) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Module ]]> </file> </compilation> Dim blobs = New Dictionary(Of String, Byte())() From { {"add_E:eAdd", New Byte() {&H13}}, {"remove_E:eRemove", New Byte() {&H13}} } Dim verifier = CompileAndVerifyFieldMarshal(source, blobs, isField:=False) VerifyParameterMetadataDecoding(verifier, blobs) End Sub <Fact> Public Sub MarshalAs_AllParameterTargets_Properties() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Module C Property P(<MarshalAs(UnmanagedType.I2)> pIndex As Integer) As <MarshalAs(UnmanagedType.I4)> Integer Get Return 0 End Get Set(<MarshalAs(UnmanagedType.I8)> pValue As Integer) End Set End Property Property Q As <MarshalAs(UnmanagedType.I4)> Integer Get Return 0 End Get Set(qValue As Integer) End Set End Property Property CRW As <MarshalAs(UnmanagedType.I4)> Integer WriteOnly Property CW As <MarshalAs(UnmanagedType.I4)> Integer Set(sValue As Integer) End Set End Property ReadOnly Property CR As <MarshalAs(UnmanagedType.I4)> Integer Get Return 0 End Get End Property End Module Interface I Property IRW As <MarshalAs(UnmanagedType.I4)> Integer ReadOnly Property IR As <MarshalAs(UnmanagedType.I4)> Integer WriteOnly Property IW As <MarshalAs(UnmanagedType.I4)> Integer Property IRW2(a As Integer, b As Integer) As <MarshalAs(UnmanagedType.I4)> Integer ReadOnly Property IR2(a As Integer, b As Integer) As <MarshalAs(UnmanagedType.I4)> Integer WriteOnly Property IW2(a As Integer, b As Integer) As <MarshalAs(UnmanagedType.I4)> Integer End Interface ]]> </file> </compilation> Dim i2 = New Byte() {&H5} Dim i4 = New Byte() {&H7} Dim i8 = New Byte() {&H9} ' Dev11 incorrectly applies return-type MarshalAs on the first parameter of an interface property. Dim blobs = New Dictionary(Of String, Byte())() From { {"get_P:", i4}, {"get_P:pIndex", i2}, {"set_P:pIndex", i2}, {"set_P:pValue", i8}, {"get_Q:", i4}, {"set_Q:qValue", Nothing}, {"get_CRW:", i4}, {"set_CRW:AutoPropertyValue", Nothing}, {"set_CW:sValue", Nothing}, {"get_CR:", i4}, {"get_IRW:", i4}, {"set_IRW:Value", i4}, {"get_IR:", i4}, {"set_IW:Value", i4}, {"get_IRW2:", i4}, {"get_IRW2:a", Nothing}, {"get_IRW2:b", Nothing}, {"set_IRW2:a", Nothing}, {"set_IRW2:b", Nothing}, {"set_IRW2:Value", i4}, {"get_IR2:", i4}, {"get_IR2:a", Nothing}, {"get_IR2:b", Nothing}, {"set_IW2:a", Nothing}, {"set_IW2:b", Nothing}, {"set_IW2:Value", i4} } Dim verifier = CompileAndVerifyFieldMarshal(source, blobs, isField:=False) CompilationUtils.AssertTheseDiagnostics(verifier.Compilation, <errors><![CDATA[ BC42364: Attributes applied on a return type of a WriteOnly Property have no effect. WriteOnly Property CW As <MarshalAs(UnmanagedType.I4)> Integer ~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></errors>) VerifyParameterMetadataDecoding(verifier, blobs) End Sub <Fact> Public Sub MarshalAs_PropertyReturnType_MissingAccessors() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Module C Property Q As <MarshalAs(UnmanagedType.I4)> Integer End Property End Module ]]> </file> </compilation> Dim c = CreateCompilationWithMscorlib40AndVBRuntime(source) CompilationUtils.AssertTheseDiagnostics(c, <errors><![CDATA[ BC30124: Property without a 'ReadOnly' or 'WriteOnly' specifier must provide both a 'Get' and a 'Set'. Property Q As <MarshalAs(UnmanagedType.I4)> Integer ~ ]]></errors>) End Sub <Fact> Public Sub MarshalAs_AllParameterTargets_PartialSubs() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Partial Class X Private Partial Sub F(<MarshalAs(UnmanagedType.BStr)> pf As Integer) End Sub Private Sub F(pf As Integer) End Sub Private Partial Sub G(pg As Integer) End Sub Private Sub G(<MarshalAs(UnmanagedType.BStr)> pg As Integer) End Sub Private Sub H(<MarshalAs(UnmanagedType.BStr)> ph As Integer) End Sub Private Partial Sub H(ph As Integer) End Sub Private Sub I(pi As Integer) End Sub Private Partial Sub I(<MarshalAs(UnmanagedType.BStr)> pi As Integer) End Sub End Class ]]> </file> </compilation> Dim blobs = New Dictionary(Of String, Byte())() From { {"F:pf", New Byte() {&H13}}, {"G:pg", New Byte() {&H13}}, {"H:ph", New Byte() {&H13}}, {"I:pi", New Byte() {&H13}} } CompileAndVerifyFieldMarshal(source, blobs, isField:=False) End Sub <Fact> Public Sub MarshalAs_AllParameterTargets_Delegate() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Delegate Function D(<MarshalAs(UnmanagedType.BStr)>p As Integer, <MarshalAs(UnmanagedType.BStr)>ByRef q As Integer) As <MarshalAs(UnmanagedType.BStr)> Integer ]]> </file> </compilation> Dim blobs = New Dictionary(Of String, Byte())() From { {".ctor:TargetObject", Nothing}, {".ctor:TargetMethod", Nothing}, {"BeginInvoke:p", New Byte() {&H13}}, {"BeginInvoke:q", New Byte() {&H13}}, {"BeginInvoke:DelegateCallback", Nothing}, {"BeginInvoke:DelegateAsyncState", Nothing}, {"EndInvoke:p", New Byte() {&H13}}, {"EndInvoke:q", New Byte() {&H13}}, {"EndInvoke:DelegateAsyncResult", Nothing}, {"Invoke:", New Byte() {&H13}}, {"Invoke:p", New Byte() {&H13}}, {"Invoke:q", New Byte() {&H13}} } Dim verifier = CompileAndVerifyFieldMarshal(source, blobs, isField:=False) VerifyParameterMetadataDecoding(verifier, blobs) End Sub <Fact> Public Sub MarshalAs_AllParameterTargets_Declare() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Module M Declare Function Foo Lib "foo" ( <MarshalAs(UnmanagedType.BStr)> explicitInt As Integer, <MarshalAs(UnmanagedType.BStr)> ByRef explicitByRefInt As Integer, <MarshalAs(UnmanagedType.Bool)> explicitString As String, <MarshalAs(UnmanagedType.Bool)> ByRef explicitByRefString As String, pString As String, ByRef pByRefString As String, pInt As Integer, ByRef pByRefInt As Integer ) As <MarshalAs(UnmanagedType.BStr)> Integer End Module ]]> </file> </compilation> Const bstr = &H13 Const bool = &H2 Const byvalstr = &H22 Const ansi_bstr = &H23 Dim blobs = New Dictionary(Of String, Byte())() From { {"Foo:", New Byte() {bstr}}, {"Foo:explicitInt", New Byte() {bstr}}, {"Foo:explicitByRefInt", New Byte() {bstr}}, {"Foo:explicitString", New Byte() {bool}}, {"Foo:explicitByRefString", New Byte() {bool}}, {"Foo:pString", New Byte() {byvalstr}}, {"Foo:pByRefString", New Byte() {ansi_bstr}}, {"Foo:pInt", Nothing}, {"Foo:pByRefInt", Nothing} } Dim verifier = CompileAndVerifyFieldMarshal(source, blobs, isField:=False, expectedSignatures:= { Signature("M", "Foo", ".method [System.Runtime.InteropServices.DllImportAttribute(""foo"", EntryPoint = ""Foo"", CharSet = 2, ExactSpelling = True, SetLastError = True, PreserveSig = True, CallingConvention = 1, BestFitMapping = False, ThrowOnUnmappableChar = False)] " & "[System.Runtime.InteropServices.PreserveSigAttribute()] " & "public static pinvokeimpl System.Int32 Foo(" & "System.Int32 explicitInt, " & "System.Int32& explicitByRefInt, " & "System.String explicitString, " & "System.String& explicitByRefString, " & "System.String& pString, " & "System.String& pByRefString, " & "System.Int32 pInt, " & "System.Int32& pByRefInt" & ") cil managed preservesig") }) VerifyParameterMetadataDecoding(verifier, blobs) End Sub <Fact()> Public Sub Parameters_Errors() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System.Runtime.InteropServices Class X Public Shared Sub f1(<MarshalAs(UnmanagedType.ByValArray)> ByValArray As Integer, <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=1)> ByValTStr As Integer) End Sub Public Shared Function f2() As <MarshalAs(UnmanagedType.ByValArray)> Integer Return 0 End Function Public Shared Function f3() As <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=1)> Integer Return 0 End Function <MarshalAs(UnmanagedType.VBByRefStr)> Public field As Integer End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40(source).VerifyDiagnostics( Diagnostic(ERRID.ERR_MarshalUnmanagedTypeOnlyValidForFields, "UnmanagedType.ByValArray").WithArguments("ByValArray"), Diagnostic(ERRID.ERR_MarshalUnmanagedTypeOnlyValidForFields, "UnmanagedType.ByValTStr").WithArguments("ByValTStr"), Diagnostic(ERRID.ERR_MarshalUnmanagedTypeOnlyValidForFields, "UnmanagedType.ByValArray").WithArguments("ByValArray"), Diagnostic(ERRID.ERR_MarshalUnmanagedTypeOnlyValidForFields, "UnmanagedType.ByValTStr").WithArguments("ByValTStr"), Diagnostic(ERRID.ERR_MarshalUnmanagedTypeNotValidForFields, "UnmanagedType.VBByRefStr").WithArguments("VBByRefStr")) End Sub ''' <summary> ''' type only, only on parameters ''' </summary> <Fact> Public Sub NativeTypeByValStr() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Class X Shared Function f( <MarshalAs(UnmanagedType.VBByRefStr, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> ByRef VBByRefStr_e1 As Integer, _ <MarshalAs(UnmanagedType.VBByRefStr, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> VBByRefStr_e2 As Char(), _ <MarshalAs(UnmanagedType.VBByRefStr, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> VBByRefStr_e3 As Integer) _ As <MarshalAs(UnmanagedType.VBByRefStr, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Integer Return 0 End Function End Class ]]> </file> </compilation> Dim blobs = New Dictionary(Of String, Byte()) From { {"f:", New Byte() {&H22}}, {"f:VBByRefStr_e1", New Byte() {&H22}}, {"f:VBByRefStr_e2", New Byte() {&H22}}, {"f:VBByRefStr_e3", New Byte() {&H22}} } Dim verifier = CompileAndVerifyFieldMarshal(source, blobs, isField:=False) VerifyParameterMetadataDecoding(verifier, blobs) End Sub End Class End Namespace
-1
dotnet/roslyn
56,011
React to string comparison changing on .NET Core
The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
jaredpar
"2021-08-30T17:18:52Z"
"2021-08-30T20:20:04Z"
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
4d99cda6e446e77dbb302e26388c1093bd3ef569
React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
./src/Compilers/VisualBasic/Portable/Declarations/DeclarationTreeBuilder.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Friend NotInheritable Class DeclarationTreeBuilder Inherits VisualBasicSyntaxVisitor(Of SingleNamespaceOrTypeDeclaration) ' The root namespace, expressing as an array of strings, one for each component. Private ReadOnly _rootNamespace As ImmutableArray(Of String) Private ReadOnly _scriptClassName As String Private ReadOnly _isSubmission As Boolean Private ReadOnly _syntaxTree As SyntaxTree Public Shared Function ForTree(tree As SyntaxTree, rootNamespace As ImmutableArray(Of String), scriptClassName As String, isSubmission As Boolean) As RootSingleNamespaceDeclaration Dim builder = New DeclarationTreeBuilder(tree, rootNamespace, scriptClassName, isSubmission) Dim decl = DirectCast(builder.ForDeclaration(tree.GetRoot()), RootSingleNamespaceDeclaration) Return decl End Function Private Sub New(syntaxTree As SyntaxTree, rootNamespace As ImmutableArray(Of String), scriptClassName As String, isSubmission As Boolean) _syntaxTree = syntaxTree _rootNamespace = rootNamespace _scriptClassName = scriptClassName _isSubmission = isSubmission End Sub Private Function ForDeclaration(node As SyntaxNode) As SingleNamespaceOrTypeDeclaration Return Visit(node) End Function Private Function VisitNamespaceChildren(node As VisualBasicSyntaxNode, members As SyntaxList(Of StatementSyntax)) As ImmutableArray(Of SingleNamespaceOrTypeDeclaration) Dim implicitClass As SingleNamespaceOrTypeDeclaration = Nothing Dim childrenBuilder = VisitNamespaceChildren(node, members, implicitClass) If implicitClass IsNot Nothing Then childrenBuilder.Add(implicitClass) End If Return childrenBuilder.ToImmutableAndFree() End Function Private Function VisitNamespaceChildren(node As VisualBasicSyntaxNode, members As SyntaxList(Of StatementSyntax), <Out()> ByRef implicitClass As SingleNamespaceOrTypeDeclaration) As ArrayBuilder(Of SingleNamespaceOrTypeDeclaration) Dim children = ArrayBuilder(Of SingleNamespaceOrTypeDeclaration).GetInstance() Dim implicitClassTypeChildren = ArrayBuilder(Of SingleTypeDeclaration).GetInstance() ' We look for any members that are not allowed in namespace. ' If there are any we create an implicit class to wrap them. Dim requiresImplicitClass = False For Each member In members Dim namespaceOrType As SingleNamespaceOrTypeDeclaration = Visit(member) If namespaceOrType IsNot Nothing Then If namespaceOrType.Kind = DeclarationKind.EventSyntheticDelegate Then ' broken code scenario. Event declared in namespace created a delegate declaration which should go into the ' implicit class implicitClassTypeChildren.Add(DirectCast(namespaceOrType, SingleTypeDeclaration)) requiresImplicitClass = True Else children.Add(namespaceOrType) End If ElseIf Not requiresImplicitClass Then requiresImplicitClass = member.Kind <> SyntaxKind.IncompleteMember AndAlso member.Kind <> SyntaxKind.EmptyStatement End If Next If requiresImplicitClass Then ' The implicit class is not static and has no extensions Dim declFlags As SingleTypeDeclaration.TypeDeclarationFlags = SingleTypeDeclaration.TypeDeclarationFlags.None Dim memberNames = GetNonTypeMemberNames(members, declFlags) implicitClass = CreateImplicitClass( node, memberNames, implicitClassTypeChildren.ToImmutable, declFlags) Else implicitClass = Nothing End If implicitClassTypeChildren.Free() Return children End Function Private Shared Function GetReferenceDirectives(compilationUnit As CompilationUnitSyntax) As ImmutableArray(Of ReferenceDirective) Dim directiveNodes = compilationUnit.GetReferenceDirectives( Function(d) Not d.File.ContainsDiagnostics AndAlso Not String.IsNullOrEmpty(d.File.ValueText)) If directiveNodes.Count = 0 Then Return ImmutableArray(Of ReferenceDirective).Empty End If Dim directives = ArrayBuilder(Of ReferenceDirective).GetInstance(directiveNodes.Count) For Each directiveNode In directiveNodes directives.Add(New ReferenceDirective(directiveNode.File.ValueText, New SourceLocation(directiveNode))) Next Return directives.ToImmutableAndFree() End Function Private Function CreateImplicitClass(parent As VisualBasicSyntaxNode, memberNames As ImmutableHashSet(Of String), children As ImmutableArray(Of SingleTypeDeclaration), declFlags As SingleTypeDeclaration.TypeDeclarationFlags) As SingleNamespaceOrTypeDeclaration Dim parentReference = _syntaxTree.GetReference(parent) Return New SingleTypeDeclaration( kind:=DeclarationKind.ImplicitClass, name:=TypeSymbol.ImplicitTypeName, arity:=0, modifiers:=DeclarationModifiers.Friend Or DeclarationModifiers.Partial Or DeclarationModifiers.NotInheritable, declFlags:=declFlags, syntaxReference:=parentReference, nameLocation:=parentReference.GetLocation(), memberNames:=memberNames, children:=children) End Function Private Function CreateScriptClass(parent As VisualBasicSyntaxNode, children As ImmutableArray(Of SingleTypeDeclaration), memberNames As ImmutableHashSet(Of String), declFlags As SingleTypeDeclaration.TypeDeclarationFlags) As SingleNamespaceOrTypeDeclaration Debug.Assert(parent.Kind = SyntaxKind.CompilationUnit AndAlso _syntaxTree.Options.Kind <> SourceCodeKind.Regular) ' script class is represented by the parent node: Dim parentReference = _syntaxTree.GetReference(parent) Dim fullName = _scriptClassName.Split("."c) ' Note: The symbol representing the merged declarations uses parentReference to enumerate non-type members. Dim decl As SingleNamespaceOrTypeDeclaration = New SingleTypeDeclaration( kind:=If(_isSubmission, DeclarationKind.Submission, DeclarationKind.Script), name:=fullName.Last(), arity:=0, modifiers:=DeclarationModifiers.Friend Or DeclarationModifiers.Partial Or DeclarationModifiers.NotInheritable, declFlags:=declFlags, syntaxReference:=parentReference, nameLocation:=parentReference.GetLocation(), memberNames:=memberNames, children:=children) For i = fullName.Length - 2 To 0 Step -1 decl = New SingleNamespaceDeclaration( name:=fullName(i), hasImports:=False, syntaxReference:=parentReference, nameLocation:=parentReference.GetLocation(), children:=ImmutableArray.Create(Of SingleNamespaceOrTypeDeclaration)(decl)) Next Return decl End Function Public Overrides Function VisitCompilationUnit(node As CompilationUnitSyntax) As SingleNamespaceOrTypeDeclaration Dim children As ImmutableArray(Of SingleNamespaceOrTypeDeclaration) Dim globalChildren As ImmutableArray(Of SingleNamespaceOrTypeDeclaration) = Nothing Dim nonGlobal As ImmutableArray(Of SingleNamespaceOrTypeDeclaration) = Nothing Dim syntaxRef = _syntaxTree.GetReference(node) Dim implicitClass As SingleNamespaceOrTypeDeclaration = Nothing Dim referenceDirectives As ImmutableArray(Of ReferenceDirective) If _syntaxTree.Options.Kind <> SourceCodeKind.Regular Then Dim childrenBuilder = ArrayBuilder(Of SingleNamespaceOrTypeDeclaration).GetInstance() Dim scriptChildren = ArrayBuilder(Of SingleTypeDeclaration).GetInstance() For Each member In node.Members Dim decl = Visit(member) If decl IsNot Nothing Then ' Although namespaces are not allowed in script code process them ' here as if they were to improve error reporting. If decl.Kind = DeclarationKind.Namespace Then childrenBuilder.Add(decl) Else scriptChildren.Add(DirectCast(decl, SingleTypeDeclaration)) End If End If Next 'Script class is not static and contains no extensions. Dim declFlags As SingleTypeDeclaration.TypeDeclarationFlags = SingleTypeDeclaration.TypeDeclarationFlags.None Dim memberNames = GetNonTypeMemberNames(node.Members, declFlags) implicitClass = CreateScriptClass(node, scriptChildren.ToImmutableAndFree(), memberNames, declFlags) children = childrenBuilder.ToImmutableAndFree() referenceDirectives = GetReferenceDirectives(node) Else children = VisitNamespaceChildren(node, node.Members, implicitClass).ToImmutableAndFree() referenceDirectives = ImmutableArray(Of ReferenceDirective).Empty End If ' Find children within NamespaceGlobal separately FindGlobalDeclarations(children, implicitClass, globalChildren, nonGlobal) If _rootNamespace.Length = 0 Then ' No project-level root namespace specified. Both global and nested children within the root. Return New RootSingleNamespaceDeclaration( hasImports:=True, treeNode:=_syntaxTree.GetReference(node), children:=globalChildren.Concat(nonGlobal), referenceDirectives:=referenceDirectives, hasAssemblyAttributes:=node.Attributes.Any) Else ' Project-level root namespace. All children without explicit global are children ' of the project-level root namespace. The root declaration has the project level namespace ' and global children within it. ' Note that we need to built the project level namespace even if it has no children [Bug 4879[ Dim projectNs = BuildRootNamespace(node, nonGlobal) globalChildren = globalChildren.Add(projectNs) Dim newChildren = globalChildren.OfType(Of SingleNamespaceOrTypeDeclaration).AsImmutable() Return New RootSingleNamespaceDeclaration( hasImports:=True, treeNode:=_syntaxTree.GetReference(node), children:=newChildren, referenceDirectives:=referenceDirectives, hasAssemblyAttributes:=node.Attributes.Any) End If End Function ' Given a set of single declarations, get the sets of global and non-global declarations. ' A regular declaration is put into "non-global declarations". ' A "Namespace Global" is not put in either place, but all its direct children are put into "global declarations". Private Sub FindGlobalDeclarations(declarations As ImmutableArray(Of SingleNamespaceOrTypeDeclaration), implicitClass As SingleNamespaceOrTypeDeclaration, ByRef globalDeclarations As ImmutableArray(Of SingleNamespaceOrTypeDeclaration), ByRef nonGlobal As ImmutableArray(Of SingleNamespaceOrTypeDeclaration)) Dim globalBuilder = ArrayBuilder(Of SingleNamespaceOrTypeDeclaration).GetInstance() Dim nonGlobalBuilder = ArrayBuilder(Of SingleNamespaceOrTypeDeclaration).GetInstance() If implicitClass IsNot Nothing Then nonGlobalBuilder.Add(implicitClass) End If For Each decl In declarations Dim nsDecl As SingleNamespaceDeclaration = TryCast(decl, SingleNamespaceDeclaration) If nsDecl IsNot Nothing AndAlso nsDecl.IsGlobalNamespace Then ' Namespace Global. globalBuilder.AddRange(nsDecl.Children) Else ' regular declaration nonGlobalBuilder.Add(decl) End If Next globalDeclarations = globalBuilder.ToImmutableAndFree() nonGlobal = nonGlobalBuilder.ToImmutableAndFree() End Sub Private Function UnescapeIdentifier(identifier As String) As String If identifier(0) = "[" Then Debug.Assert(identifier(identifier.Length - 1) = "]") Return identifier.Substring(1, identifier.Length - 2) Else Return identifier End If End Function ' Build the declaration for the root (project-level) namespace. Private Function BuildRootNamespace(node As CompilationUnitSyntax, children As ImmutableArray(Of SingleNamespaceOrTypeDeclaration)) As SingleNamespaceDeclaration Debug.Assert(_rootNamespace.Length > 0) Dim ns As SingleNamespaceDeclaration = Nothing ' The compilation node will count as a location for the innermost project level ' namespace. i.e. if the project level namespace is "Goo.Bar", then each compilation unit ' is a location for "Goo.Bar". "Goo" still has no syntax location though. ' ' By doing this we ensure that top level type and namespace declarations will have ' symbols whose parent namespace symbol points to the parent container CompilationUnit. ' This ensures parity with the case where their is no 'project-level' namespace and the ' global namespaces point to the compilation unit syntax. Dim syntaxReference = _syntaxTree.GetReference(node) Dim nameLocation = syntaxReference.GetLocation() ' traverse components from right to left For i = _rootNamespace.Length - 1 To 0 Step -1 ' treat all root namespace parts as implicitly escaped. ' a root namespace with a name "global" will actually create "Global.[global]" ns = New SingleNamespaceDeclaration( name:=UnescapeIdentifier(_rootNamespace(i)), hasImports:=True, syntaxReference:=syntaxReference, nameLocation:=nameLocation, children:=children, isPartOfRootNamespace:=True) ' Only the innermost namespace will point at compilation unit. All other outer ' namespaces will have no location. syntaxReference = Nothing nameLocation = Nothing ' This namespace is the child of the namespace to the left. children = ImmutableArray.Create(Of SingleNamespaceOrTypeDeclaration)(ns) Next Return ns End Function Public Overrides Function VisitNamespaceBlock(nsBlockSyntax As NamespaceBlockSyntax) As SingleNamespaceOrTypeDeclaration Dim nsDeclSyntax As NamespaceStatementSyntax = nsBlockSyntax.NamespaceStatement Dim children = VisitNamespaceChildren(nsBlockSyntax, nsBlockSyntax.Members) Dim name As NameSyntax = nsDeclSyntax.Name While TypeOf name Is QualifiedNameSyntax Dim dotted = DirectCast(name, QualifiedNameSyntax) Dim ns = New SingleNamespaceDeclaration( name:=dotted.Right.Identifier.ValueText, hasImports:=True, syntaxReference:=_syntaxTree.GetReference(dotted), nameLocation:=_syntaxTree.GetLocation(dotted.Right.Span), children:=children) children = {ns}.OfType(Of SingleNamespaceOrTypeDeclaration).AsImmutable() name = dotted.Left End While ' This is either the global namespace, or a regular namespace. Represent the global namespace ' with the empty string. If name.Kind = SyntaxKind.GlobalName Then If nsBlockSyntax.Parent.Kind = SyntaxKind.CompilationUnit Then ' Namespace Global only allowed as direct child of compilation. Return New GlobalNamespaceDeclaration( hasImports:=True, syntaxReference:=_syntaxTree.GetReference(name), nameLocation:=_syntaxTree.GetLocation(name.Span), children:=children) Else ' Error for this will be diagnosed later. Create a namespace named "Global" for error recovery. (see corresponding code in BinderFactory) Return New SingleNamespaceDeclaration( name:="Global", hasImports:=True, syntaxReference:=_syntaxTree.GetReference(name), nameLocation:=_syntaxTree.GetLocation(name.Span), children:=children) End If Else Return New SingleNamespaceDeclaration( name:=DirectCast(name, IdentifierNameSyntax).Identifier.ValueText, hasImports:=True, syntaxReference:=_syntaxTree.GetReference(name), nameLocation:=_syntaxTree.GetLocation(name.Span), children:=children) End If End Function Private Structure TypeBlockInfo Public ReadOnly TypeBlockSyntax As TypeBlockSyntax Public ReadOnly TypeDeclaration As SingleTypeDeclaration Public ReadOnly NestedTypes As ArrayBuilder(Of Integer) Public Sub New(typeBlockSyntax As TypeBlockSyntax) MyClass.New(typeBlockSyntax, Nothing, Nothing) End Sub Private Sub New(typeBlockSyntax As TypeBlockSyntax, declaration As SingleTypeDeclaration, nestedTypes As ArrayBuilder(Of Integer)) Me.TypeBlockSyntax = typeBlockSyntax Me.TypeDeclaration = declaration Me.NestedTypes = nestedTypes End Sub Public Function WithNestedTypes(nested As ArrayBuilder(Of Integer)) As TypeBlockInfo Debug.Assert(Me.TypeDeclaration Is Nothing) Debug.Assert(Me.NestedTypes Is Nothing) Debug.Assert(nested IsNot Nothing) Return New TypeBlockInfo(Me.TypeBlockSyntax, Nothing, nested) End Function Public Function WithDeclaration(declaration As SingleTypeDeclaration) As TypeBlockInfo Debug.Assert(Me.TypeDeclaration Is Nothing) Debug.Assert(declaration IsNot Nothing) Return New TypeBlockInfo(Me.TypeBlockSyntax, declaration, Me.NestedTypes) End Function End Structure Private Function VisitTypeBlockNew(topTypeBlockSyntax As TypeBlockSyntax) As SingleNamespaceOrTypeDeclaration Dim typeStack = ArrayBuilder(Of TypeBlockInfo).GetInstance typeStack.Add(New TypeBlockInfo(topTypeBlockSyntax)) ' Fill the chain with types Dim index As Integer = 0 While index < typeStack.Count Dim typeEntry As TypeBlockInfo = typeStack(index) Dim members As SyntaxList(Of StatementSyntax) = typeEntry.TypeBlockSyntax.Members If members.Count > 0 Then Dim nestedTypeIndices As ArrayBuilder(Of Integer) = Nothing For Each member In members Select Case member.Kind Case SyntaxKind.ModuleBlock, SyntaxKind.ClassBlock, SyntaxKind.StructureBlock, SyntaxKind.InterfaceBlock If nestedTypeIndices Is Nothing Then nestedTypeIndices = ArrayBuilder(Of Integer).GetInstance() End If nestedTypeIndices.Add(typeStack.Count) typeStack.Add(New TypeBlockInfo(DirectCast(member, TypeBlockSyntax))) End Select Next If nestedTypeIndices IsNot Nothing Then typeStack(index) = typeEntry.WithNestedTypes(nestedTypeIndices) End If End If index += 1 End While ' Process types Debug.Assert(index = typeStack.Count) Dim childrenBuilder = ArrayBuilder(Of SingleTypeDeclaration).GetInstance() While index > 0 index -= 1 Dim typeEntry As TypeBlockInfo = typeStack(index) Dim children = ImmutableArray(Of SingleTypeDeclaration).Empty Dim members As SyntaxList(Of StatementSyntax) = typeEntry.TypeBlockSyntax.Members If members.Count > 0 Then childrenBuilder.Clear() For Each member In members Select Case member.Kind Case SyntaxKind.ModuleBlock, SyntaxKind.ClassBlock, SyntaxKind.StructureBlock, SyntaxKind.InterfaceBlock ' should be processed already Case Else Dim typeDecl = TryCast(Visit(member), SingleTypeDeclaration) If typeDecl IsNot Nothing Then childrenBuilder.Add(typeDecl) End If End Select Next Dim nestedTypes As ArrayBuilder(Of Integer) = typeEntry.NestedTypes If nestedTypes IsNot Nothing Then For i = 0 To nestedTypes.Count - 1 childrenBuilder.Add(typeStack(nestedTypes(i)).TypeDeclaration) Next nestedTypes.Free() End If children = childrenBuilder.ToImmutable() End If Dim typeBlockSyntax As TypeBlockSyntax = typeEntry.TypeBlockSyntax Dim declarationSyntax As TypeStatementSyntax = typeBlockSyntax.BlockStatement ' Get the arity for things that can have arity. Dim typeArity As Integer = 0 Select Case typeBlockSyntax.Kind Case SyntaxKind.ClassBlock, SyntaxKind.StructureBlock, SyntaxKind.InterfaceBlock typeArity = GetArity(declarationSyntax.TypeParameterList) End Select Dim declFlags As SingleTypeDeclaration.TypeDeclarationFlags = If(declarationSyntax.AttributeLists.Any(), SingleTypeDeclaration.TypeDeclarationFlags.HasAnyAttributes, SingleTypeDeclaration.TypeDeclarationFlags.None) If (typeBlockSyntax.Inherits.Any) Then declFlags = declFlags Or SingleTypeDeclaration.TypeDeclarationFlags.HasBaseDeclarations End If Dim memberNames = GetNonTypeMemberNames(typeBlockSyntax.Members, declFlags) typeStack(index) = typeEntry.WithDeclaration( New SingleTypeDeclaration( kind:=GetKind(declarationSyntax.Kind), name:=declarationSyntax.Identifier.ValueText, arity:=typeArity, modifiers:=GetModifiers(declarationSyntax.Modifiers), declFlags:=declFlags, syntaxReference:=_syntaxTree.GetReference(typeBlockSyntax), nameLocation:=_syntaxTree.GetLocation(typeBlockSyntax.BlockStatement.Identifier.Span), memberNames:=memberNames, children:=children)) End While childrenBuilder.Free() Dim result As SingleNamespaceOrTypeDeclaration = typeStack(0).TypeDeclaration typeStack.Free() Return result End Function Public Overrides Function VisitModuleBlock(ByVal moduleBlockSyntax As ModuleBlockSyntax) As SingleNamespaceOrTypeDeclaration Return VisitTypeBlockNew(moduleBlockSyntax) End Function Public Overrides Function VisitClassBlock(ByVal classBlockSyntax As ClassBlockSyntax) As SingleNamespaceOrTypeDeclaration Return VisitTypeBlockNew(classBlockSyntax) End Function Public Overrides Function VisitStructureBlock(ByVal structureBlockSyntax As StructureBlockSyntax) As SingleNamespaceOrTypeDeclaration Return VisitTypeBlockNew(structureBlockSyntax) End Function Public Overrides Function VisitInterfaceBlock(ByVal interfaceBlockSyntax As InterfaceBlockSyntax) As SingleNamespaceOrTypeDeclaration Return VisitTypeBlockNew(interfaceBlockSyntax) End Function Public Overrides Function VisitEnumBlock(enumBlockSyntax As EnumBlockSyntax) As SingleNamespaceOrTypeDeclaration Dim declarationSyntax As EnumStatementSyntax = enumBlockSyntax.EnumStatement Dim declFlags As SingleTypeDeclaration.TypeDeclarationFlags = If(declarationSyntax.AttributeLists.Any(), SingleTypeDeclaration.TypeDeclarationFlags.HasAnyAttributes, SingleTypeDeclaration.TypeDeclarationFlags.None) If (declarationSyntax.UnderlyingType IsNot Nothing) Then declFlags = declFlags Or SingleTypeDeclaration.TypeDeclarationFlags.HasBaseDeclarations End If Dim memberNames = GetMemberNames(enumBlockSyntax, declFlags) Return New SingleTypeDeclaration( kind:=GetKind(declarationSyntax.Kind), name:=declarationSyntax.Identifier.ValueText, arity:=0, modifiers:=GetModifiers(declarationSyntax.Modifiers), declFlags:=declFlags, syntaxReference:=_syntaxTree.GetReference(enumBlockSyntax), nameLocation:=_syntaxTree.GetLocation(enumBlockSyntax.EnumStatement.Identifier.Span), memberNames:=memberNames, children:=VisitTypeChildren(enumBlockSyntax.Members)) End Function Private Function VisitTypeChildren(members As SyntaxList(Of StatementSyntax)) As ImmutableArray(Of SingleTypeDeclaration) If members.Count = 0 Then Return ImmutableArray(Of SingleTypeDeclaration).Empty End If Dim children = ArrayBuilder(Of SingleTypeDeclaration).GetInstance() For Each member In members Dim typeDecl = TryCast(Visit(member), SingleTypeDeclaration) If typeDecl IsNot Nothing Then children.Add(typeDecl) End If Next Return children.ToImmutableAndFree() End Function ''' <summary> ''' Pool of builders used to create our member name sets. Importantly, these use ''' <see cref="CaseInsensitiveComparison.Comparer"/> so that name lookup happens in an ''' appropriate manner for VB identifiers. This allows fast member name O(log(n)) even if ''' the casing doesn't match. ''' </summary> Private Shared ReadOnly s_memberNameBuilderPool As New ObjectPool(Of ImmutableHashSet(Of String).Builder)( Function() ImmutableHashSet.CreateBuilder(IdentifierComparison.Comparer)) Private Shared Function ToImmutableAndFree(builder As ImmutableHashSet(Of String).Builder) As ImmutableHashSet(Of String) Dim result = builder.ToImmutable() builder.Clear() s_memberNameBuilderPool.Free(builder) Return result End Function Private Function GetNonTypeMemberNames(members As SyntaxList(Of StatementSyntax), ByRef declFlags As SingleTypeDeclaration.TypeDeclarationFlags) As ImmutableHashSet(Of String) Dim anyMethodHadExtensionSyntax = False Dim anyMemberHasAttributes = False Dim anyNonTypeMembers = False Dim results = s_memberNameBuilderPool.Allocate() For Each statement In members Select Case statement.Kind Case SyntaxKind.FieldDeclaration anyNonTypeMembers = True Dim field = DirectCast(statement, FieldDeclarationSyntax) If field.AttributeLists.Any Then anyMemberHasAttributes = True End If For Each decl In field.Declarators For Each name In decl.Names results.Add(name.Identifier.ValueText) Next Next Case SyntaxKind.SubBlock, SyntaxKind.FunctionBlock, SyntaxKind.ConstructorBlock, SyntaxKind.OperatorBlock anyNonTypeMembers = True Dim methodDecl = DirectCast(statement, MethodBlockBaseSyntax).BlockStatement If methodDecl.AttributeLists.Any Then anyMemberHasAttributes = True End If AddMemberNames(methodDecl, results) Case SyntaxKind.PropertyBlock anyNonTypeMembers = True Dim propertyDecl = DirectCast(statement, PropertyBlockSyntax) If propertyDecl.PropertyStatement.AttributeLists.Any Then anyMemberHasAttributes = True Else For Each a In propertyDecl.Accessors If a.BlockStatement.AttributeLists.Any Then anyMemberHasAttributes = True End If Next End If AddMemberNames(propertyDecl.PropertyStatement, results) Case SyntaxKind.SubStatement, SyntaxKind.FunctionStatement, SyntaxKind.SubNewStatement, SyntaxKind.DeclareSubStatement, SyntaxKind.DeclareFunctionStatement, SyntaxKind.OperatorStatement, SyntaxKind.PropertyStatement anyNonTypeMembers = True Dim methodDecl = DirectCast(statement, MethodBaseSyntax) If methodDecl.AttributeLists.Any Then anyMemberHasAttributes = True End If AddMemberNames(methodDecl, results) Case SyntaxKind.EventBlock anyNonTypeMembers = True Dim eventDecl = DirectCast(statement, EventBlockSyntax) If eventDecl.EventStatement.AttributeLists.Any Then anyMemberHasAttributes = True Else For Each a In eventDecl.Accessors If a.BlockStatement.AttributeLists.Any Then anyMemberHasAttributes = True End If Next End If Dim name = eventDecl.EventStatement.Identifier.ValueText results.Add(name) Case SyntaxKind.EventStatement anyNonTypeMembers = True Dim eventDecl = DirectCast(statement, EventStatementSyntax) If eventDecl.AttributeLists.Any Then anyMemberHasAttributes = True End If Dim name = eventDecl.Identifier.ValueText results.Add(name) End Select Next If (anyMemberHasAttributes) Then declFlags = declFlags Or SingleTypeDeclaration.TypeDeclarationFlags.AnyMemberHasAttributes End If If (anyNonTypeMembers) Then declFlags = declFlags Or SingleTypeDeclaration.TypeDeclarationFlags.HasAnyNontypeMembers End If Return ToImmutableAndFree(results) End Function Private Function GetMemberNames(enumBlockSyntax As EnumBlockSyntax, ByRef declFlags As SingleTypeDeclaration.TypeDeclarationFlags) As ImmutableHashSet(Of String) Dim members = enumBlockSyntax.Members If (members.Count <> 0) Then declFlags = declFlags Or SingleTypeDeclaration.TypeDeclarationFlags.HasAnyNontypeMembers End If Dim results = s_memberNameBuilderPool.Allocate() Dim anyMemberHasAttributes As Boolean = False For Each member In enumBlockSyntax.Members ' skip empty statements that represent invalid syntax in the Enum: If member.Kind = SyntaxKind.EnumMemberDeclaration Then Dim enumMember = DirectCast(member, EnumMemberDeclarationSyntax) results.Add(enumMember.Identifier.ValueText) If Not anyMemberHasAttributes AndAlso enumMember.AttributeLists.Any Then anyMemberHasAttributes = True End If End If Next If (anyMemberHasAttributes) Then declFlags = declFlags Or SingleTypeDeclaration.TypeDeclarationFlags.AnyMemberHasAttributes End If Return ToImmutableAndFree(results) End Function Private Sub AddMemberNames(methodDecl As MethodBaseSyntax, results As ImmutableHashSet(Of String).Builder) Dim name = SourceMethodSymbol.GetMemberNameFromSyntax(methodDecl) results.Add(name) End Sub Public Overrides Function VisitDelegateStatement(node As DelegateStatementSyntax) As SingleNamespaceOrTypeDeclaration Dim declFlags As SingleTypeDeclaration.TypeDeclarationFlags = If(node.AttributeLists.Any(), SingleTypeDeclaration.TypeDeclarationFlags.HasAnyAttributes, SingleTypeDeclaration.TypeDeclarationFlags.None) declFlags = declFlags Or SingleTypeDeclaration.TypeDeclarationFlags.HasAnyNontypeMembers Return New SingleTypeDeclaration( kind:=DeclarationKind.Delegate, name:=node.Identifier.ValueText, arity:=GetArity(node.TypeParameterList), modifiers:=GetModifiers(node.Modifiers), declFlags:=declFlags, syntaxReference:=_syntaxTree.GetReference(node), nameLocation:=_syntaxTree.GetLocation(node.Identifier.Span), memberNames:=ImmutableHashSet(Of String).Empty, children:=ImmutableArray(Of SingleTypeDeclaration).Empty) End Function Public Overrides Function VisitEventStatement(node As EventStatementSyntax) As SingleNamespaceOrTypeDeclaration If node.AsClause IsNot Nothing OrElse node.ImplementsClause IsNot Nothing Then ' this event will not need a type Return Nothing End If Dim declFlags As SingleTypeDeclaration.TypeDeclarationFlags = If(node.AttributeLists.Any(), SingleTypeDeclaration.TypeDeclarationFlags.HasAnyAttributes, SingleTypeDeclaration.TypeDeclarationFlags.None) declFlags = declFlags Or SingleTypeDeclaration.TypeDeclarationFlags.HasAnyNontypeMembers Return New SingleTypeDeclaration( kind:=DeclarationKind.EventSyntheticDelegate, name:=node.Identifier.ValueText, arity:=0, modifiers:=GetModifiers(node.Modifiers), declFlags:=declFlags, syntaxReference:=_syntaxTree.GetReference(node), nameLocation:=_syntaxTree.GetLocation(node.Identifier.Span), memberNames:=ImmutableHashSet(Of String).Empty, children:=ImmutableArray(Of SingleTypeDeclaration).Empty) End Function ' Public because BinderCache uses it also. Public Shared Function GetKind(kind As SyntaxKind) As DeclarationKind Select Case kind Case SyntaxKind.ClassStatement : Return DeclarationKind.Class Case SyntaxKind.InterfaceStatement : Return DeclarationKind.Interface Case SyntaxKind.StructureStatement : Return DeclarationKind.Structure Case SyntaxKind.NamespaceStatement : Return DeclarationKind.Namespace Case SyntaxKind.ModuleStatement : Return DeclarationKind.Module Case SyntaxKind.EnumStatement : Return DeclarationKind.Enum Case SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement : Return DeclarationKind.Delegate Case Else Throw ExceptionUtilities.UnexpectedValue(kind) End Select End Function ' Public because BinderCache uses it also. Public Shared Function GetArity(typeParamsSyntax As TypeParameterListSyntax) As Integer If typeParamsSyntax Is Nothing Then Return 0 Else Return typeParamsSyntax.Parameters.Count End If End Function Private Shared Function GetModifiers(modifiers As SyntaxTokenList) As DeclarationModifiers Dim result As DeclarationModifiers = DeclarationModifiers.None For Each modifier In modifiers Dim bit As DeclarationModifiers = 0 Select Case modifier.Kind Case SyntaxKind.MustInheritKeyword : bit = DeclarationModifiers.MustInherit Case SyntaxKind.NotInheritableKeyword : bit = DeclarationModifiers.NotInheritable Case SyntaxKind.PartialKeyword : bit = DeclarationModifiers.Partial Case SyntaxKind.ShadowsKeyword : bit = DeclarationModifiers.Shadows Case SyntaxKind.PublicKeyword : bit = DeclarationModifiers.Public Case SyntaxKind.ProtectedKeyword : bit = DeclarationModifiers.Protected Case SyntaxKind.FriendKeyword : bit = DeclarationModifiers.Friend Case SyntaxKind.PrivateKeyword : bit = DeclarationModifiers.Private Case SyntaxKind.ShadowsKeyword : bit = DeclarationModifiers.Shadows Case SyntaxKind.MustInheritKeyword : bit = DeclarationModifiers.MustInherit Case SyntaxKind.NotInheritableKeyword : bit = DeclarationModifiers.NotInheritable Case SyntaxKind.PartialKeyword : bit = DeclarationModifiers.Partial Case SyntaxKind.SharedKeyword : bit = DeclarationModifiers.Shared Case SyntaxKind.ReadOnlyKeyword : bit = DeclarationModifiers.ReadOnly Case SyntaxKind.WriteOnlyKeyword : bit = DeclarationModifiers.WriteOnly Case SyntaxKind.OverridesKeyword : bit = DeclarationModifiers.Overrides Case SyntaxKind.OverridableKeyword : bit = DeclarationModifiers.Overridable Case SyntaxKind.MustOverrideKeyword : bit = DeclarationModifiers.MustOverride Case SyntaxKind.NotOverridableKeyword : bit = DeclarationModifiers.NotOverridable Case SyntaxKind.OverloadsKeyword : bit = DeclarationModifiers.Overloads Case SyntaxKind.WithEventsKeyword : bit = DeclarationModifiers.WithEvents Case SyntaxKind.DimKeyword : bit = DeclarationModifiers.Dim Case SyntaxKind.ConstKeyword : bit = DeclarationModifiers.Const Case SyntaxKind.DefaultKeyword : bit = DeclarationModifiers.Default Case SyntaxKind.StaticKeyword : bit = DeclarationModifiers.Static Case SyntaxKind.WideningKeyword : bit = DeclarationModifiers.Widening Case SyntaxKind.NarrowingKeyword : bit = DeclarationModifiers.Narrowing Case SyntaxKind.AsyncKeyword : bit = DeclarationModifiers.Async Case SyntaxKind.IteratorKeyword : bit = DeclarationModifiers.Iterator Case Else ' It is possible to run into other tokens here, but only in error conditions. ' We are going to ignore them here. If Not modifier.GetDiagnostics().Any(Function(d) d.Severity = DiagnosticSeverity.Error) Then Throw ExceptionUtilities.UnexpectedValue(modifier.Kind) End If End Select result = result Or bit Next Return result End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Friend NotInheritable Class DeclarationTreeBuilder Inherits VisualBasicSyntaxVisitor(Of SingleNamespaceOrTypeDeclaration) ' The root namespace, expressing as an array of strings, one for each component. Private ReadOnly _rootNamespace As ImmutableArray(Of String) Private ReadOnly _scriptClassName As String Private ReadOnly _isSubmission As Boolean Private ReadOnly _syntaxTree As SyntaxTree Public Shared Function ForTree(tree As SyntaxTree, rootNamespace As ImmutableArray(Of String), scriptClassName As String, isSubmission As Boolean) As RootSingleNamespaceDeclaration Dim builder = New DeclarationTreeBuilder(tree, rootNamespace, scriptClassName, isSubmission) Dim decl = DirectCast(builder.ForDeclaration(tree.GetRoot()), RootSingleNamespaceDeclaration) Return decl End Function Private Sub New(syntaxTree As SyntaxTree, rootNamespace As ImmutableArray(Of String), scriptClassName As String, isSubmission As Boolean) _syntaxTree = syntaxTree _rootNamespace = rootNamespace _scriptClassName = scriptClassName _isSubmission = isSubmission End Sub Private Function ForDeclaration(node As SyntaxNode) As SingleNamespaceOrTypeDeclaration Return Visit(node) End Function Private Function VisitNamespaceChildren(node As VisualBasicSyntaxNode, members As SyntaxList(Of StatementSyntax)) As ImmutableArray(Of SingleNamespaceOrTypeDeclaration) Dim implicitClass As SingleNamespaceOrTypeDeclaration = Nothing Dim childrenBuilder = VisitNamespaceChildren(node, members, implicitClass) If implicitClass IsNot Nothing Then childrenBuilder.Add(implicitClass) End If Return childrenBuilder.ToImmutableAndFree() End Function Private Function VisitNamespaceChildren(node As VisualBasicSyntaxNode, members As SyntaxList(Of StatementSyntax), <Out()> ByRef implicitClass As SingleNamespaceOrTypeDeclaration) As ArrayBuilder(Of SingleNamespaceOrTypeDeclaration) Dim children = ArrayBuilder(Of SingleNamespaceOrTypeDeclaration).GetInstance() Dim implicitClassTypeChildren = ArrayBuilder(Of SingleTypeDeclaration).GetInstance() ' We look for any members that are not allowed in namespace. ' If there are any we create an implicit class to wrap them. Dim requiresImplicitClass = False For Each member In members Dim namespaceOrType As SingleNamespaceOrTypeDeclaration = Visit(member) If namespaceOrType IsNot Nothing Then If namespaceOrType.Kind = DeclarationKind.EventSyntheticDelegate Then ' broken code scenario. Event declared in namespace created a delegate declaration which should go into the ' implicit class implicitClassTypeChildren.Add(DirectCast(namespaceOrType, SingleTypeDeclaration)) requiresImplicitClass = True Else children.Add(namespaceOrType) End If ElseIf Not requiresImplicitClass Then requiresImplicitClass = member.Kind <> SyntaxKind.IncompleteMember AndAlso member.Kind <> SyntaxKind.EmptyStatement End If Next If requiresImplicitClass Then ' The implicit class is not static and has no extensions Dim declFlags As SingleTypeDeclaration.TypeDeclarationFlags = SingleTypeDeclaration.TypeDeclarationFlags.None Dim memberNames = GetNonTypeMemberNames(members, declFlags) implicitClass = CreateImplicitClass( node, memberNames, implicitClassTypeChildren.ToImmutable, declFlags) Else implicitClass = Nothing End If implicitClassTypeChildren.Free() Return children End Function Private Shared Function GetReferenceDirectives(compilationUnit As CompilationUnitSyntax) As ImmutableArray(Of ReferenceDirective) Dim directiveNodes = compilationUnit.GetReferenceDirectives( Function(d) Not d.File.ContainsDiagnostics AndAlso Not String.IsNullOrEmpty(d.File.ValueText)) If directiveNodes.Count = 0 Then Return ImmutableArray(Of ReferenceDirective).Empty End If Dim directives = ArrayBuilder(Of ReferenceDirective).GetInstance(directiveNodes.Count) For Each directiveNode In directiveNodes directives.Add(New ReferenceDirective(directiveNode.File.ValueText, New SourceLocation(directiveNode))) Next Return directives.ToImmutableAndFree() End Function Private Function CreateImplicitClass(parent As VisualBasicSyntaxNode, memberNames As ImmutableHashSet(Of String), children As ImmutableArray(Of SingleTypeDeclaration), declFlags As SingleTypeDeclaration.TypeDeclarationFlags) As SingleNamespaceOrTypeDeclaration Dim parentReference = _syntaxTree.GetReference(parent) Return New SingleTypeDeclaration( kind:=DeclarationKind.ImplicitClass, name:=TypeSymbol.ImplicitTypeName, arity:=0, modifiers:=DeclarationModifiers.Friend Or DeclarationModifiers.Partial Or DeclarationModifiers.NotInheritable, declFlags:=declFlags, syntaxReference:=parentReference, nameLocation:=parentReference.GetLocation(), memberNames:=memberNames, children:=children) End Function Private Function CreateScriptClass(parent As VisualBasicSyntaxNode, children As ImmutableArray(Of SingleTypeDeclaration), memberNames As ImmutableHashSet(Of String), declFlags As SingleTypeDeclaration.TypeDeclarationFlags) As SingleNamespaceOrTypeDeclaration Debug.Assert(parent.Kind = SyntaxKind.CompilationUnit AndAlso _syntaxTree.Options.Kind <> SourceCodeKind.Regular) ' script class is represented by the parent node: Dim parentReference = _syntaxTree.GetReference(parent) Dim fullName = _scriptClassName.Split("."c) ' Note: The symbol representing the merged declarations uses parentReference to enumerate non-type members. Dim decl As SingleNamespaceOrTypeDeclaration = New SingleTypeDeclaration( kind:=If(_isSubmission, DeclarationKind.Submission, DeclarationKind.Script), name:=fullName.Last(), arity:=0, modifiers:=DeclarationModifiers.Friend Or DeclarationModifiers.Partial Or DeclarationModifiers.NotInheritable, declFlags:=declFlags, syntaxReference:=parentReference, nameLocation:=parentReference.GetLocation(), memberNames:=memberNames, children:=children) For i = fullName.Length - 2 To 0 Step -1 decl = New SingleNamespaceDeclaration( name:=fullName(i), hasImports:=False, syntaxReference:=parentReference, nameLocation:=parentReference.GetLocation(), children:=ImmutableArray.Create(Of SingleNamespaceOrTypeDeclaration)(decl)) Next Return decl End Function Public Overrides Function VisitCompilationUnit(node As CompilationUnitSyntax) As SingleNamespaceOrTypeDeclaration Dim children As ImmutableArray(Of SingleNamespaceOrTypeDeclaration) Dim globalChildren As ImmutableArray(Of SingleNamespaceOrTypeDeclaration) = Nothing Dim nonGlobal As ImmutableArray(Of SingleNamespaceOrTypeDeclaration) = Nothing Dim syntaxRef = _syntaxTree.GetReference(node) Dim implicitClass As SingleNamespaceOrTypeDeclaration = Nothing Dim referenceDirectives As ImmutableArray(Of ReferenceDirective) If _syntaxTree.Options.Kind <> SourceCodeKind.Regular Then Dim childrenBuilder = ArrayBuilder(Of SingleNamespaceOrTypeDeclaration).GetInstance() Dim scriptChildren = ArrayBuilder(Of SingleTypeDeclaration).GetInstance() For Each member In node.Members Dim decl = Visit(member) If decl IsNot Nothing Then ' Although namespaces are not allowed in script code process them ' here as if they were to improve error reporting. If decl.Kind = DeclarationKind.Namespace Then childrenBuilder.Add(decl) Else scriptChildren.Add(DirectCast(decl, SingleTypeDeclaration)) End If End If Next 'Script class is not static and contains no extensions. Dim declFlags As SingleTypeDeclaration.TypeDeclarationFlags = SingleTypeDeclaration.TypeDeclarationFlags.None Dim memberNames = GetNonTypeMemberNames(node.Members, declFlags) implicitClass = CreateScriptClass(node, scriptChildren.ToImmutableAndFree(), memberNames, declFlags) children = childrenBuilder.ToImmutableAndFree() referenceDirectives = GetReferenceDirectives(node) Else children = VisitNamespaceChildren(node, node.Members, implicitClass).ToImmutableAndFree() referenceDirectives = ImmutableArray(Of ReferenceDirective).Empty End If ' Find children within NamespaceGlobal separately FindGlobalDeclarations(children, implicitClass, globalChildren, nonGlobal) If _rootNamespace.Length = 0 Then ' No project-level root namespace specified. Both global and nested children within the root. Return New RootSingleNamespaceDeclaration( hasImports:=True, treeNode:=_syntaxTree.GetReference(node), children:=globalChildren.Concat(nonGlobal), referenceDirectives:=referenceDirectives, hasAssemblyAttributes:=node.Attributes.Any) Else ' Project-level root namespace. All children without explicit global are children ' of the project-level root namespace. The root declaration has the project level namespace ' and global children within it. ' Note that we need to built the project level namespace even if it has no children [Bug 4879[ Dim projectNs = BuildRootNamespace(node, nonGlobal) globalChildren = globalChildren.Add(projectNs) Dim newChildren = globalChildren.OfType(Of SingleNamespaceOrTypeDeclaration).AsImmutable() Return New RootSingleNamespaceDeclaration( hasImports:=True, treeNode:=_syntaxTree.GetReference(node), children:=newChildren, referenceDirectives:=referenceDirectives, hasAssemblyAttributes:=node.Attributes.Any) End If End Function ' Given a set of single declarations, get the sets of global and non-global declarations. ' A regular declaration is put into "non-global declarations". ' A "Namespace Global" is not put in either place, but all its direct children are put into "global declarations". Private Sub FindGlobalDeclarations(declarations As ImmutableArray(Of SingleNamespaceOrTypeDeclaration), implicitClass As SingleNamespaceOrTypeDeclaration, ByRef globalDeclarations As ImmutableArray(Of SingleNamespaceOrTypeDeclaration), ByRef nonGlobal As ImmutableArray(Of SingleNamespaceOrTypeDeclaration)) Dim globalBuilder = ArrayBuilder(Of SingleNamespaceOrTypeDeclaration).GetInstance() Dim nonGlobalBuilder = ArrayBuilder(Of SingleNamespaceOrTypeDeclaration).GetInstance() If implicitClass IsNot Nothing Then nonGlobalBuilder.Add(implicitClass) End If For Each decl In declarations Dim nsDecl As SingleNamespaceDeclaration = TryCast(decl, SingleNamespaceDeclaration) If nsDecl IsNot Nothing AndAlso nsDecl.IsGlobalNamespace Then ' Namespace Global. globalBuilder.AddRange(nsDecl.Children) Else ' regular declaration nonGlobalBuilder.Add(decl) End If Next globalDeclarations = globalBuilder.ToImmutableAndFree() nonGlobal = nonGlobalBuilder.ToImmutableAndFree() End Sub Private Function UnescapeIdentifier(identifier As String) As String If identifier(0) = "[" Then Debug.Assert(identifier(identifier.Length - 1) = "]") Return identifier.Substring(1, identifier.Length - 2) Else Return identifier End If End Function ' Build the declaration for the root (project-level) namespace. Private Function BuildRootNamespace(node As CompilationUnitSyntax, children As ImmutableArray(Of SingleNamespaceOrTypeDeclaration)) As SingleNamespaceDeclaration Debug.Assert(_rootNamespace.Length > 0) Dim ns As SingleNamespaceDeclaration = Nothing ' The compilation node will count as a location for the innermost project level ' namespace. i.e. if the project level namespace is "Goo.Bar", then each compilation unit ' is a location for "Goo.Bar". "Goo" still has no syntax location though. ' ' By doing this we ensure that top level type and namespace declarations will have ' symbols whose parent namespace symbol points to the parent container CompilationUnit. ' This ensures parity with the case where their is no 'project-level' namespace and the ' global namespaces point to the compilation unit syntax. Dim syntaxReference = _syntaxTree.GetReference(node) Dim nameLocation = syntaxReference.GetLocation() ' traverse components from right to left For i = _rootNamespace.Length - 1 To 0 Step -1 ' treat all root namespace parts as implicitly escaped. ' a root namespace with a name "global" will actually create "Global.[global]" ns = New SingleNamespaceDeclaration( name:=UnescapeIdentifier(_rootNamespace(i)), hasImports:=True, syntaxReference:=syntaxReference, nameLocation:=nameLocation, children:=children, isPartOfRootNamespace:=True) ' Only the innermost namespace will point at compilation unit. All other outer ' namespaces will have no location. syntaxReference = Nothing nameLocation = Nothing ' This namespace is the child of the namespace to the left. children = ImmutableArray.Create(Of SingleNamespaceOrTypeDeclaration)(ns) Next Return ns End Function Public Overrides Function VisitNamespaceBlock(nsBlockSyntax As NamespaceBlockSyntax) As SingleNamespaceOrTypeDeclaration Dim nsDeclSyntax As NamespaceStatementSyntax = nsBlockSyntax.NamespaceStatement Dim children = VisitNamespaceChildren(nsBlockSyntax, nsBlockSyntax.Members) Dim name As NameSyntax = nsDeclSyntax.Name While TypeOf name Is QualifiedNameSyntax Dim dotted = DirectCast(name, QualifiedNameSyntax) Dim ns = New SingleNamespaceDeclaration( name:=dotted.Right.Identifier.ValueText, hasImports:=True, syntaxReference:=_syntaxTree.GetReference(dotted), nameLocation:=_syntaxTree.GetLocation(dotted.Right.Span), children:=children) children = {ns}.OfType(Of SingleNamespaceOrTypeDeclaration).AsImmutable() name = dotted.Left End While ' This is either the global namespace, or a regular namespace. Represent the global namespace ' with the empty string. If name.Kind = SyntaxKind.GlobalName Then If nsBlockSyntax.Parent.Kind = SyntaxKind.CompilationUnit Then ' Namespace Global only allowed as direct child of compilation. Return New GlobalNamespaceDeclaration( hasImports:=True, syntaxReference:=_syntaxTree.GetReference(name), nameLocation:=_syntaxTree.GetLocation(name.Span), children:=children) Else ' Error for this will be diagnosed later. Create a namespace named "Global" for error recovery. (see corresponding code in BinderFactory) Return New SingleNamespaceDeclaration( name:="Global", hasImports:=True, syntaxReference:=_syntaxTree.GetReference(name), nameLocation:=_syntaxTree.GetLocation(name.Span), children:=children) End If Else Return New SingleNamespaceDeclaration( name:=DirectCast(name, IdentifierNameSyntax).Identifier.ValueText, hasImports:=True, syntaxReference:=_syntaxTree.GetReference(name), nameLocation:=_syntaxTree.GetLocation(name.Span), children:=children) End If End Function Private Structure TypeBlockInfo Public ReadOnly TypeBlockSyntax As TypeBlockSyntax Public ReadOnly TypeDeclaration As SingleTypeDeclaration Public ReadOnly NestedTypes As ArrayBuilder(Of Integer) Public Sub New(typeBlockSyntax As TypeBlockSyntax) MyClass.New(typeBlockSyntax, Nothing, Nothing) End Sub Private Sub New(typeBlockSyntax As TypeBlockSyntax, declaration As SingleTypeDeclaration, nestedTypes As ArrayBuilder(Of Integer)) Me.TypeBlockSyntax = typeBlockSyntax Me.TypeDeclaration = declaration Me.NestedTypes = nestedTypes End Sub Public Function WithNestedTypes(nested As ArrayBuilder(Of Integer)) As TypeBlockInfo Debug.Assert(Me.TypeDeclaration Is Nothing) Debug.Assert(Me.NestedTypes Is Nothing) Debug.Assert(nested IsNot Nothing) Return New TypeBlockInfo(Me.TypeBlockSyntax, Nothing, nested) End Function Public Function WithDeclaration(declaration As SingleTypeDeclaration) As TypeBlockInfo Debug.Assert(Me.TypeDeclaration Is Nothing) Debug.Assert(declaration IsNot Nothing) Return New TypeBlockInfo(Me.TypeBlockSyntax, declaration, Me.NestedTypes) End Function End Structure Private Function VisitTypeBlockNew(topTypeBlockSyntax As TypeBlockSyntax) As SingleNamespaceOrTypeDeclaration Dim typeStack = ArrayBuilder(Of TypeBlockInfo).GetInstance typeStack.Add(New TypeBlockInfo(topTypeBlockSyntax)) ' Fill the chain with types Dim index As Integer = 0 While index < typeStack.Count Dim typeEntry As TypeBlockInfo = typeStack(index) Dim members As SyntaxList(Of StatementSyntax) = typeEntry.TypeBlockSyntax.Members If members.Count > 0 Then Dim nestedTypeIndices As ArrayBuilder(Of Integer) = Nothing For Each member In members Select Case member.Kind Case SyntaxKind.ModuleBlock, SyntaxKind.ClassBlock, SyntaxKind.StructureBlock, SyntaxKind.InterfaceBlock If nestedTypeIndices Is Nothing Then nestedTypeIndices = ArrayBuilder(Of Integer).GetInstance() End If nestedTypeIndices.Add(typeStack.Count) typeStack.Add(New TypeBlockInfo(DirectCast(member, TypeBlockSyntax))) End Select Next If nestedTypeIndices IsNot Nothing Then typeStack(index) = typeEntry.WithNestedTypes(nestedTypeIndices) End If End If index += 1 End While ' Process types Debug.Assert(index = typeStack.Count) Dim childrenBuilder = ArrayBuilder(Of SingleTypeDeclaration).GetInstance() While index > 0 index -= 1 Dim typeEntry As TypeBlockInfo = typeStack(index) Dim children = ImmutableArray(Of SingleTypeDeclaration).Empty Dim members As SyntaxList(Of StatementSyntax) = typeEntry.TypeBlockSyntax.Members If members.Count > 0 Then childrenBuilder.Clear() For Each member In members Select Case member.Kind Case SyntaxKind.ModuleBlock, SyntaxKind.ClassBlock, SyntaxKind.StructureBlock, SyntaxKind.InterfaceBlock ' should be processed already Case Else Dim typeDecl = TryCast(Visit(member), SingleTypeDeclaration) If typeDecl IsNot Nothing Then childrenBuilder.Add(typeDecl) End If End Select Next Dim nestedTypes As ArrayBuilder(Of Integer) = typeEntry.NestedTypes If nestedTypes IsNot Nothing Then For i = 0 To nestedTypes.Count - 1 childrenBuilder.Add(typeStack(nestedTypes(i)).TypeDeclaration) Next nestedTypes.Free() End If children = childrenBuilder.ToImmutable() End If Dim typeBlockSyntax As TypeBlockSyntax = typeEntry.TypeBlockSyntax Dim declarationSyntax As TypeStatementSyntax = typeBlockSyntax.BlockStatement ' Get the arity for things that can have arity. Dim typeArity As Integer = 0 Select Case typeBlockSyntax.Kind Case SyntaxKind.ClassBlock, SyntaxKind.StructureBlock, SyntaxKind.InterfaceBlock typeArity = GetArity(declarationSyntax.TypeParameterList) End Select Dim declFlags As SingleTypeDeclaration.TypeDeclarationFlags = If(declarationSyntax.AttributeLists.Any(), SingleTypeDeclaration.TypeDeclarationFlags.HasAnyAttributes, SingleTypeDeclaration.TypeDeclarationFlags.None) If (typeBlockSyntax.Inherits.Any) Then declFlags = declFlags Or SingleTypeDeclaration.TypeDeclarationFlags.HasBaseDeclarations End If Dim memberNames = GetNonTypeMemberNames(typeBlockSyntax.Members, declFlags) typeStack(index) = typeEntry.WithDeclaration( New SingleTypeDeclaration( kind:=GetKind(declarationSyntax.Kind), name:=declarationSyntax.Identifier.ValueText, arity:=typeArity, modifiers:=GetModifiers(declarationSyntax.Modifiers), declFlags:=declFlags, syntaxReference:=_syntaxTree.GetReference(typeBlockSyntax), nameLocation:=_syntaxTree.GetLocation(typeBlockSyntax.BlockStatement.Identifier.Span), memberNames:=memberNames, children:=children)) End While childrenBuilder.Free() Dim result As SingleNamespaceOrTypeDeclaration = typeStack(0).TypeDeclaration typeStack.Free() Return result End Function Public Overrides Function VisitModuleBlock(ByVal moduleBlockSyntax As ModuleBlockSyntax) As SingleNamespaceOrTypeDeclaration Return VisitTypeBlockNew(moduleBlockSyntax) End Function Public Overrides Function VisitClassBlock(ByVal classBlockSyntax As ClassBlockSyntax) As SingleNamespaceOrTypeDeclaration Return VisitTypeBlockNew(classBlockSyntax) End Function Public Overrides Function VisitStructureBlock(ByVal structureBlockSyntax As StructureBlockSyntax) As SingleNamespaceOrTypeDeclaration Return VisitTypeBlockNew(structureBlockSyntax) End Function Public Overrides Function VisitInterfaceBlock(ByVal interfaceBlockSyntax As InterfaceBlockSyntax) As SingleNamespaceOrTypeDeclaration Return VisitTypeBlockNew(interfaceBlockSyntax) End Function Public Overrides Function VisitEnumBlock(enumBlockSyntax As EnumBlockSyntax) As SingleNamespaceOrTypeDeclaration Dim declarationSyntax As EnumStatementSyntax = enumBlockSyntax.EnumStatement Dim declFlags As SingleTypeDeclaration.TypeDeclarationFlags = If(declarationSyntax.AttributeLists.Any(), SingleTypeDeclaration.TypeDeclarationFlags.HasAnyAttributes, SingleTypeDeclaration.TypeDeclarationFlags.None) If (declarationSyntax.UnderlyingType IsNot Nothing) Then declFlags = declFlags Or SingleTypeDeclaration.TypeDeclarationFlags.HasBaseDeclarations End If Dim memberNames = GetMemberNames(enumBlockSyntax, declFlags) Return New SingleTypeDeclaration( kind:=GetKind(declarationSyntax.Kind), name:=declarationSyntax.Identifier.ValueText, arity:=0, modifiers:=GetModifiers(declarationSyntax.Modifiers), declFlags:=declFlags, syntaxReference:=_syntaxTree.GetReference(enumBlockSyntax), nameLocation:=_syntaxTree.GetLocation(enumBlockSyntax.EnumStatement.Identifier.Span), memberNames:=memberNames, children:=VisitTypeChildren(enumBlockSyntax.Members)) End Function Private Function VisitTypeChildren(members As SyntaxList(Of StatementSyntax)) As ImmutableArray(Of SingleTypeDeclaration) If members.Count = 0 Then Return ImmutableArray(Of SingleTypeDeclaration).Empty End If Dim children = ArrayBuilder(Of SingleTypeDeclaration).GetInstance() For Each member In members Dim typeDecl = TryCast(Visit(member), SingleTypeDeclaration) If typeDecl IsNot Nothing Then children.Add(typeDecl) End If Next Return children.ToImmutableAndFree() End Function ''' <summary> ''' Pool of builders used to create our member name sets. Importantly, these use ''' <see cref="CaseInsensitiveComparison.Comparer"/> so that name lookup happens in an ''' appropriate manner for VB identifiers. This allows fast member name O(log(n)) even if ''' the casing doesn't match. ''' </summary> Private Shared ReadOnly s_memberNameBuilderPool As New ObjectPool(Of ImmutableHashSet(Of String).Builder)( Function() ImmutableHashSet.CreateBuilder(IdentifierComparison.Comparer)) Private Shared Function ToImmutableAndFree(builder As ImmutableHashSet(Of String).Builder) As ImmutableHashSet(Of String) Dim result = builder.ToImmutable() builder.Clear() s_memberNameBuilderPool.Free(builder) Return result End Function Private Function GetNonTypeMemberNames(members As SyntaxList(Of StatementSyntax), ByRef declFlags As SingleTypeDeclaration.TypeDeclarationFlags) As ImmutableHashSet(Of String) Dim anyMethodHadExtensionSyntax = False Dim anyMemberHasAttributes = False Dim anyNonTypeMembers = False Dim results = s_memberNameBuilderPool.Allocate() For Each statement In members Select Case statement.Kind Case SyntaxKind.FieldDeclaration anyNonTypeMembers = True Dim field = DirectCast(statement, FieldDeclarationSyntax) If field.AttributeLists.Any Then anyMemberHasAttributes = True End If For Each decl In field.Declarators For Each name In decl.Names results.Add(name.Identifier.ValueText) Next Next Case SyntaxKind.SubBlock, SyntaxKind.FunctionBlock, SyntaxKind.ConstructorBlock, SyntaxKind.OperatorBlock anyNonTypeMembers = True Dim methodDecl = DirectCast(statement, MethodBlockBaseSyntax).BlockStatement If methodDecl.AttributeLists.Any Then anyMemberHasAttributes = True End If AddMemberNames(methodDecl, results) Case SyntaxKind.PropertyBlock anyNonTypeMembers = True Dim propertyDecl = DirectCast(statement, PropertyBlockSyntax) If propertyDecl.PropertyStatement.AttributeLists.Any Then anyMemberHasAttributes = True Else For Each a In propertyDecl.Accessors If a.BlockStatement.AttributeLists.Any Then anyMemberHasAttributes = True End If Next End If AddMemberNames(propertyDecl.PropertyStatement, results) Case SyntaxKind.SubStatement, SyntaxKind.FunctionStatement, SyntaxKind.SubNewStatement, SyntaxKind.DeclareSubStatement, SyntaxKind.DeclareFunctionStatement, SyntaxKind.OperatorStatement, SyntaxKind.PropertyStatement anyNonTypeMembers = True Dim methodDecl = DirectCast(statement, MethodBaseSyntax) If methodDecl.AttributeLists.Any Then anyMemberHasAttributes = True End If AddMemberNames(methodDecl, results) Case SyntaxKind.EventBlock anyNonTypeMembers = True Dim eventDecl = DirectCast(statement, EventBlockSyntax) If eventDecl.EventStatement.AttributeLists.Any Then anyMemberHasAttributes = True Else For Each a In eventDecl.Accessors If a.BlockStatement.AttributeLists.Any Then anyMemberHasAttributes = True End If Next End If Dim name = eventDecl.EventStatement.Identifier.ValueText results.Add(name) Case SyntaxKind.EventStatement anyNonTypeMembers = True Dim eventDecl = DirectCast(statement, EventStatementSyntax) If eventDecl.AttributeLists.Any Then anyMemberHasAttributes = True End If Dim name = eventDecl.Identifier.ValueText results.Add(name) End Select Next If (anyMemberHasAttributes) Then declFlags = declFlags Or SingleTypeDeclaration.TypeDeclarationFlags.AnyMemberHasAttributes End If If (anyNonTypeMembers) Then declFlags = declFlags Or SingleTypeDeclaration.TypeDeclarationFlags.HasAnyNontypeMembers End If Return ToImmutableAndFree(results) End Function Private Function GetMemberNames(enumBlockSyntax As EnumBlockSyntax, ByRef declFlags As SingleTypeDeclaration.TypeDeclarationFlags) As ImmutableHashSet(Of String) Dim members = enumBlockSyntax.Members If (members.Count <> 0) Then declFlags = declFlags Or SingleTypeDeclaration.TypeDeclarationFlags.HasAnyNontypeMembers End If Dim results = s_memberNameBuilderPool.Allocate() Dim anyMemberHasAttributes As Boolean = False For Each member In enumBlockSyntax.Members ' skip empty statements that represent invalid syntax in the Enum: If member.Kind = SyntaxKind.EnumMemberDeclaration Then Dim enumMember = DirectCast(member, EnumMemberDeclarationSyntax) results.Add(enumMember.Identifier.ValueText) If Not anyMemberHasAttributes AndAlso enumMember.AttributeLists.Any Then anyMemberHasAttributes = True End If End If Next If (anyMemberHasAttributes) Then declFlags = declFlags Or SingleTypeDeclaration.TypeDeclarationFlags.AnyMemberHasAttributes End If Return ToImmutableAndFree(results) End Function Private Sub AddMemberNames(methodDecl As MethodBaseSyntax, results As ImmutableHashSet(Of String).Builder) Dim name = SourceMethodSymbol.GetMemberNameFromSyntax(methodDecl) results.Add(name) End Sub Public Overrides Function VisitDelegateStatement(node As DelegateStatementSyntax) As SingleNamespaceOrTypeDeclaration Dim declFlags As SingleTypeDeclaration.TypeDeclarationFlags = If(node.AttributeLists.Any(), SingleTypeDeclaration.TypeDeclarationFlags.HasAnyAttributes, SingleTypeDeclaration.TypeDeclarationFlags.None) declFlags = declFlags Or SingleTypeDeclaration.TypeDeclarationFlags.HasAnyNontypeMembers Return New SingleTypeDeclaration( kind:=DeclarationKind.Delegate, name:=node.Identifier.ValueText, arity:=GetArity(node.TypeParameterList), modifiers:=GetModifiers(node.Modifiers), declFlags:=declFlags, syntaxReference:=_syntaxTree.GetReference(node), nameLocation:=_syntaxTree.GetLocation(node.Identifier.Span), memberNames:=ImmutableHashSet(Of String).Empty, children:=ImmutableArray(Of SingleTypeDeclaration).Empty) End Function Public Overrides Function VisitEventStatement(node As EventStatementSyntax) As SingleNamespaceOrTypeDeclaration If node.AsClause IsNot Nothing OrElse node.ImplementsClause IsNot Nothing Then ' this event will not need a type Return Nothing End If Dim declFlags As SingleTypeDeclaration.TypeDeclarationFlags = If(node.AttributeLists.Any(), SingleTypeDeclaration.TypeDeclarationFlags.HasAnyAttributes, SingleTypeDeclaration.TypeDeclarationFlags.None) declFlags = declFlags Or SingleTypeDeclaration.TypeDeclarationFlags.HasAnyNontypeMembers Return New SingleTypeDeclaration( kind:=DeclarationKind.EventSyntheticDelegate, name:=node.Identifier.ValueText, arity:=0, modifiers:=GetModifiers(node.Modifiers), declFlags:=declFlags, syntaxReference:=_syntaxTree.GetReference(node), nameLocation:=_syntaxTree.GetLocation(node.Identifier.Span), memberNames:=ImmutableHashSet(Of String).Empty, children:=ImmutableArray(Of SingleTypeDeclaration).Empty) End Function ' Public because BinderCache uses it also. Public Shared Function GetKind(kind As SyntaxKind) As DeclarationKind Select Case kind Case SyntaxKind.ClassStatement : Return DeclarationKind.Class Case SyntaxKind.InterfaceStatement : Return DeclarationKind.Interface Case SyntaxKind.StructureStatement : Return DeclarationKind.Structure Case SyntaxKind.NamespaceStatement : Return DeclarationKind.Namespace Case SyntaxKind.ModuleStatement : Return DeclarationKind.Module Case SyntaxKind.EnumStatement : Return DeclarationKind.Enum Case SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement : Return DeclarationKind.Delegate Case Else Throw ExceptionUtilities.UnexpectedValue(kind) End Select End Function ' Public because BinderCache uses it also. Public Shared Function GetArity(typeParamsSyntax As TypeParameterListSyntax) As Integer If typeParamsSyntax Is Nothing Then Return 0 Else Return typeParamsSyntax.Parameters.Count End If End Function Private Shared Function GetModifiers(modifiers As SyntaxTokenList) As DeclarationModifiers Dim result As DeclarationModifiers = DeclarationModifiers.None For Each modifier In modifiers Dim bit As DeclarationModifiers = 0 Select Case modifier.Kind Case SyntaxKind.MustInheritKeyword : bit = DeclarationModifiers.MustInherit Case SyntaxKind.NotInheritableKeyword : bit = DeclarationModifiers.NotInheritable Case SyntaxKind.PartialKeyword : bit = DeclarationModifiers.Partial Case SyntaxKind.ShadowsKeyword : bit = DeclarationModifiers.Shadows Case SyntaxKind.PublicKeyword : bit = DeclarationModifiers.Public Case SyntaxKind.ProtectedKeyword : bit = DeclarationModifiers.Protected Case SyntaxKind.FriendKeyword : bit = DeclarationModifiers.Friend Case SyntaxKind.PrivateKeyword : bit = DeclarationModifiers.Private Case SyntaxKind.ShadowsKeyword : bit = DeclarationModifiers.Shadows Case SyntaxKind.MustInheritKeyword : bit = DeclarationModifiers.MustInherit Case SyntaxKind.NotInheritableKeyword : bit = DeclarationModifiers.NotInheritable Case SyntaxKind.PartialKeyword : bit = DeclarationModifiers.Partial Case SyntaxKind.SharedKeyword : bit = DeclarationModifiers.Shared Case SyntaxKind.ReadOnlyKeyword : bit = DeclarationModifiers.ReadOnly Case SyntaxKind.WriteOnlyKeyword : bit = DeclarationModifiers.WriteOnly Case SyntaxKind.OverridesKeyword : bit = DeclarationModifiers.Overrides Case SyntaxKind.OverridableKeyword : bit = DeclarationModifiers.Overridable Case SyntaxKind.MustOverrideKeyword : bit = DeclarationModifiers.MustOverride Case SyntaxKind.NotOverridableKeyword : bit = DeclarationModifiers.NotOverridable Case SyntaxKind.OverloadsKeyword : bit = DeclarationModifiers.Overloads Case SyntaxKind.WithEventsKeyword : bit = DeclarationModifiers.WithEvents Case SyntaxKind.DimKeyword : bit = DeclarationModifiers.Dim Case SyntaxKind.ConstKeyword : bit = DeclarationModifiers.Const Case SyntaxKind.DefaultKeyword : bit = DeclarationModifiers.Default Case SyntaxKind.StaticKeyword : bit = DeclarationModifiers.Static Case SyntaxKind.WideningKeyword : bit = DeclarationModifiers.Widening Case SyntaxKind.NarrowingKeyword : bit = DeclarationModifiers.Narrowing Case SyntaxKind.AsyncKeyword : bit = DeclarationModifiers.Async Case SyntaxKind.IteratorKeyword : bit = DeclarationModifiers.Iterator Case Else ' It is possible to run into other tokens here, but only in error conditions. ' We are going to ignore them here. If Not modifier.GetDiagnostics().Any(Function(d) d.Severity = DiagnosticSeverity.Error) Then Throw ExceptionUtilities.UnexpectedValue(modifier.Kind) End If End Select result = result Or bit Next Return result End Function End Class End Namespace
-1
dotnet/roslyn
56,011
React to string comparison changing on .NET Core
The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
jaredpar
"2021-08-30T17:18:52Z"
"2021-08-30T20:20:04Z"
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
4d99cda6e446e77dbb302e26388c1093bd3ef569
React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This impacted a number of our tests which weren't explicitly using ordinal to compare strings. The fix here makes our tests run consistently across the various versions of .NET Core and .NET Framework https://github.com/dotnet/runtime/issues/43956
./src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/MockSymbolTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Text Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class TestSymbols ' Create a trivial compilation with no source or references. Private Function TrivialCompilation() As VisualBasicCompilation Return VisualBasicCompilation.Create("Test") End Function <Fact> Public Sub TestArrayType() Dim compilation As VisualBasicCompilation = TrivialCompilation() Dim elementType As NamedTypeSymbol = New MockNamedTypeSymbol("TestClass", Enumerable.Empty(Of Symbol)) ' this can be any type. Dim ats1 As ArrayTypeSymbol = ArrayTypeSymbol.CreateVBArray(elementType, Nothing, 1, compilation) Assert.Equal(1, ats1.Rank) Assert.Same(elementType, ats1.ElementType) Assert.Equal(SymbolKind.ArrayType, ats1.Kind) Assert.True(ats1.IsReferenceType) Assert.False(ats1.IsValueType) Assert.Equal("TestClass()", ats1.ToString()) Dim ats2 As ArrayTypeSymbol = ArrayTypeSymbol.CreateVBArray(elementType, Nothing, 2, compilation) Assert.Equal(2, ats2.Rank) Assert.Same(elementType, ats2.ElementType) Assert.Equal(SymbolKind.ArrayType, ats2.Kind) Assert.True(ats2.IsReferenceType) Assert.False(ats2.IsValueType) Assert.Equal("TestClass(*,*)", ats2.ToString()) Dim ats3 As ArrayTypeSymbol = ArrayTypeSymbol.CreateVBArray(elementType, Nothing, 3, compilation) Assert.Equal(3, ats3.Rank) Assert.Equal("TestClass(*,*,*)", ats3.ToString()) End Sub <Fact> Public Sub TestMissingMetadataSymbol() Dim missingAssemblyName = New AssemblyIdentity("goo") Dim assem As AssemblySymbol = New MockAssemblySymbol("banana") Dim [module] = New MissingModuleSymbol(assem, -1) Dim container As NamedTypeSymbol = New MockNamedTypeSymbol("TestClass", Enumerable.Empty(Of Symbol), TypeKind.Class) Dim mms1 = New MissingMetadataTypeSymbol.TopLevel(New MissingAssemblySymbol(missingAssemblyName).Modules(0), "Elvis", "Lives", 2, True) Assert.Equal(2, mms1.Arity) Assert.Equal("Elvis", mms1.NamespaceName) Assert.Equal("Lives", mms1.Name) Assert.Equal("Elvis.Lives(Of ,)[missing]", mms1.ToTestDisplayString()) Assert.Equal("goo", mms1.ContainingAssembly.Identity.Name) Dim mms2 = New MissingMetadataTypeSymbol.TopLevel([module], "Elvis.Is", "Cool", 0, True) Assert.Equal(0, mms2.Arity) Assert.Equal("Elvis.Is", mms2.NamespaceName) Assert.Equal("Cool", mms2.Name) Assert.Equal("Elvis.Is.Cool[missing]", mms2.ToTestDisplayString()) Assert.Same(assem, mms2.ContainingAssembly) ' TODO: Add test for 3rd constructor. End Sub <Fact> Public Sub TestNamespaceExtent() Dim assem1 As AssemblySymbol = New MockAssemblySymbol("goo") Dim ne1 As NamespaceExtent = New NamespaceExtent(assem1) Assert.Equal(ne1.Kind, NamespaceKind.Assembly) Assert.Same(ne1.Assembly, assem1) Dim compilation As VisualBasicCompilation = TrivialCompilation() Dim ne2 As NamespaceExtent = New NamespaceExtent(compilation) Assert.IsType(Of Microsoft.CodeAnalysis.VisualBasic.VisualBasicCompilation)(ne2.Compilation) Assert.Throws(Of InvalidOperationException)(Sub() Dim tmp = ne1.Compilation() End Sub) End Sub Private Function CreateMockSymbol(extent As NamespaceExtent, xel As XElement) As Symbol Dim result As Symbol Dim childSymbols = From childElement In xel.Elements() Select CreateMockSymbol(extent, childElement) Dim name As String = xel.Attribute("name").Value Select Case xel.Name.LocalName Case "ns" result = New MockNamespaceSymbol(name, extent, childSymbols) Case "class" result = New MockNamedTypeSymbol(name, childSymbols, TypeKind.Class) Case Else Throw New ApplicationException("unexpected xml element") End Select For Each child As IMockSymbol In childSymbols child.SetContainer(result) Next Return result End Function Private Sub DumpSymbol(sym As Symbol, builder As StringBuilder, level As Integer) If TypeOf sym Is NamespaceSymbol Then builder.AppendFormat("Namespace {0} [{1}]", sym.Name, DirectCast(sym, NamespaceSymbol).Extent) ElseIf TypeOf sym Is NamedTypeSymbol Then builder.AppendFormat("{0} {1}", DirectCast(sym, NamedTypeSymbol).TypeKind.ToString(), sym.Name) Else Throw New ApplicationException("Unexpected symbol kind") End If If TypeOf sym Is NamespaceOrTypeSymbol AndAlso DirectCast(sym, NamespaceOrTypeSymbol).GetMembers().Any() Then builder.AppendLine(" { ") For Each child As Symbol In (From c In DirectCast(sym, NamespaceOrTypeSymbol).GetMembers().AsEnumerable() Order By c.Name) For i = 0 To level builder.Append(" ") Next DumpSymbol(child, builder, level + 1) builder.AppendLine() Next For i = 0 To level - 1 builder.Append(" ") Next builder.Append("}") End If End Sub Private Function DumpSymbol(sym As Symbol) As String Dim builder As New StringBuilder() DumpSymbol(sym, builder, 0) Return builder.ToString() End Function <Fact> Public Sub TestMergedNamespaces() Dim root1 As NamespaceSymbol = DirectCast(CreateMockSymbol(New NamespaceExtent(New MockAssemblySymbol("Assem1")), <ns name=''> <ns name='A'> <ns name='D'/> <ns name='E'/> <ns name='F'> <ns name='G'/> </ns> </ns> <ns name='B'/> <ns name='C'/> <ns name='U'/> <class name='X'/> </ns>), NamespaceSymbol) Dim root2 As NamespaceSymbol = DirectCast(CreateMockSymbol(New NamespaceExtent(New MockAssemblySymbol("Assem2")), <ns name=''> <ns name='B'> <ns name='K'/> </ns> <ns name='C'/> <class name='X'/> <class name='Y'/> </ns>), NamespaceSymbol) Dim root3 As NamespaceSymbol = DirectCast(CreateMockSymbol(New NamespaceExtent(New MockAssemblySymbol("Assem3")), <ns name=''> <ns name='a'> <ns name='D'/> <ns name='e'> <ns name='H'/> </ns> </ns> <ns name='B'> <ns name='K'> <ns name='L'/> <class name='L'/> </ns> </ns> <class name='Z'/> </ns>), NamespaceSymbol) Dim merged As NamespaceSymbol = MergedNamespaceSymbol.CreateForTestPurposes(New MockAssemblySymbol("Merged"), {root1, root2, root3}) Dim expected As String = <expected>Namespace [Assembly: Merged] { Namespace A [Assembly: Merged] { Namespace D [Assembly: Merged] Namespace E [Assembly: Merged] { Namespace H [Assembly: Assem3] } Namespace F [Assembly: Assem1] { Namespace G [Assembly: Assem1] } } Namespace B [Assembly: Merged] { Namespace K [Assembly: Merged] { Class L Namespace L [Assembly: Assem3] } } Namespace C [Assembly: Merged] Namespace U [Assembly: Assem1] Class X Class X Class Y Class Z }</expected>.Value.Replace(vbLf, Environment.NewLine). Replace("Assembly: Merged", "Assembly: Merged, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"). Replace("Assembly: Assem1", "Assembly: Assem1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"). Replace("Assembly: Assem3", "Assembly: Assem3, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null") Assert.Equal(expected, DumpSymbol(merged)) Dim merged2 As NamespaceSymbol = MergedNamespaceSymbol.CreateForTestPurposes(New MockAssemblySymbol("Merged2"), {root1}) Assert.Same(merged2, root1) End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Text Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class TestSymbols ' Create a trivial compilation with no source or references. Private Function TrivialCompilation() As VisualBasicCompilation Return VisualBasicCompilation.Create("Test") End Function <Fact> Public Sub TestArrayType() Dim compilation As VisualBasicCompilation = TrivialCompilation() Dim elementType As NamedTypeSymbol = New MockNamedTypeSymbol("TestClass", Enumerable.Empty(Of Symbol)) ' this can be any type. Dim ats1 As ArrayTypeSymbol = ArrayTypeSymbol.CreateVBArray(elementType, Nothing, 1, compilation) Assert.Equal(1, ats1.Rank) Assert.Same(elementType, ats1.ElementType) Assert.Equal(SymbolKind.ArrayType, ats1.Kind) Assert.True(ats1.IsReferenceType) Assert.False(ats1.IsValueType) Assert.Equal("TestClass()", ats1.ToString()) Dim ats2 As ArrayTypeSymbol = ArrayTypeSymbol.CreateVBArray(elementType, Nothing, 2, compilation) Assert.Equal(2, ats2.Rank) Assert.Same(elementType, ats2.ElementType) Assert.Equal(SymbolKind.ArrayType, ats2.Kind) Assert.True(ats2.IsReferenceType) Assert.False(ats2.IsValueType) Assert.Equal("TestClass(*,*)", ats2.ToString()) Dim ats3 As ArrayTypeSymbol = ArrayTypeSymbol.CreateVBArray(elementType, Nothing, 3, compilation) Assert.Equal(3, ats3.Rank) Assert.Equal("TestClass(*,*,*)", ats3.ToString()) End Sub <Fact> Public Sub TestMissingMetadataSymbol() Dim missingAssemblyName = New AssemblyIdentity("goo") Dim assem As AssemblySymbol = New MockAssemblySymbol("banana") Dim [module] = New MissingModuleSymbol(assem, -1) Dim container As NamedTypeSymbol = New MockNamedTypeSymbol("TestClass", Enumerable.Empty(Of Symbol), TypeKind.Class) Dim mms1 = New MissingMetadataTypeSymbol.TopLevel(New MissingAssemblySymbol(missingAssemblyName).Modules(0), "Elvis", "Lives", 2, True) Assert.Equal(2, mms1.Arity) Assert.Equal("Elvis", mms1.NamespaceName) Assert.Equal("Lives", mms1.Name) Assert.Equal("Elvis.Lives(Of ,)[missing]", mms1.ToTestDisplayString()) Assert.Equal("goo", mms1.ContainingAssembly.Identity.Name) Dim mms2 = New MissingMetadataTypeSymbol.TopLevel([module], "Elvis.Is", "Cool", 0, True) Assert.Equal(0, mms2.Arity) Assert.Equal("Elvis.Is", mms2.NamespaceName) Assert.Equal("Cool", mms2.Name) Assert.Equal("Elvis.Is.Cool[missing]", mms2.ToTestDisplayString()) Assert.Same(assem, mms2.ContainingAssembly) ' TODO: Add test for 3rd constructor. End Sub <Fact> Public Sub TestNamespaceExtent() Dim assem1 As AssemblySymbol = New MockAssemblySymbol("goo") Dim ne1 As NamespaceExtent = New NamespaceExtent(assem1) Assert.Equal(ne1.Kind, NamespaceKind.Assembly) Assert.Same(ne1.Assembly, assem1) Dim compilation As VisualBasicCompilation = TrivialCompilation() Dim ne2 As NamespaceExtent = New NamespaceExtent(compilation) Assert.IsType(Of Microsoft.CodeAnalysis.VisualBasic.VisualBasicCompilation)(ne2.Compilation) Assert.Throws(Of InvalidOperationException)(Sub() Dim tmp = ne1.Compilation() End Sub) End Sub Private Function CreateMockSymbol(extent As NamespaceExtent, xel As XElement) As Symbol Dim result As Symbol Dim childSymbols = From childElement In xel.Elements() Select CreateMockSymbol(extent, childElement) Dim name As String = xel.Attribute("name").Value Select Case xel.Name.LocalName Case "ns" result = New MockNamespaceSymbol(name, extent, childSymbols) Case "class" result = New MockNamedTypeSymbol(name, childSymbols, TypeKind.Class) Case Else Throw New ApplicationException("unexpected xml element") End Select For Each child As IMockSymbol In childSymbols child.SetContainer(result) Next Return result End Function Private Sub DumpSymbol(sym As Symbol, builder As StringBuilder, level As Integer) If TypeOf sym Is NamespaceSymbol Then builder.AppendFormat("Namespace {0} [{1}]", sym.Name, DirectCast(sym, NamespaceSymbol).Extent) ElseIf TypeOf sym Is NamedTypeSymbol Then builder.AppendFormat("{0} {1}", DirectCast(sym, NamedTypeSymbol).TypeKind.ToString(), sym.Name) Else Throw New ApplicationException("Unexpected symbol kind") End If If TypeOf sym Is NamespaceOrTypeSymbol AndAlso DirectCast(sym, NamespaceOrTypeSymbol).GetMembers().Any() Then builder.AppendLine(" { ") For Each child As Symbol In (From c In DirectCast(sym, NamespaceOrTypeSymbol).GetMembers().AsEnumerable() Order By c.Name) For i = 0 To level builder.Append(" ") Next DumpSymbol(child, builder, level + 1) builder.AppendLine() Next For i = 0 To level - 1 builder.Append(" ") Next builder.Append("}") End If End Sub Private Function DumpSymbol(sym As Symbol) As String Dim builder As New StringBuilder() DumpSymbol(sym, builder, 0) Return builder.ToString() End Function <Fact> Public Sub TestMergedNamespaces() Dim root1 As NamespaceSymbol = DirectCast(CreateMockSymbol(New NamespaceExtent(New MockAssemblySymbol("Assem1")), <ns name=''> <ns name='A'> <ns name='D'/> <ns name='E'/> <ns name='F'> <ns name='G'/> </ns> </ns> <ns name='B'/> <ns name='C'/> <ns name='U'/> <class name='X'/> </ns>), NamespaceSymbol) Dim root2 As NamespaceSymbol = DirectCast(CreateMockSymbol(New NamespaceExtent(New MockAssemblySymbol("Assem2")), <ns name=''> <ns name='B'> <ns name='K'/> </ns> <ns name='C'/> <class name='X'/> <class name='Y'/> </ns>), NamespaceSymbol) Dim root3 As NamespaceSymbol = DirectCast(CreateMockSymbol(New NamespaceExtent(New MockAssemblySymbol("Assem3")), <ns name=''> <ns name='a'> <ns name='D'/> <ns name='e'> <ns name='H'/> </ns> </ns> <ns name='B'> <ns name='K'> <ns name='L'/> <class name='L'/> </ns> </ns> <class name='Z'/> </ns>), NamespaceSymbol) Dim merged As NamespaceSymbol = MergedNamespaceSymbol.CreateForTestPurposes(New MockAssemblySymbol("Merged"), {root1, root2, root3}) Dim expected As String = <expected>Namespace [Assembly: Merged] { Namespace A [Assembly: Merged] { Namespace D [Assembly: Merged] Namespace E [Assembly: Merged] { Namespace H [Assembly: Assem3] } Namespace F [Assembly: Assem1] { Namespace G [Assembly: Assem1] } } Namespace B [Assembly: Merged] { Namespace K [Assembly: Merged] { Class L Namespace L [Assembly: Assem3] } } Namespace C [Assembly: Merged] Namespace U [Assembly: Assem1] Class X Class X Class Y Class Z }</expected>.Value.Replace(vbLf, Environment.NewLine). Replace("Assembly: Merged", "Assembly: Merged, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"). Replace("Assembly: Assem1", "Assembly: Assem1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"). Replace("Assembly: Assem3", "Assembly: Assem3, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null") Assert.Equal(expected, DumpSymbol(merged)) Dim merged2 As NamespaceSymbol = MergedNamespaceSymbol.CreateForTestPurposes(New MockAssemblySymbol("Merged2"), {root1}) Assert.Same(merged2, root1) End Sub End Class End Namespace
-1